<?php
require_once 'db.php'; // Include database connection

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

$response = array();

try {
    // Handle preflight requests
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        // Just send the headers and exit, no need to process further
        http_response_code(200);
        exit();
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = json_decode(file_get_contents("php://input"), true);
        $username = $data['username'];
        $password = $data['password'];

        $stmt = $conn->prepare("SELECT * FROM admin_users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            // Verify password
            if (password_verify($password, $user['password'])) {
                $response['success'] = true;
                $response['message'] = 'Login successful';
                // You can also include more data if needed, like a session token
            } else {
                $response['success'] = false;
                $response['message'] = 'Invalid password';
            }
        } else {
            $response['success'] = false;
            $response['message'] = 'Invalid username';
        }
    } else {
        http_response_code(405); // Method Not Allowed
        $response['error'] = 'Method not allowed';
    }
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    $response['error'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
