<?php
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    session_set_cookie_params([
        'lifetime' => 31536000,
        'path' => '/',
        'secure' => isset($_SERVER['HTTPS']),
        'httponly' => true
    ]);
    session_start();
}
require_once __DIR__ . '/../config/db.php';

// --- HELPER FUNCTIONS ---

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

function requireLogin()
{
    if (!isLoggedIn()) {
        header("Location: login.php");
        exit;
    }
}

function isAdmin()
{
    return isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
}

function requireAdmin()
{
    if (!isAdmin()) {
        header("Location: ../index.php"); // or admin login
        exit;
    }
}

function getUser($pdo, $id)
{
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}


function getSetting($key)
{
    global $pdo;
    $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = ?");
    $stmt->execute([$key]);
    return $stmt->fetchColumn() ?: '';
}

function sanitize($data)
{
    return htmlspecialchars(strip_tags(trim($data)));
}

// Format Date
function timeAgo($datetime)
{
    $time = strtotime($datetime);
    $diff = time() - $time;
    if ($diff < 60)
        return 'Just now';
    if ($diff < 3600)
        return floor($diff / 60) . ' mins ago';
    if ($diff < 86400)
        return floor($diff / 3600) . ' hours ago';
    return date("d M Y", $time);
}

// JSON Response
function jsonResponse($success, $message, $data = [])
{
    header('Content-Type: application/json');
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit;
}
?>