<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ShippingZone;
use App\Models\ShippingRate;
use Illuminate\Http\Request;

class ShippingRateController extends Controller
{
    public function index(ShippingZone $zone)
    {
        $rates = $zone->rates;
        return view('admin.shipping.rates.index', compact('zone', 'rates'));
    }

    public function create(ShippingZone $zone)
    {
        return view('admin.shipping.rates.create', compact('zone'));
    }

    public function store(Request $request, ShippingZone $zone)
    {
        $validated = $request->validate([
            'service' => 'required|string',
            'service_name' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'delivery_days' => 'required|string',
            'is_active' => 'boolean',
        ]);

        $zone->rates()->create($validated);

        return redirect()->route('admin.shipping.zones.rates.index', $zone)
            ->with('success', 'Shipping rate created successfully.');
    }

    public function edit(ShippingZone $zone, ShippingRate $rate)
    {
        return view('admin.shipping.rates.edit', compact('zone', 'rate'));
    }

    public function update(Request $request, ShippingZone $zone, ShippingRate $rate)
    {
        $validated = $request->validate([
            'service' => 'required|string',
            'service_name' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'delivery_days' => 'required|string',
            'is_active' => 'boolean',
        ]);

        $rate->update($validated);

        return redirect()->route('admin.shipping.zones.rates.index', $zone)
            ->with('success', 'Shipping rate updated successfully.');
    }

    public function calculateRate(Request $request)
    {
        $request->validate([
            'zone_id' => 'required|exists:shipping_zones,id',
            'weight' => 'nullable|numeric|min:0',
            'total' => 'nullable|numeric|min:0'
        ]);

        $rates = ShippingRate::where('shipping_zone_id', $request->zone_id)
            ->where('is_active', true)
            ->get();

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

    public function destroy(ShippingZone $zone, ShippingRate $rate)
    {
        $rate->delete();

        return redirect()->route('admin.shipping.zones.rates.index', $zone)
            ->with('success', 'Shipping rate deleted successfully.');
    }
}