<?php
namespace App\Controllers;

use App\Models\Category;
use App\Models\Mod;
use Throwable;

class CategoryController extends BaseController
{
    public function show(string $slug): string
    {
        $sort = $this->normalizeSort($_GET['sirala'] ?? $_GET['sort'] ?? 'newest');

        try {
            $categoryModel = new Category();
            $modModel = new Mod();
            $category = $categoryModel->findBySlug($slug);

            if (!$category) {
                return $this->notFound();
            }

            $children = $categoryModel->children((int) $category['id']);
            $categoryIds = $categoryModel->treeIds((int) $category['id']);
            $mods = $modModel->list([
                'category_ids' => $categoryIds,
                'sort' => $sort,
                'limit' => 24,
            ]);

            return $this->view('main', 'categories/show', [
                'title' => $category['name'],
                'category' => $category,
                'categories' => $categoryModel->modRoots(12),
                'children' => $children,
                'mods' => $mods,
                'slug' => $slug,
                'sort' => $sort,
            ]);
        } catch (Throwable) {
            $data = $this->samples();

            return $this->view('main', 'categories/show', [
                'title' => 'Kategori',
                'category' => [
                    'name' => 'Kategori',
                    'slug' => $slug,
                    'description' => 'Veritabani baglantisi bekleniyor.',
                    'banner' => '',
                    'icon' => '',
                    'mod_count' => count($data['mods'] ?? []),
                ],
                'categories' => $data['categories'] ?? [],
                'children' => [],
                'mods' => $data['mods'] ?? [],
                'slug' => $slug,
                'sort' => $sort,
            ]);
        }
    }

    private function normalizeSort(string $sort): string
    {
        return match ($sort) {
            'indirilen', 'downloads', 'downloaded' => 'downloaded',
            'goruntulenen', 'views', 'viewed' => 'viewed',
            'populer', 'popular' => 'popular',
            'premium' => 'premium',
            'ucretsiz', 'free' => 'free',
            default => 'newest',
        };
    }

    private function notFound(): string
    {
        http_response_code(404);

        return $this->view('main', 'pages/show', [
            'title' => '404',
            'page' => [
                'title' => 'Kategori bulunamadi',
                'content' => 'Aradigin kategori yayinda degil veya tasinmis olabilir.',
            ],
        ]);
    }
}
