<?php

namespace App\Http\Controllers;

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

class CityController extends Controller
{
    public function index()
    {
        $cities = City::with('country.parentContinent')->orderBy('name')->get();
        $countries = Country::active()->with('parentContinent')->orderBy('name')->get();

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

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

        City::create($validated);

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

    public function edit(City $city)
    {
        $countries = Country::with('parentContinent')->orderBy('name')->get();

        return view('geography.cities.edit', compact('city', 'countries'));
    }

    public function update(Request $request, City $city)
    {
        $validated = $request->validate([
            'country_id' => 'required|exists:countries,id',
            'name' => 'required|string|max:255',
            'status' => 'required|in:0,1',
        ]);
        $validated['status'] = (bool) (int) $validated['status'];

        $city->update($validated);

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

    public function destroy(City $city)
    {
        $city->delete();

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