<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CityRequest;
use App\Models\City;
use App\Models\Country;

class CityController extends Controller
{
    public function index()
    {
        $search = request('search');

        $cities = City::when($search, function ($query) use ($search) {
            return $query->where('name', 'like', '%'.$search.'%')->orWhereHas('country', function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        })->orderBy('name')->paginate(20)->withQueryString();

        $countries = Country::all();

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

    public function store(CityRequest $request)
    {
        City::create([
            'name' => $request->name,
            'country_id' => $request->country_id,
            'delivery_charge' => $request->delivery_charge,
            'amount' => $request->max_amount,
        ]);

        return to_route('admin.city.index')->withSuccess(__('Created Successfully'));
    }

    public function update(CityRequest $request, City $city)
    {
        $city->update([
            'name' => $request->name,
            'country_id' => $request->country_id,
            'delivery_charge' => $request->delivery_charge,
            'amount' => $request->max_amount,
        ]);

        return to_route('admin.city.index')->withSuccess(__('Updated Successfully'));
    }
}
