<?php
// Ensure no output before this
session_start();
include_once 'config/database.php';
include_once 'includes/functions.php';

// Set headers first
header('Content-Type: application/json');

// Enable error logging but don't display to users
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

try {
    $database = new Database();
    $db = $database->getConnection();

    // Get JSON input
    $json = file_get_contents('php://input');
    $input = json_decode($json, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Invalid JSON input");
    }

    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    $remember = $input['remember'] ?? 0;

    if (empty($username) || empty($password)) {
        throw new Exception("Username and password are required.");
    }

    $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password'])) {
        // Record failed login history if we have a valid user
        if ($user && function_exists('recordLoginHistory')) {
            recordLoginHistory($db, $user['id'], false);
        }
        logLoginAttempt($db, $username, false);
        throw new Exception("Invalid username or password.");
    }

    if ($user['status'] !== 'active') {
        throw new Exception('Account is not active. Please contact support.');
    }

    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
    $_SESSION['auth_step'] = 'pin';
    
    // Update last login time
    $update_stmt = $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
    $update_stmt->execute([$user['id']]);
    
    // Debug logging for last_login update
    $check_stmt = $db->prepare("SELECT last_login FROM users WHERE id = ?");
    $check_stmt->execute([$user['id']]);
    $last_login = $check_stmt->fetchColumn();
    error_log("Updated last_login for user {$user['id']} to: " . ($last_login ?? 'NULL'));
    
    // Record successful login history
    if (function_exists('recordLoginHistory')) {
        recordLoginHistory($db, $user['id'], true);
    }
    logLoginAttempt($db, $username, true, $user['id']);

    if ($remember) {
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
        $stmt = $db->prepare("INSERT INTO remember_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$user['id'], $token, $expires]);
        setcookie('remember_token', $token, strtotime('+30 days'), '/', '', true, true);
    }

    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'redirect' => 'pin-verification.php'
    ]);
    exit;

} catch (Exception $e) {
    error_log("Login error: " . $e->getMessage());
    http_response_code(400); // Bad Request
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
    exit;
}
