<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once __DIR__ . '/../../config.php';

$json = file_get_contents('php://input');
$data = json_decode($json);

if (!$data || !isset($data->identifier) || !isset($data->password)) {
    echo json_encode(["success" => false, "message" => "Invalid request data."]);
    exit;
}

$identifier = trim($data->identifier);
$password   = (string)$data->password;

try {
    // Fetch user by username or email ONLY (do not filter by password here)
    $stmt = $pdo->prepare("SELECT * FROM Users WHERE (Username = ? OR Email = ?) LIMIT 1");
    $stmt->execute([$identifier, $identifier]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

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

    $stored = $user['PasswordHash'];

    $valid = false;

    // 1) First, try password_verify (for properly hashed passwords)
    // password_verify() automatically understands hashes created with password_hash().[web:10][web:18]
    if (!empty($stored) && password_verify($password, $stored)) {
        $valid = true;

        // Optional: if hash is outdated, rehash and update. [web:12][web:16]
        if (password_needs_rehash($stored, PASSWORD_DEFAULT)) {
            $newHash = password_hash($password, PASSWORD_DEFAULT);
            $upd = $pdo->prepare("UPDATE Users SET PasswordHash = ? WHERE Id = ?");
            $upd->execute([$newHash, $user['Id']]);
        }

    } else {
        // 2) Legacy: stored value is plain text, compare directly
        if ($password === $stored) {
            $valid = true;

            // Immediately upgrade to a secure hash
            $newHash = password_hash($password, PASSWORD_DEFAULT); // bcrypt/argon2 via PASSWORD_DEFAULT.[web:10][web:17]
            $upd = $pdo->prepare("UPDATE Users SET PasswordHash = ? WHERE Id = ?");
            $upd->execute([$newHash, $user['Id']]);
        }
    }

    if (!$valid) {
        echo json_encode(["success" => false, "message" => "Incorrect password."]);
        exit;
    }

    // Check web access flag
    if ((int)$user['AllowWebAccess'] !== 1) {
        echo json_encode(["success" => false, "message" => "Web access denied for this account."]);
        exit;
    }

    echo json_encode([
        "success" => true,
        "user" => [
            "FullName" => $user['FullName'],
            "Role"     => $user['Role'],
            "Username" => $user['Username']
        ]
    ]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Server error occurred."]);
}
