<?php

namespace App\Http\Controllers;

use App\Models\Country;
use Illuminate\Http\Request;

class CountryController extends Controller
{
    public function index(Request $request)
    {
        $query = Country::query()->withCount(['universities', 'scholarships'])->orderBy('name');

        if ($request->filled('search')) {
            $query->where('name', 'like', '%'.$request->search.'%');
        }

        if ($request->filled('popular')) {
            $query->where('is_popular', true);
        }

        $countries = $query->paginate(12);

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

    public function show(Country $country)
    {
        $country->loadCount(['universities', 'scholarships', 'admissionGuides']);
        $country->load([
            'universities' => fn ($query) => $query->withCount('programs')->orderBy('ranking')->take(8),
            'scholarships' => fn ($query) => $query->published()->orderBy('deadline')->take(6),
            'admissionGuides' => fn ($query) => $query->orderBy('title')->take(6),
        ]);

        return view('countries.show', compact('country'));
    }
}
