<?php
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");

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

include('unified_config.php');

$data = json_decode(file_get_contents("php://input"), true);

$email = $data['email'] ?? '';
$password = $data['password'] ?? '';

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

$stmt = $conn->prepare("SELECT * FROM loginusers WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && $password === $user['password']) { // ✅ plain text comparison
    session_start();
    $_SESSION['clogin'] = $user['email']; // save session
    
    // ------------------
    // Send login alert email
    // ------------------
    if (EMAIL_AUTOMATION_ENABLED && LOGIN_ALERT_ENABLED) {
        $mailSystem = getMailSystem();
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $fullName = $user['first_name'] . ' ' . $user['last_name'];
        
        $emailResult = $mailSystem->sendLoginAlert($user['email'], $fullName, $ipAddress, $userAgent);
        
        // Log email result
        if (!$emailResult['success']) {
            error_log("Failed to send login alert to {$user['email']}: " . $emailResult['message']);
        }
    }
    
    echo json_encode([
        "success" => true,
        "message" => "Login successful",
        "user" => [
            "id" => $user['id'],
            "email" => $user['email'],
            "first_name" => $user['first_name'],
            "last_name" => $user['last_name']
        ]
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Invalid credentials"]);
}
?>
