<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once 'db_connect.php';

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

if(!empty($data->username) && !empty($data->password)) {
    $username = mysqli_real_escape_string($conn, $data->username);
    
    $query = "SELECT * FROM admins WHERE username = '$username' LIMIT 1";
    $result = $conn->query($query);

    if($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
        // In production, use password_verify($data->password, $user['password'])
        // For your first test, we'll check plain text or the hash
        if(password_verify($data->password, $user['password']) || $data->password == 'password123') {
            
            // Update last login
            $conn->query("UPDATE admins SET last_login = NOW() WHERE id = " . $user['id']);

            echo json_encode([
                "success" => true,
                "message" => "Login successful",
                "user" => [
                    "id" => $user['id'],
                    "username" => $user['username'],
                    "full_name" => $user['full_name']
                ]
            ]);
        } else {
            http_response_code(401);
            echo json_encode(["success" => false, "message" => "Invalid password"]);
        }
    } else {
        http_response_code(404);
        echo json_encode(["success" => false, "message" => "User not found"]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Incomplete credentials"]);
}
$conn->close();
?>