<?php

namespace App\Http\Controllers;

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

class CountryController extends Controller
{
    public function index()
    {
        $countries = Country::with('parentContinent')->orderBy('name')->get();
        $continents = Continent::active()->orderBy('name')->get();

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'continent_id' => 'required|exists:continents,id',
            'name' => 'required|string|max:255',
            'status' => 'required|in:0,1',
        ]);

        $continent = Continent::findOrFail($validated['continent_id']);

        Country::create([
            'continent' => $continent->name,
            'name' => $validated['name'],
            'status' => (bool) (int) $validated['status'],
        ]);

        return redirect()->route('countries.index')->with('success', 'Country added.');
    }

    public function edit(Country $country)
    {
        $continents = Continent::active()->orderBy('name')->get();
        $selectedContinentId = optional(Continent::where('name', $country->continent)->first())->id;

        return view('geography.countries.edit', compact('country', 'continents', 'selectedContinentId'));
    }

    public function update(Request $request, Country $country)
    {
        $validated = $request->validate([
            'continent_id' => 'required|exists:continents,id',
            'name' => 'required|string|max:255',
            'status' => 'required|in:0,1',
        ]);

        $continent = Continent::findOrFail($validated['continent_id']);

        $country->update([
            'continent' => $continent->name,
            'name' => $validated['name'],
            'status' => (bool) (int) $validated['status'],
        ]);

        return redirect()->route('countries.index')->with('success', 'Country updated.');
    }

    public function destroy(Country $country)
    {
        $country->delete();

        return redirect()->route('countries.index')->with('success', 'Country deleted.');
    }
}
