<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php';
header('Content-Type: application/json');

try {
    $email = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($email) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
        exit;
    }

    // ✅ Fetch user info
    $stmt = $pdo->prepare("
        SELECT id, fullname, email, password, is_verified, 
               last_login, last_ip, device, current_login
        FROM users 
        WHERE email = ?
    ");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => 'No account found with this email.']);
        exit;
    }

    if (!password_verify($password, $user['password'])) {
        echo json_encode(['status' => 'error', 'message' => 'Incorrect password.']);
        exit;
    }

    if (!$user['is_verified']) {
        echo json_encode([
            'status' => 'unverified',
            'message' => 'Your account has not been verified.',
            'email' => $email
        ]);
        exit;
    }

    // ✅ Get user IP, device, and current time
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown IP';
    $device = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown Device';
    $current_login = date('Y-m-d H:i:s');

    // ✅ Move current_login to last_login, then update new current_login
    $update = $pdo->prepare("
        UPDATE users 
        SET last_login = current_login, 
            current_login = ?, 
            last_ip = ?, 
            device = ?
        WHERE id = ?
    ");
    $update->execute([$current_login, $ip, $device, $user['id']]);

    // ✅ Store session data (use updated last_login from before)
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['fullname'] = $user['fullname'];
    $_SESSION['last_login'] = $user['current_login'] ?? 'First login'; // show previous session login time
    $_SESSION['device'] = $device;
    $_SESSION['last_ip'] = $ip;

    echo json_encode([
        'status' => 'success',
        'message' => 'Login successful! Redirecting...'
    ]);
    exit;

} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
    exit;
}
