<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Zone;
use Illuminate\Http\Request;

class ZoneController extends Controller
{
    public function index()
    {
        $zones = Zone::withCount('restaurants')->orderBy('name')->get();
        $total = $zones->count();
        $active = $zones->where('is_active', true)->count();
        $inactive = $total - $active;
        $totalRestaurants = $zones->sum('restaurants_count');

        return view('admin.zones.index', [
            'zones' => $zones,
            'stats' => [
                'total' => $total,
                'active' => $active,
                'inactive' => $inactive,
                'restaurants' => $totalRestaurants,
            ],
        ]);
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'city' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'center_address' => 'nullable|string|max:255',
            'center_lat' => 'nullable|numeric',
            'center_lng' => 'nullable|numeric',
            'radius_km' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active');

        Zone::create($data);

        return redirect()
            ->route('admin.zones.index')
            ->with('success', 'Zona creada correctamente.');
    }

    public function edit(Zone $zone)
    {
        return view('admin.zones.edit', [
            'zone' => $zone,
        ]);
    }

    public function update(Request $request, Zone $zone)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'city' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'center_address' => 'nullable|string|max:255',
            'center_lat' => 'nullable|numeric',
            'center_lng' => 'nullable|numeric',
            'radius_km' => 'nullable|numeric|min:0',
            'is_active' => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active');

        $zone->update($data);

        return redirect()
            ->route('admin.zones.index')
            ->with('success', 'Zona actualizada.');
    }

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

        return redirect()
            ->route('admin.zones.index')
            ->with('success', 'Zona eliminada.');
    }
}
