<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

include "config.php"; // your DB connection
include "mail_system.php"; // Include mail system

$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_verify($password, $user['password'])) {
    session_start();
    $_SESSION['clogin'] = $user['email']; // ✅ save session
    
    // Get user info for login alert
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $device = getBrowserInfo($user_agent); // Helper function to parse user agent
    $login_time = date('Y-m-d H:i:s');
    $full_name = $user['first_name'] . " " . $user['last_name'];
    
    // Log the login attempt
    $log_stmt = $conn->prepare("INSERT INTO login_logs (user_id, ip_address, user_agent, login_time) VALUES (?, ?, ?, ?)");
    $log_stmt->bind_param("isss", $user['id'], $ip_address, $user_agent, $login_time);
    $log_stmt->execute();
    $log_stmt->close();
    
    // Send login alert email (async to not slow down login)
    $mailer = new ZForexMailer();
    $mail_result = $mailer->sendLoginAlert($email, $full_name, $login_time, $ip_address, $device);
    
    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']
        ],
        "login_alert_sent" => $mail_result['success']
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Invalid credentials"]);
}

$stmt->close();
$conn->close();

// Helper function to parse user agent
function getBrowserInfo($user_agent) {
    $browser = "Unknown Browser";
    $os = "Unknown OS";
    
    // Detect browser
    if (strpos($user_agent, 'Chrome') !== false) {
        $browser = "Chrome";
    } elseif (strpos($user_agent, 'Firefox') !== false) {
        $browser = "Firefox";
    } elseif (strpos($user_agent, 'Safari') !== false) {
        $browser = "Safari";
    } elseif (strpos($user_agent, 'Edge') !== false) {
        $browser = "Edge";
    }
    
    // Detect OS
    if (strpos($user_agent, 'Windows') !== false) {
        $os = "Windows";
    } elseif (strpos($user_agent, 'Mac') !== false) {
        $os = "macOS";
    } elseif (strpos($user_agent, 'Linux') !== false) {
        $os = "Linux";
    } elseif (strpos($user_agent, 'Android') !== false) {
        $os = "Android";
    } elseif (strpos($user_agent, 'iOS') !== false) {
        $os = "iOS";
    }
    
    return $browser . " on " . $os;
}
?>