<?php

namespace App\Http\Controllers\Admin;

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

class DeliveryZoneController extends Controller
{
    public function index()
    {
        $items = DeliveryZone::latest()->paginate(10);
        return view('admin.delivery.delivery-zones.index', compact('items'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'city' => 'required|max:255',
            'state' => 'required|max:255',
            'country' => 'required|max:255',
            'zipcode' => 'nullable|max:20',
            'delivery_fee' => 'required|numeric|min:0',
            'min_order_amount' => 'required|numeric|min:0',
            'free_delivery_amount' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        DeliveryZone::create($validated);

        return redirect()->route('admin.delivery.zones.index')
            ->with('success', 'Delivery zone created successfully');
    }

    public function edit(DeliveryZone $deliveryZone)
    {
        $item = $deliveryZone;
        return view('admin.delivery.delivery-zones.edit', compact('item'));
    }

    public function update(Request $request, DeliveryZone $deliveryZone)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'city' => 'required|max:255',
            'state' => 'required|max:255',
            'country' => 'required|max:255',
            'zipcode' => 'nullable|max:20',
            'delivery_fee' => 'required|numeric|min:0',
            'min_order_amount' => 'required|numeric|min:0',
            'free_delivery_amount' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $deliveryZone->update($validated);

        return redirect()->route('admin.delivery.zones.index')
            ->with('success', 'Delivery zone updated successfully');
    }

    public function destroy(DeliveryZone $deliveryZone)
    {
        $deliveryZone->delete();

        return redirect()->route('admin.delivery.zones.index')
            ->with('success', 'Delivery zone deleted successfully');
    }
}
