<?php
require_once __DIR__ . '/../models/Game.php';
require_once __DIR__ . '/../models/Category.php';
require_once __DIR__ . '/../models/SiteSettings.php';

class CategoryController {
    private $gameModel;
    private $categoryModel;
    private $siteSettings;

    public function __construct() {
        $this->gameModel = new Game();
        $this->categoryModel = new Category();
        $this->siteSettings = new SiteSettings();
    }

    public function index() {
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = (int)($this->siteSettings->getSetting('categories_per_page') ?? 12);
        $offset = ($page - 1) * $limit;
        
        $categories = $this->categoryModel->getAllCategories($limit, $offset);
        $totalCategories = $this->categoryModel->getTotalCategories();
        $totalPages = ceil($totalCategories / $limit);
        
        $popularCategories = $this->categoryModel->getPopularCategories(10);
        
        $pageTitle = 'All Categories';
        $pageDescription = 'Browse all game categories on our gaming portal.';
        
        include __DIR__ . '/../views/categories.php';
    }
    
    public function show($slug) {
        // Get the category directly from the database using the slug from the URL
        $category = $this->categoryModel->getCategoryBySlug($slug);
        
        if (!$category) {
            header('HTTP/1.0 404 Not Found');
            include __DIR__ . '/../views/404.php';
            return;
        }
        
        // Log the category data for debugging
        error_log("Category data for slug '{$slug}': " . json_encode($category));
        
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = (int)($this->siteSettings->getSetting('category_games_per_page') ?? 12);
        $offset = ($page - 1) * $limit;

        // Get games for this category
        $games = $this->gameModel->getGamesByCategory($slug, $limit, $offset);
        $totalGames = $this->gameModel->getTotalGamesByCategory($slug);
        $totalPages = ceil($totalGames / $limit);
        
        // Get popular categories for the sidebar
        $popularCategories = $this->categoryModel->getPopularCategories(10);
        
        // Override any potential hardcoded values by setting these variables explicitly
        $categoryName = $category['name'];
        $categorySlug = $category['slug'];
        $categoryId = $category['id'];
        
        // Set page title and description for SEO
        $pageTitle = $categoryName . ' Games';
        $pageDescription = 'Play the best ' . $categoryName . ' games for free on our gaming portal.';
        
        // Include the view with the correct category data
        include __DIR__ . '/../views/category.php';
    }
}
