<?php
require_once __DIR__ . '/db.php';

function slugify($text) {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text, '-');
}

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

function time_ago($datetime) {
    $ts = strtotime($datetime);
    if (!$ts) return '';
    $diff = time() - $ts;
    if ($diff < 60) return 'just now';
    if ($diff < 3600) return floor($diff / 60) . ' min ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hr ago';
    if ($diff < 2592000) return floor($diff / 86400) . ' days ago';
    return date('d M Y', $ts);
}

function paginate_links($current, $total_pages, $base_url, $extra_params = []) {
    if ($total_pages <= 1) return '';
    $mk = function($p) use ($base_url, $extra_params) {
        $params = $extra_params;
        $params['page'] = $p;
        return e($base_url . '?' . http_build_query($params));
    };
    $html = '<nav class="pagination" aria-label="Pagination">';
    $start = max(1, $current - 2);
    $end = min($total_pages, $current + 2);

    if ($current > 1) {
        $html .= '<a href="' . $mk($current - 1) . '" class="page-btn prev">&laquo; Prev</a>';
    }
    if ($start > 1) {
        $html .= '<a href="' . $mk(1) . '" class="page-btn">1</a>';
        if ($start > 2) $html .= '<span class="page-dots">&hellip;</span>';
    }
    for ($i = $start; $i <= $end; $i++) {
        $active = $i == $current ? ' active' : '';
        $html .= '<a href="' . $mk($i) . '" class="page-btn' . $active . '">' . $i . '</a>';
    }
    if ($end < $total_pages) {
        if ($end < $total_pages - 1) $html .= '<span class="page-dots">&hellip;</span>';
        $html .= '<a href="' . $mk($total_pages) . '" class="page-btn">' . $total_pages . '</a>';
    }
    if ($current < $total_pages) {
        $html .= '<a href="' . $mk($current + 1) . '" class="page-btn next">Next &raquo;</a>';
    }
    $html .= '</nav>';
    return $html;
}

function get_latest_news($limit = 12, $offset = 0, $search = '') {
    $pdo = db();
    if ($search) {
        $stmt = $pdo->prepare("SELECT * FROM news WHERE title LIKE ? OR summary LIKE ?
            ORDER BY published_at DESC LIMIT ? OFFSET ?");
        $like = '%' . $search . '%';
        $stmt->bindValue(1, $like);
        $stmt->bindValue(2, $like);
        $stmt->bindValue(3, $limit, PDO::PARAM_INT);
        $stmt->bindValue(4, $offset, PDO::PARAM_INT);
        $stmt->execute();
    } else {
        $stmt = $pdo->prepare("SELECT * FROM news ORDER BY published_at DESC LIMIT ? OFFSET ?");
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->bindValue(2, $offset, PDO::PARAM_INT);
        $stmt->execute();
    }
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function count_news($search = '') {
    $pdo = db();
    if ($search) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM news WHERE title LIKE ? OR summary LIKE ?");
        $like = '%' . $search . '%';
        $stmt->execute([$like, $like]);
    } else {
        $stmt = $pdo->query("SELECT COUNT(*) FROM news");
    }
    return (int)$stmt->fetchColumn();
}

function get_news_by_slug($slug) {
    $stmt = db()->prepare("SELECT * FROM news WHERE slug = ? LIMIT 1");
    $stmt->execute([$slug]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function search_games($q = '', $limit = 24, $offset = 0, $category = '') {
    $pdo = db();
    $where = [];
    $params = [];
    if ($q !== '') {
        $where[] = "(name LIKE ? OR description LIKE ? OR category LIKE ?)";
        $like = '%' . $q . '%';
        array_push($params, $like, $like, $like);
    }
    if ($category !== '') {
        $where[] = "category = ?";
        $params[] = $category;
    }
    $sql = "SELECT * FROM games";
    if ($where) $sql .= " WHERE " . implode(' AND ', $where);
    $sql .= " ORDER BY name ASC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;

    $stmt = $pdo->prepare($sql);
    foreach ($params as $i => $v) {
        $type = (is_int($v)) ? PDO::PARAM_INT : PDO::PARAM_STR;
        $stmt->bindValue($i + 1, $v, $type);
    }
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function count_games($q = '', $category = '') {
    $pdo = db();
    $where = [];
    $params = [];
    if ($q !== '') {
        $where[] = "(name LIKE ? OR description LIKE ? OR category LIKE ?)";
        $like = '%' . $q . '%';
        array_push($params, $like, $like, $like);
    }
    if ($category !== '') {
        $where[] = "category = ?";
        $params[] = $category;
    }
    $sql = "SELECT COUNT(*) FROM games";
    if ($where) $sql .= " WHERE " . implode(' AND ', $where);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return (int)$stmt->fetchColumn();
}

function get_game_by_slug($slug) {
    $stmt = db()->prepare("SELECT * FROM games WHERE slug = ? LIMIT 1");
    $stmt->execute([$slug]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function get_categories() {
    $stmt = db()->query("SELECT DISTINCT category FROM games WHERE category IS NOT NULL AND category != '' ORDER BY category ASC");
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function get_page_num() {
    $p = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    return max(1, $p);
}
