<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\DataTables\CityDataTable;
use App\Models\City;
use App\Models\Country;
use App\Http\Requests\Admin\City\StoreCityRequest;
use App\Http\Requests\Admin\City\UpdateCityRequest;
use App\Repositories\CityRepository;
use Illuminate\Http\Request;

class CityController extends Controller
{
    protected CityRepository $repository;

    public function __construct(CityRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index(CityDataTable $dataTable)
    {
        $countries = Country::active()->orderBy('name->en')->get();

        return view('admin.cities.index', [
            'dataTable' => $dataTable->html(),
            'countries' => $countries,
        ]);
    }

    public function datatable(CityDataTable $dataTable)
    {
        return $dataTable->ajax();
    }

    public function create()
    {
        $countries = Country::active()->orderBy('name->en')->get();
        return view('admin.cities.create', compact('countries'));
    }

    public function store(StoreCityRequest $request)
    {
        $this->repository->create($request->validated());
        return response()->json([
            'message' => __('dashboard.city_created'),
            'redirect_url' => route('admin.cities.index')
        ]);
    }

    public function show(City $city)
    {
        $city->load('country');

        return view('admin.cities.show', [
            'city' => $city,
        ]);
    }

    public function edit(City $city)
    {
        $countries = Country::active()->orderBy('name->en')->get();
        return view('admin.cities.edit', compact('city', 'countries'));
    }

    public function update(UpdateCityRequest $request, City $city)
    {
        $this->repository->update($city, $request->validated());
        return response()->json([
            'message' => __('dashboard.city_updated'),
            'redirect_url' => route('admin.cities.index')
        ]);
    }

    public function destroy(City $city)
    {
        $result = $this->repository->delete($city);

        return response()->json([
            'message' => $result['success'] ? __('dashboard.city_deleted') : __('dashboard.cannot_delete_has_relations'),
            'success' => $result['success'],
            'relations' => $result['relations']
        ]);
    }

    public function updateStatus(City $city)
    {
        $result = $this->repository->statusToggle($city);

        return response()->json([
            'message' => $result['message'],
            'success' => $result['success']
        ]);
    }

    public function bulkDelete(Request $request)
    {
        $request->validate(['ids' => 'required|array']);

        $result = $this->repository->bulkDelete($request->ids);

        return response()->json([
            'message' => __('dashboard.deleted_success'),
            'success' => true,
            'data' => $result
        ]);
    }

    public function bulkStatus(Request $request)
    {
        $request->validate(['ids' => 'required|array', 'status' => 'required|boolean']);

        $result = $this->repository->bulkStatus($request->ids, $request->status);

        return response()->json([
            'message' => __('dashboard.status_updated'),
            'success' => true,
            'data' => $result
        ]);
    }

    public function listCities(Request $request)
    {
        $search = $request->q;
        $countryId = $request->country_id;

        $cities = City::query()
            ->when($search, function ($q) use ($search) {
                $q->where('name->en', 'like', "%$search%")
                  ->orWhere('name->ar', 'like', "%$search%");
            })
            ->when($countryId, function ($q) use ($countryId) {
                $q->where('country_id', $countryId);
            })
            ->active()
            ->orderBy('name->en')
            ->limit(20)
            ->get();
          

        $formatted = $cities->map(function ($city) {
            return [
                "id" => $city->id,
                "text" => $city->getTranslation('name', app()->getLocale())
            ];
        });

        return response()->json($formatted);
    }
}
