<?php

namespace App\Http\Controllers;

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

class CityController extends Controller
{
    public function index()
    {
        $cities = City::with('governorate')
            ->orderBy('name')
            ->paginate(20);
        
        return view('cities.index', compact('cities'));
    }

    public function create()
    {
        $governorates = Governorate::orderBy('name')->get();
        return view('cities.create', compact('governorates'));
    }

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

        City::create($request->only('name', 'governorate_id'));

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

    public function edit(City $city)
    {
        $governorates = Governorate::orderBy('name')->get();
        return view('cities.edit', compact('city', 'governorates'));
    }

    public function update(Request $request, City $city)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'governorate_id' => 'required|exists:governorates,id',
        ]);

        $city->update($request->only('name', 'governorate_id'));

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

    public function destroy(City $city)
    {
        if ($city->clients()->count() > 0 || $city->visits()->count() > 0) {
            return back()->with('error', 'Cannot delete city. There are associated clients or visits.');
        }

        $city->delete();

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

    public function getByGovernorate(Request $request)
    {
        $cities = City::where('governorate_id', $request->governorate_id)
            ->orderBy('name')
            ->get();
        
        return response()->json($cities);
    }
}