<?php
// ✅ Headers for CORS and JSON
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, Authorization");

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

// Include database connection
include_once 'config.php'; // make sure this file contains $conn = new mysqli(...);

$response = ["success" => false, "message" => "Invalid request"];

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

if (isset($data->email) && isset($data->password)) {
    $email = $conn->real_escape_string($data->email);
    $password = $conn->real_escape_string($data->password);

    // Check if user exists
    $sql = "SELECT * FROM adminlogins WHERE email='$email' LIMIT 1";
    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();

        // Check password (if storing plain text, compare directly; otherwise use password_verify for hashed passwords)
        if ($user['password'] === $password) {
            // Login success
            $response = [
                "success" => true,
                "message" => "Login successful",
                "data" => [
                    "username" => $user['username'],
                    "email" => $user['email'],
                    "uid" => $user['uid'],
                    "empId" => $user['empId'],
                    "userRole" => $user['userRole'],
                    "userDepartment" => $user['userDepartment'],
                    "userAccessLevel" => $user['userAccessLevel']
                ]
            ];
        } else {
            $response = ["success" => false, "message" => "Incorrect password"];
        }
    } else {
        $response = ["success" => false, "message" => "Email not found"];
    }
} else {
    $response = ["success" => false, "message" => "Email and password required"];
}





echo json_encode($response);
