<?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(...);

// ===== ADD THIS FUNCTION =====
function log_admin_activity($conn, $uid, $email, $action, $success = 1) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

    $stmt = $conn->prepare("
        INSERT INTO login_activity (uid, email, role, action, success, ip, user_agent)
        VALUES (?, ?, 'admin', ?, ?, ?, ?)
    ");
    $stmt->bind_param("ississ", $uid, $email, $action, $success, $ip, $user_agent);
    $stmt->execute();
}
// ===== END FUNCTION =====

$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 (plain text for now)
        if ($user['password'] === $password) {
            // ===== LOG SUCCESSFUL LOGIN =====
            log_admin_activity($conn, $user['uid'], $email, 'login', 1);

            $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 {
            // ===== LOG FAILED LOGIN =====
            log_admin_activity($conn, $user['uid'], $email, 'login', 0);

            $response = ["success" => false, "message" => "Incorrect password"];
        }
    } else {
        // ===== LOG FAILED LOGIN (email not found) =====
        log_admin_activity($conn, null, $email, 'login', 0);

        $response = ["success" => false, "message" => "Email not found"];
    }
} else {
    $response = ["success" => false, "message" => "Email and password required"];
}

echo json_encode($response);
