<?php

namespace App\Http\Controllers;

use App\Domain\Event\Models\Event;
use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Enums\SectionKey;
use App\Domain\Website\Models\WebsiteNews;
use App\Domain\Website\Models\WebsiteSetting;
use App\Domain\Website\Services\WebsiteDataService;
use App\Domain\Website\Services\WebsiteSectionService;
use App\Domain\Website\Services\WebsiteSettingService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PublicWebsiteController extends Controller
{
    public function __construct(
        private WebsiteDataService $dataService,
        private WebsiteSectionService $sectionService,
        private WebsiteSettingService $settingService,
    ) {}

    public function home()
    {
        $academy = Academy::first();

        if (!$academy) {
            return redirect()->route('login');
        }

        $settings = $this->settingService->getOrCreate($academy);
        app()->instance('current_academy', $academy);
        app()->instance('website_settings', $settings);

        $sections = $this->sectionService->getEnabled($academy);

        if ($sections->isEmpty()) {
            $this->sectionService->seedDefaults($academy);
            $sections = $this->sectionService->getEnabled($academy);
        }

        $data = $this->gatherSectionData($academy, $sections);

        return view('website.index', [
            'academy' => $academy,
            'settings' => $settings,
            'sections' => $sections,
            'data' => $data,
            'showLoginButton' => true,
        ]);
    }

    public function show(string $slug)
    {
        $academy = app('current_academy');
        $settings = app('website_settings');

        $sections = $this->sectionService->getEnabled($academy);

        $data = $this->gatherSectionData($academy, $sections);

        return view('website.index', [
            'academy' => $academy,
            'settings' => $settings,
            'sections' => $sections,
            'data' => $data,
            'showLoginButton' => true,
        ]);
    }

    public function preview(Request $request)
    {
        $academy = app('current_academy');
        $settings = app(WebsiteSettingService::class)->getOrCreate($academy);

        app()->instance('website_settings', $settings);

        $sections = $this->sectionService->getAll($academy)->where('is_enabled', true);
        $data = $this->gatherSectionData($academy, $sections);

        return view('website.index', [
            'academy' => $academy,
            'settings' => $settings,
            'sections' => $sections,
            'data' => $data,
            'isPreview' => true,
        ]);
    }

    public function newsIndex(string $slug)
    {
        $academy = app('current_academy');
        $settings = app('website_settings');

        $category = request('category');

        $query = WebsiteNews::where('academy_id', $academy->id)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->orderByDesc('published_at');

        if ($category) {
            $query->where('category', $category);
        }

        $news = $query->paginate(12);
        $categories = WebsiteNews::where('academy_id', $academy->id)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->whereNotNull('category')
            ->distinct()
            ->pluck('category');

        return view('website.news-index', [
            'academy' => $academy,
            'settings' => $settings,
            'news' => $news,
            'categories' => $categories,
            'activeCategory' => $category,
        ]);
    }

    public function newsShow(string $slug, string $news)
    {
        $academy = app('current_academy');
        $settings = app('website_settings');

        $article = WebsiteNews::where('academy_id', $academy->id)
            ->where('slug', $news)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->firstOrFail();

        $related = WebsiteNews::where('academy_id', $academy->id)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->where('id', '!=', $article->id)
            ->when($article->category, fn($q) => $q->where('category', $article->category))
            ->latest('published_at')
            ->take(3)
            ->get();

        return view('website.news-show', [
            'academy' => $academy,
            'settings' => $settings,
            'article' => $article,
            'related' => $related,
        ]);
    }

    private function gatherSectionData(Academy $academy, $sections): array
    {
        $data = [];
        $enabledKeys = $sections->pluck('section_key');

        if ($enabledKeys->contains(SectionKey::Activities)) {
            $data['activities'] = $this->dataService->getActivities($academy);
        }

        if ($enabledKeys->contains(SectionKey::Programs)) {
            $data['programs'] = $this->dataService->getPrograms($academy);
        }

        if ($enabledKeys->contains(SectionKey::Branches)) {
            $data['branches'] = $this->dataService->getBranches($academy);
        }

        if ($enabledKeys->contains(SectionKey::Stats)) {
            $data['stats'] = $this->dataService->getStats($academy);
        }

        if ($enabledKeys->contains(SectionKey::Testimonials)) {
            $data['testimonials'] = $this->dataService->getTestimonials($academy);
        }

        if ($enabledKeys->contains(SectionKey::Faq)) {
            $data['faqs'] = $this->dataService->getFaqs($academy);
        }

        if ($enabledKeys->contains(SectionKey::News)) {
            $data['news'] = $this->dataService->getNews($academy);
        }

        if ($enabledKeys->contains(SectionKey::Partners)) {
            $data['partners'] = $this->dataService->getPartners($academy);
        }

        if ($enabledKeys->contains(SectionKey::Gallery)) {
            $data['gallery'] = $this->dataService->getGalleryImages($academy);
        }

        if ($enabledKeys->contains(SectionKey::Events)) {
            $data['events'] = Event::withoutGlobalScope('academy')
                ->where('academy_id', $academy->id)
                ->published()
                ->where('starts_at', '>', now()->subDay())
                ->with('cover')
                ->orderBy('starts_at')
                ->take(6)
                ->get();
        }

        return $data;
    }
}
