<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\ZoneDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreZoneRequest;
use App\Http\Requests\UpdateZoneRequest;
use App\Models\Zone;
use App\Services\ZoneService;
use Illuminate\Http\Request;

class ZoneController extends Controller
{
    public function __construct(protected ZoneService $service)
    {
        $this->authorizeResource(Zone::class, 'zone');
    }

    public function index()
    {
        $zones = Zone::select(['id', 'name'])->orderBy('name')->get();

        return view('admin.zones.index', compact('zones'));
    }

    public function data(Request $request, ZoneDataTable $dataTable)
    {
        $this->authorize('viewAny', Zone::class);

        return $dataTable->render($request);
    }

    public function store(StoreZoneRequest $request)
    {
        $zone = $this->service->create($request->validated());

        return response()->json(['success' => true, 'data' => $zone], 201);
    }

    public function edit(Zone $zone)
    {
        return response()->json([
            'data' => $zone,
            'update_url' => route('admin.zones.update', $zone),
        ]);
    }

    public function update(UpdateZoneRequest $request, Zone $zone)
    {
        $this->service->update($zone, $request->validated());

        return response()->json(['success' => true, 'data' => $zone->fresh()]);
    }

    public function destroy(Zone $zone)
    {
        $this->service->delete($zone);

        return response()->json(['success' => true]);
    }
}
