<?php
require __DIR__ . '/config.php';

header('Content-Type: application/json');

$conn = getDbConnection();
$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['username'], $data['password'])) {
    echo json_encode(["success" => false, "status" => "error", "message" => "Invalid input"]);
    exit();
}

$username = trim($data['username']);
$password = $data['password'];

$stmt = $conn->prepare("SELECT user_id, password, token FROM users WHERE username = ? AND is_active = 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password'])) {
    if (empty($user['token'])) {
        $user['token'] = bin2hex(random_bytes(32));
        $updateStmt = $conn->prepare("UPDATE users SET token = ? WHERE user_id = ?");
        $updateStmt->bind_param("si", $user['token'], $user['user_id']);
        $updateStmt->execute();
    }

    echo json_encode([
        "success" => true, 
        "status" => "success",  // ✅ Ensure "status" field is included
        "message" => "Login successful",
        "token" => $user['token']
    ]);
} else {
    echo json_encode([
        "success" => false, 
        "status" => "error", 
        "message" => "Invalid credentials or inactive account"
    ]);
}

$conn->close();
?>
