<?php

namespace App\Http\Controllers;

use App\Models\CountriesPageContent;
use App\Models\CountrySectionsContent;
use App\Models\Country;
use App\Models\HomePageContent;
use App\Models\PartnerInstitution;
use App\Models\StudentReview;
use App\Models\VisaSuccessStory;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CountryController extends Controller
{
    public function index(Request $request): View
    {
        $countries = Country::active()
            ->ordered()
            ->when($request->filled('search'), function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->string('search') . '%');
            })
            ->get();

        $pageContent = CountriesPageContent::getContent();
        $homeContent = HomePageContent::getContent();

        return view('countries.index', compact('countries', 'pageContent', 'homeContent'));
    }

    public function show(string $slug): View
    {
        $country = Country::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();
        $sections = $country->resolvedPageSections();
        $countrySections = CountrySectionsContent::resolveForCountry($country->slug, $country->name);
        $studentReviews = StudentReview::active()->ordered()->limit(8)->get();
        $homeContent = HomePageContent::getContent();
        PartnerInstitution::ensureDemoItems();
        $partnerInstitutions = PartnerInstitution::active()->ordered()->get();
        if ($partnerInstitutions->isEmpty()) {
            $partnerInstitutions = collect($homeContent['institutions']['items'] ?? [])->map(function ($name) {
                return (object) ['name' => $name, 'logo_url' => null];
            });
        }
        $visaStories = VisaSuccessStory::active()->ordered()->limit(6)->get();

        if ($visaStories->isEmpty()) {
            $visaStories = VisaSuccessStory::fallbackStories();
        }

        $others = Country::active()
            ->ordered()
            ->where('id', '!=', $country->id)
            ->limit(6)
            ->get();

        return view('countries.show', compact(
            'country',
            'others',
            'sections',
            'countrySections',
            'studentReviews',
            'partnerInstitutions',
            'visaStories'
        ));
    }
}
