<?php
header("Content-Type: application/json");
require('dbcon.php');

// Read input ONCE
$rawInput = file_get_contents("php://input");
//file_put_contents("log.txt", $rawInput . PHP_EOL, FILE_APPEND);

// Decode JSON
$data = json_decode($rawInput, true);

$emailOrPhone = isset($data['emailOrPhone']) ? trim($data['emailOrPhone']) : '';


if ($emailOrPhone === "") {
    echo json_encode([
        "success" => false,
        "message" => "No identifier given"
    ]);
    exit;
}

try {
    // ✅ Proper prepared statement
    $stmt = $pdo->prepare(
        "SELECT * FROM users WHERE email = '$emailOrPhone' OR phone = '$emailOrPhone' LIMIT 1"
    );

    $stmt->execute([$emailOrPhone, $emailOrPhone]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Log properly
    //file_put_contents("log.txt", json_encode($user) . PHP_EOL, FILE_APPEND);

    if ($user) {
        echo json_encode([
            "success" => true,
            "user" => $user
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "User not found"
        ]);
    }

} catch (PDOException $e) {
    echo json_encode([
        "success" => false,
        "message" => "Database error"
    ]);
}
