<?php
ini_set('display_errors', 0);
error_reporting(0);
header("Content-Type: application/json");

// Read raw POST data
$rawData = file_get_contents("php://input");
$data = json_decode($rawData, true);

// 頎巾垂 Capture raw input (debug)
//file_put_contents("log.txt", $rawData . PHP_EOL, FILE_APPEND);

// Validate input
if (!isset($data["emailOrPhone"]) || !isset($data["password"])) {
    echo json_encode([
        "success" => false,
        "message" => "Missing required fields"
    ]);
    exit;
}

$emailOrPhone = trim($data["emailOrPhone"]);
$password1 = trim($data["password"]);
$pass = md5($password1); // 鈿狅笍 Using MD5 (not secure, but matches DB)

require('dbcon.php'); // must define $pdo

try {
    // 頎巾垂 Secure prepared statement
    $sql = $pdo->prepare("SELECT id, name, email, acc_pin, transaction_pin, password 
                          FROM users 
                          WHERE (email = :emailOrPhone OR phone = :emailOrPhone) 
                          LIMIT 1");
    $sql->execute([":emailOrPhone" => $emailOrPhone]);
    
    $num=$sql->rowCount();
    

    $user = $sql->fetch(PDO::FETCH_ASSOC);
file_put_contents("log.txt", $pass  . PHP_EOL, FILE_APPEND);

    if ($user) {
   
        if ($pass === $user["password"]) { // compare MD5 hashes

            unset($user["password"]); // don鈥檛 return password
            echo json_encode([
                "success" => true,
                "message" => "Login successful",
                "user" => $user
            ]);
        } else {
        //file_put_contents("log.txt", "57688" . PHP_EOL, FILE_APPEND);
        	
            echo json_encode([
                "success" => false,
                "message" => "Invalid email/phone or password"
            ]);
        }
    } else {
        echo json_encode([
            "success" => false,
            "message" => "User not found"
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Database error: " . $e->getMessage()
    ]);
}
