<?php
require __DIR__ . '/../config.php';
require __DIR__ . '/../db.php';

session_name(SESSION_NAME);
session_start();

function requireLogin() {
    if (empty($_SESSION['admin_logged_in'])) {
        header('Location: login.php');
        exit;
    }
}

function csrfField() {
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
    return '<input type="hidden" name="csrf" value="' . htmlspecialchars($_SESSION['csrf']) . '">';
}

function checkCsrf() {
    if (empty($_POST['csrf']) || empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $_POST['csrf'])) {
        http_response_code(403);
        die('Invalid CSRF token. Go back and try again.');
    }
}

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