<?php
namespace App\Controllers;

use App\Core\{Auth, Session};
use App\Models\Category;
use App\Models\CommunityPost;
use App\Models\Mod;
use App\Models\Music;
use App\Models\Story;
use Throwable;

class HomeController extends BaseController
{
    public function localized(string $lang): string
    {
        $supported = $this->config['supported_languages'] ?? ['tr', 'en', 'de', 'fr'];
        if (!in_array($lang, $supported, true)) {
            return $this->notFound();
        }

        Session::put('lang', $lang);

        return $this->index();
    }

    public function index(): string
    {
        try {
            $categoryModel = new Category();
            $modModel = new Mod();
            $musicModel = new Music();

            $topGames = $categoryModel->findBySlugs(['fs25-mods', 'fs22-mods', 'fs13-mods', 'fs11-mods', 'packs', 'weekly-choice']);
            $fs25 = $categoryModel->findBySlug('fs25-mods');
            $fs25Ids = $fs25 ? $categoryModel->treeIds((int) $fs25['id']) : [];

            $sections = [
                'new' => ['title' => 'FS25 Yeni Modlar', 'mods' => $modModel->latestFs25($fs25Ids, 8), 'url' => '/kategori/fs25-mods'],
                'popular' => ['title' => 'Populer Modlar', 'mods' => $modModel->popular(8), 'url' => '/arama?sirala=populer'],
                'recommended' => ['title' => 'Onerilen Modlar', 'mods' => $modModel->recommended(8), 'url' => '/arama?sirala=onerilen'],
                'premium' => ['title' => 'Premium Modlar', 'mods' => $modModel->premium(8), 'url' => '/arama?sirala=premium'],
            ];

            $music = $musicModel->publishedPreview(6);
        } catch (Throwable) {
            $sample = $this->samples();
            $topGames = $this->fallbackCategories($sample['categories'] ?? []);
            $sections = [
                'new' => ['title' => 'FS25 Yeni Modlar', 'mods' => $sample['mods'] ?? [], 'url' => '/kategori/fs25-mods'],
                'popular' => ['title' => 'Populer Modlar', 'mods' => $sample['mods'] ?? [], 'url' => '/arama?sirala=populer'],
                'recommended' => ['title' => 'Onerilen Modlar', 'mods' => $sample['mods'] ?? [], 'url' => '/arama?sirala=onerilen'],
                'premium' => ['title' => 'Premium Modlar', 'mods' => array_values(array_filter($sample['mods'] ?? [], fn (array $mod): bool => !empty($mod['premium']))), 'url' => '/arama?sirala=premium'],
            ];
            $music = $sample['music'] ?? [];
        }

        $communityPosts = [];
        $stories = [];
        try {
            $communityPosts = (new CommunityPost())->listFeed(Auth::id(), 10);
            $stories = (new Story())->listActiveFeed(Auth::id(), 18);
        } catch (Throwable $exception) {
            $this->logException($exception, 'home.community-story');
        }

        return $this->view('main', 'home/index', [
            'title' => 'Zalorox',
            'topGames' => $topGames,
            'sections' => $sections,
            'mods' => $sections['new']['mods'] ?? [],
            'music' => $music,
            'communityPosts' => $communityPosts,
            'stories' => $stories,
        ]);
    }

    public function notFound(): string
    {
        http_response_code(404);
        return $this->view('main', 'pages/show', ['title' => '404', 'page' => ['title' => 'Sayfa bulunamadi', 'content' => 'Aradigin sayfa yok veya tasinmis.']]);
    }

    private function fallbackCategories(array $categories): array
    {
        return array_map(static function (string $name): array {
            $slug = strtolower(str_replace([' ', '_'], '-', $name));

            return [
                'id' => 0,
                'name' => $name,
                'slug' => $slug,
                'description' => '',
                'icon' => '',
                'banner' => '',
                'mod_count' => 0,
            ];
        }, $categories);
    }
}
