    <?php
    // Allow any origin (for development only)
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type");

    // Handle preflight requests (OPTIONS)
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit();
    }

    session_start();
    header("Content-Type: application/json");
    include '../../dbcon.php';

    $data = json_decode(file_get_contents("php://input"), true);
    $email = mysqli_real_escape_string($conn, $data['email'] ?? '');
    $password = $data['password'] ?? '';

    if (!$email || !$password) {
        echo json_encode(["status" => "error", "message" => "Email and password required"]);
        exit;
    }

    // Fetch user
    $result = mysqli_query($conn, "
        SELECT u.*, r.role_name 
        FROM users u 
        JOIN roles r ON u.role_id = r.id 
        WHERE u.email = '$email' LIMIT 1
    ");

    if (mysqli_num_rows($result) === 1) {
        $user = mysqli_fetch_assoc($result);

        if ($user['status'] === 'blocked') {
            echo json_encode(["status" => "error", "message" => "Account is blocked"]);
            exit;
        }

        if (password_verify($password, $user['password'])) {
            // Update user status
            mysqli_query($conn, "UPDATE users SET status='active' WHERE id='{$user['id']}'");

            // Store full user info in session
            $_SESSION['user'] = [
                "id" => $user['id'],
                "role" => $user['role_name'],
                "full_name" => $user['full_name'],
                "email" => $user['email'],
                "phone" => $user['phone'],
                "country" => $user['country'],
                "status" => "active"
            ];

            echo json_encode([
                "status" => "success",
                "message" => "Login successful",
                "user" => $_SESSION['user']
            ]);
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid password"]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "User not found"]);
    }
    ?>