<?php

namespace App\Http\Controllers;

use App\Models\Governorate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GovernorateController extends Controller
{
    public function index()
    {
        $governorates = Governorate::withCount('cities')
            ->orderBy('name')
            ->paginate(20);
        
        return view('governorates.index', compact('governorates'));
    }

    public function create()
    {
        return view('governorates.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:governorates',
        ]);

        Governorate::create($request->only('name'));

        return redirect()->route('governorates.index')
            ->with('success', 'Governorate created successfully.');
    }

    public function edit(Governorate $governorate)
    {
        return view('governorates.edit', compact('governorate'));
    }

    public function update(Request $request, Governorate $governorate)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:governorates,name,' . $governorate->id,
        ]);

        $governorate->update($request->only('name'));

        return redirect()->route('governorates.index')
            ->with('success', 'Governorate updated successfully.');
    }

    public function destroy(Governorate $governorate)
    {
        if ($governorate->cities()->count() > 0) {
            return back()->with('error', 'Cannot delete governorate. There are associated cities.');
        }

        $governorate->delete();

        return redirect()->route('governorates.index')
            ->with('success', 'Governorate deleted successfully.');
    }
}