<?php
// Suppress deprecation warnings for cleaner JSON output
error_reporting(E_ALL & ~E_DEPRECATED);

require_once '../config/database.php';

// Check if this is an AJAX request
$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

// Only set JSON header for AJAX requests
if ($is_ajax) {
    header('Content-Type: application/json');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    } else {
        header('Location: ../login.php?error=method_not_allowed');
    }
    exit;
}

$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$remember_me = isset($_POST['remember_me']) ? true : false;

if (empty($username) || empty($password)) {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'KSO ID/Username and password are required']);
    } else {
        header('Location: ../login.php?error=missing_credentials');
    }
    exit;
}

try {
    $pdo = getDBConnection();
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Check if IP is blocked (rate limiting)
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as failed_attempts 
        FROM activity_logs 
        WHERE ip_address = ? 
        AND action = 'login_failed' 
        AND created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
    ");
    $stmt->execute([$ip_address]);
    $ip_attempts = $stmt->fetch()['failed_attempts'];
    
    if ($ip_attempts >= 5) {
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => 'Too many failed attempts. Please try again later.']);
        } else {
            header('Location: ../login.php?error=too_many_attempts');
        }
        exit;
    }
    
    // Find admin by username, email, or KSO ID
    $stmt = $pdo->prepare("SELECT * FROM admins WHERE (username = ? OR email = ? OR kso_id = ?) AND status = 'active'");
    $stmt->execute([$username, $username, $username]);
    $admin = $stmt->fetch();
    
    if (!$admin) {
        // Log failed login attempt
        $stmt = $pdo->prepare("
            INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent, created_at) 
            VALUES (NULL, 'login_failed', 'Invalid login credentials: ' . ?, ?, ?, NOW())
        ");
        $stmt->execute([$username, $ip_address, $user_agent]);
        
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => 'Invalid KSO ID, username, or password']);
        } else {
            header('Location: ../login.php?error=invalid_credentials');
        }
        exit;
    }
    
    // Check if account is locked
    if ($admin['locked_until'] && new DateTime($admin['locked_until']) > new DateTime()) {
        $locked_until = new DateTime($admin['locked_until']);
        $remaining_time = $locked_until->diff(new DateTime())->format('%i minutes');
        
        echo json_encode([
            'success' => false, 
            'message' => "Account is locked. Try again in {$remaining_time}."
        ]);
        exit;
    }
    
    if (password_verify($password, $admin['password_hash'])) {
        // Reset login attempts and unlock account
        $stmt = $pdo->prepare("
            UPDATE admins 
            SET login_attempts = 0, 
                locked_until = NULL, 
                last_login = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$admin['id']]);
        
        // Set session variables
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_username'] = $admin['username'];
        $_SESSION['admin_role'] = $admin['role'];
        $_SESSION['admin_name'] = $admin['first_name'] . ' ' . $admin['last_name'];
        $_SESSION['admin_permissions'] = !empty($admin['permissions']) ? json_decode($admin['permissions'], true) : [];
        
        // Set remember me cookie if requested
        if ($remember_me) {
            $token = bin2hex(random_bytes(32));
            $expires = time() + (30 * 24 * 60 * 60); // 30 days
            
            setcookie('remember_token', $token, $expires, '/', '', true, true);
            
            // TODO: Store token in database when admin_sessions table is created
            // For now, we'll just set the cookie without database storage
            error_log("Remember me token set but admin_sessions table not available for storage");
        }
        
        // Log successful login
        $stmt = $pdo->prepare("
            INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent, created_at) 
            VALUES (?, 'login', 'Admin login successful', ?, ?, NOW())
        ");
        $stmt->execute([$admin['id'], $ip_address, $user_agent]);
        
        if ($is_ajax) {
            echo json_encode([
                'success' => true, 
                'message' => 'Login successful',
                'redirect' => 'index.php',
                'admin_name' => $admin['first_name'] . ' ' . $admin['last_name'],
                'admin_role' => $admin['role']
            ]);
        } else {
            // For normal form submission, redirect to dashboard
            header('Location: ../index.php');
            exit;
        }
    } else {
        // Increment login attempts
        $new_attempts = $admin['login_attempts'] + 1;
        $lock_account = false;
        $locked_until = null;
        
        // Lock account after 5 failed attempts
        if ($new_attempts >= 5) {
            $lock_account = true;
            $locked_until = date('Y-m-d H:i:s', time() + (15 * 60)); // Lock for 15 minutes
        }
        
        $stmt = $pdo->prepare("
            UPDATE admins 
            SET login_attempts = ?, 
                locked_until = ? 
            WHERE id = ?
        ");
        $stmt->execute([$new_attempts, $locked_until, $admin['id']]);
        
        // Log failed login attempt
        $stmt = $pdo->prepare("
            INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent, created_at) 
            VALUES (?, 'login_failed', 'Invalid password attempt', ?, ?, NOW())
        ");
        $stmt->execute([$admin['id'], $ip_address, $user_agent]);
        
        $message = 'Invalid username or password';
        if ($lock_account) {
            $message = 'Account locked due to multiple failed attempts. Try again in 15 minutes.';
        } elseif ($new_attempts >= 3) {
            $remaining_attempts = 5 - $new_attempts;
            $message = "Invalid password. {$remaining_attempts} attempts remaining before account lock.";
        }
        
        echo json_encode(['success' => false, 'message' => $message]);
    }
} catch (Exception $e) {
    // Log system error
    error_log("Login system error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Login system temporarily unavailable']);
}
?>
