<?php
session_start();
require_once 'db.php';
require_once 'activity_logger.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF token validation
    if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        header('Location: ../login.php?error=csrf_error');
        exit();
    }

    // Unset the token so it can't be used again
    // unset($_SESSION['csrf_token']); // Keep token for re-attempts on failed login

    if (!isset($_POST['username']) || !isset($_POST['password'])) {
        header('Location: ../login.php?error=missing_fields');
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            session_regenerate_id(true);
            log_activity($user['id'], 'User Login', 'User ' . $user['username'] . ' logged in.');
            session_write_close();
            header('Location: ../index.php');
            exit();
        } else {
            header('Location: ../login.php?error=invalid_credentials');
            exit();
        }
    } catch (PDOException $e) {
        // Log the error instead of showing it to the user
        error_log('Authentication error: ' . $e->getMessage());
        header('Location: ../login.php?error=db_error');
        exit();
    }
}
?>
