<?php
// backend/api/login.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. Trim spaces (Bahut important hai)
    $account_id = isset($_POST['account_id']) ? trim($_POST['account_id']) : '';
    $password   = isset($_POST['password']) ? $_POST['password'] : '';

    if (empty($account_id) || empty($password)) {
        echo "Error: Please enter both Account ID and Password!";
        exit;
    }

    // 2. SQL injection se bachne ke liye escape karein
    $safe_account_id = mysqli_real_escape_string($conn, $account_id);

    // 3. User ko dhoondne ki query
    $query = "SELECT * FROM users WHERE account_id = '$safe_account_id' LIMIT 1";
    $result = mysqli_query($conn, $query);
    
    // DEBUGGING: Agar ID nahi mil rahi, toh check karein table mein data hai ya nahi
    if (!$result) {
        echo "Error in Database Query: " . mysqli_error($conn);
        exit;
    }

    if (mysqli_num_rows($result) === 0) {
        // Agar yahan error aata hai, toh check karein ki DB mein 180139 hi likha hai ya kuch aur
        echo "Error: Account ID ($account_id) not found in our records!";
        exit;
    }

    $user = mysqli_fetch_assoc($result);
    $db_password = $user['password'];
    $is_valid = false;

    // 4. Password Check (Secure + Plain Text Support)
    if (strpos($db_password, '$2y$') === 0) {
        if (password_verify($password, $db_password)) {
            $is_valid = true;
        }
    } else {
        if ($password === $db_password) {
            $is_valid = true;
        }
    }

    if ($is_valid) {
        echo "Success:" . $user['wallet'] . ":" . $user['account_id'];
    } else {
        echo "Error: Incorrect Password!";
    }

} else {
    echo "Error: Invalid Request Method";
}
?>