<?php
// Strict JSON + CORS
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// -------- Debug-safe error logging (no display in browser) --------
ini_set('display_errors', '0');
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}
// Turn mysqli errors into Exceptions (so we can catch them)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    // 1) Load config (must define db() or $conn)
    require_once __DIR__ . '/unified_config.php';

    // Accept either a function db(): mysqli OR a $conn = new mysqli(...)
    if (function_exists('db')) {
        $conn = db();
    } elseif (isset($conn) && $conn instanceof mysqli) {
        // ok
    } else {
        throw new Exception("Database connection not provided. Ensure unified_config.php defines db() or \$conn.");
    }

    // ===== ADD THIS FUNCTION HERE =====
    function log_client_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 (?, ?, 'client', ?, ?, ?, ?)
        ");
        $stmt->bind_param("ississ", $uid, $email, $action, $success, $ip, $user_agent);
        $stmt->execute();
    }
    // ===== END FUNCTION =====

    // 2) Read JSON body
    $raw = file_get_contents("php://input");
    if ($raw === false || $raw === '') {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Empty request body"]);
        exit;
    }
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Invalid JSON"]);
        exit;
    }

    $email    = trim($data['email'] ?? '');
    $password = (string)($data['password'] ?? '');
    $token    = isset($data['token']) ? trim((string)$data['token']) : ''; // optional

    if ($email === '' || $password === '') {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Missing fields"]);
        exit;
    }

    // 3) Query user (also fetch email verification fields)
    $stmt = $conn->prepare("
        SELECT id, email, first_name, last_name, password, emailToken, email_confirmed, suspend
        FROM loginusers
        WHERE email = ?
        LIMIT 1
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res  = $stmt->get_result();
    $user = $res->fetch_assoc();

    // 4a) Basic password check (plain text for now; recommend password_hash later)
    $ok = $user && ($password === (string)$user['password']);

    // ===== LOG FAILED LOGIN ATTEMPT =====
    if (!$ok) {
        log_client_activity($conn, $user['id'] ?? null, $email, 'login', 0);
        http_response_code(401);
        echo json_encode(["success" => false, "message" => "Invalid credentials"]);
        exit;
    }

    // 4b) Check if client is suspended
    if ((int)$user['suspend'] === 1) {
        log_client_activity($conn, $user['id'], $email, 'login', 0); // log suspended attempt
        http_response_code(403);
        echo json_encode([
            "success" => false,
            "message" => "Your account has been suspended. Please contact support."
        ]);
        exit;
    }

    // 5) Email verification gate
    if ((int)$user['email_confirmed'] === 0) {
        if ($token !== '' && hash_equals((string)$user['emailToken'], $token)) {
            $upd = $conn->prepare("
                UPDATE loginusers
                SET email_confirmed = 1, emailToken = NULL
                WHERE id = ?
                LIMIT 1
            ");
            $uid = (int)$user['id'];
            $upd->bind_param("i", $uid);
            $upd->execute();
            $user['email_confirmed'] = 1;
            $user['emailToken'] = null;
        } else {
            log_client_activity($conn, $user['id'], $email, 'login', 0); // log unverified attempt
            http_response_code(403);
            echo json_encode([
                "success"      => false,
                "message"      => "Please verify your email before logging in.",
                "needs_verify" => true,
                "hint"         => "If you have a verification token, include it as 'token' in the request."
            ]);
            exit;
        }
    }

    // 6) Proceed with login (session + optional email alert)
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    $_SESSION['clogin'] = $user['email'];

    // ===== LOG SUCCESSFUL LOGIN =====
    log_client_activity($conn, $user['id'], $email, 'login', 1);

    // Optional: send login alert (no changes here)
    $EMAIL_AUTOMATION_ENABLED = defined('EMAIL_AUTOMATION_ENABLED') ? EMAIL_AUTOMATION_ENABLED : false;
    $LOGIN_ALERT_ENABLED      = defined('LOGIN_ALERT_ENABLED') ? LOGIN_ALERT_ENABLED : false;

    if ($EMAIL_AUTOMATION_ENABLED && $LOGIN_ALERT_ENABLED && function_exists('getMailSystem')) {
        try {
            $mailSystem = getMailSystem();
            if (is_object($mailSystem) && method_exists($mailSystem, 'sendLoginAlert')) {
                $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
                $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
                $fullName  = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
                $emailResult = $mailSystem->sendLoginAlert($user['email'], $fullName, $ipAddress, $userAgent);
                if (!(is_array($emailResult) && ($emailResult['success'] ?? false))) {
                    error_log("Login alert mail failed for {$user['email']}: " . ($emailResult['message'] ?? 'unknown error'));
                }
            } else {
                error_log("getMailSystem() did not return a valid mailer with sendLoginAlert().");
            }
        } catch (Throwable $e) {
            error_log("Login alert exception: " . $e->getMessage());
        }
    }

    echo json_encode([
        "success" => true,
        "message" => "Login successful",
        "user" => [
            "id"             => (int)$user['id'],
            "email"          => $user['email'],
            "first_name"     => $user['first_name'] ?? '',
            "last_name"      => $user['last_name'] ?? '',
            "email_confirmed"=> (int)$user['email_confirmed']
        ]
    ]);
    exit;

} catch (Throwable $e) {
    error_log("LOGIN_FATAL: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Server error"]);
    exit;
}
