<?php
// ✅ Debugging (Remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ Headers
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 DB Connection
include_once __DIR__ . '/../config.php'; // adjust path correctly

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

    $stmt = $conn->prepare("
        INSERT INTO login_activity (uid, email, role, action, success, ip, user_agent)
        VALUES (?, ?, 'admin', ?, ?, ?, ?)
    ");
    if ($stmt) {
        $stmt->bind_param("sssiss", $uid, $email, $action, $success, $ip, $user_agent);
        if (!$stmt->execute()) {
            error_log("SQL Error: " . $stmt->error);
        }
    } else {
        error_log("Prepare failed: " . $conn->error);
    }
}

$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);

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

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

        if ($user['password'] === $password) {
            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_admin_activity($conn, $user['uid'], $email, 'login', 0);
            $response = ["success" => false, "message" => "Incorrect password"];
        }
    } else {
        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);
