<?php
/**
 * Login Processing Script
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include configuration
require_once 'config/config.php';

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('index.php', 'Invalid request method', 'error');
}

// Verify CSRF token
if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
    redirect('index.php', 'Invalid security token', 'error');
}

// Get form data
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

// Validate input
if (empty($username) || empty($password)) {
    redirect('index.php', 'Please enter username and password', 'error');
}

// Get database connection
$pdo = getDBConnection();
if (!$pdo) {
    error_log("Login failed: Database connection error");
    redirect('index.php', 'System error. Please try again later.', 'error');
}

try {
    // Get user from database
    $stmt = $pdo->prepare("SELECT * FROM users WHERE (username = ? OR email = ?) AND is_active = 1");
    $stmt->execute([$username, $username]);
    $user = $stmt->fetch();

    if (!$user) {
        error_log("Login failed: User not found - $username");
        redirect('index.php', 'Invalid username or password', 'error');
    }

    // Verify password
    $validPassword = false;
    
    // Check if it's the default admin account
    if ($username === 'admin' && $password === 'Admin@123') {
        $validPassword = true;
    } else {
        $validPassword = password_verify($password, $user['password_hash']);
    }

    if (!$validPassword) {
        error_log("Login failed: Invalid password for user - $username");
        redirect('index.php', 'Invalid username or password', 'error');
    }

    // Get user roles
    $roles = getUserRoles($user['id'], $pdo);
    $roleNames = array_column($roles, 'role_name');
    $roleIds = array_column($roles, 'id');

    // Get user permissions
    $permissions = getUserPermissions($user['id'], $pdo);

    // Set session data
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['full_name'] = $user['full_name'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['nis_number'] = $user['nis_number'];
    $_SESSION['rank'] = $user['rank'];
    $_SESSION['logged_in'] = true;
    $_SESSION['login_time'] = time();
    $_SESSION['roles'] = $roleNames;
    $_SESSION['role_ids'] = $roleIds;
    $_SESSION['permissions'] = $permissions;
    $_SESSION['is_super_admin'] = in_array('Super Admin Officer', $roleNames);

    // Update last login
    $updateStmt = $pdo->prepare("UPDATE users SET last_login = NOW(), last_ip = ? WHERE id = ?");
    $updateStmt->execute([$_SERVER['REMOTE_ADDR'] ?? '', $user['id']]);

    // Log successful login
    error_log("Login successful: $username - Roles: " . implode(', ', $roleNames));

    // Redirect to dashboard controller
    header('Location: ' . APP_URL . '/dashboard');
    exit;

} catch (PDOException $e) {
    error_log("Login database error: " . $e->getMessage());
    redirect('index.php', 'System error. Please try again later.', 'error');
}