<?php
// Start session with basic settings for now
session_start();

function isAuthenticated() {
    return isset($_SESSION['user_id']);
}

function requireAuth() {
    if (!isAuthenticated()) {
        header('Location: login.php');
        exit;
    }
    
    // Update last activity time
    $_SESSION['last_activity'] = time();
}

function logout() {
    // Clear all session data
    $_SESSION = array();
    
    // Destroy the session cookie
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login
    header('Location: login.php');
    exit;
}

// Log activity with basic information
function logActivity($action, $details = '') {
    try {
        $db = getDB();
        $stmt = $db->prepare('INSERT INTO activity_log (user_id, action, details) VALUES (:user_id, :action, :details)');
        $stmt->bindValue(':user_id', $_SESSION['user_id'] ?? null, SQLITE3_INTEGER);
        $stmt->bindValue(':action', $action, SQLITE3_TEXT);
        $stmt->bindValue(':details', $details, SQLITE3_TEXT);
        $stmt->execute();
    } catch (Exception $e) {
        error_log('Failed to log activity: ' . $e->getMessage());
    }
}

// Simple CSRF token function
function validateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            http_response_code(403);
            die('Invalid CSRF token');
        }
    }
    return $_SESSION['csrf_token'];
}

function getCSRFTokenField() {
    $token = validateCSRFToken();
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token) . '">';
}

function h($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
