<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\DeliveryZone;
use App\Models\Supplier;
use App\Models\SupplierDeliveryRate;
use App\Services\DeliveryCalculatorService;
use Illuminate\Http\Request;

class DeliveryController extends Controller
{
    protected DeliveryCalculatorService $deliveryService;

    public function __construct(DeliveryCalculatorService $deliveryService)
    {
        $this->middleware('auth');
        $this->deliveryService = $deliveryService;
    }

    public function calculate()
    {
        $zones = DeliveryZone::where('is_active', true)
            ->orderBy('min_distance_km')
            ->get();

        return view('delivery.calculate', compact('zones'));
    }

    public function estimate(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'city' => 'required|string',
            'province' => 'nullable|string',
            'postal_code' => 'nullable|string',
            'weight' => 'nullable|numeric|min:0',
            'order_total' => 'nullable|numeric|min:0',
        ]);

        $supplier = Supplier::findOrFail($request->supplier_id);

        $result = $this->deliveryService->calculateDeliveryCost(
            $supplier,
            $request->city,
            $request->province,
            $request->postal_code,
            $request->weight ?? 0,
            $request->order_total ?? 0
        );

        if ($request->ajax()) {
            return response()->json($result);
        }

        return back()->with('delivery_result', $result);
    }

    // Admin: Manage delivery zones
    public function zones()
    {
        $zones = DeliveryZone::orderBy('min_distance_km')->get();

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

    public function storeZone(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'min_distance_km' => 'required|integer|min:0',
            'max_distance_km' => 'required|integer|gt:min_distance_km',
            'base_rate' => 'required|numeric|min:0',
            'rate_per_km' => 'required|numeric|min:0',
            'rate_per_kg' => 'required|numeric|min:0',
            'estimated_days_min' => 'required|integer|min:1',
            'estimated_days_max' => 'required|integer|gte:estimated_days_min',
        ]);

        DeliveryZone::create($request->all());

        return back()->with('success', 'Delivery zone created successfully!');
    }

    public function updateZone(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'min_distance_km' => 'required|integer|min:0',
            'max_distance_km' => 'required|integer|gt:min_distance_km',
            'base_rate' => 'required|numeric|min:0',
            'rate_per_km' => 'required|numeric|min:0',
            'rate_per_kg' => 'required|numeric|min:0',
            'estimated_days_min' => 'required|integer|min:1',
            'estimated_days_max' => 'required|integer|gte:estimated_days_min',
        ]);

        $zone = DeliveryZone::findOrFail($id);
        $zone->update($request->all());

        return back()->with('success', 'Delivery zone updated successfully!');
    }

    public function deleteZone($id)
    {
        $zone = DeliveryZone::findOrFail($id);
        $zone->delete();

        return back()->with('success', 'Delivery zone deleted successfully!');
    }

    // Supplier: Manage their delivery rates
    public function supplierRates()
    {
        $supplier = auth()->user()->supplier;
        
        if (!$supplier) {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $zones = DeliveryZone::where('is_active', true)
            ->orderBy('min_distance_km')
            ->get();

        $supplierRates = SupplierDeliveryRate::where('supplier_id', $supplier->id)
            ->get()
            ->keyBy('delivery_zone_id');

        return view('supplier.delivery-rates', compact('zones', 'supplierRates', 'supplier'));
    }

    public function updateSupplierRates(Request $request)
    {
        $supplier = auth()->user()->supplier;
        
        if (!$supplier) {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $request->validate([
            'rates' => 'required|array',
            'rates.*.delivery_zone_id' => 'required|exists:delivery_zones,id',
            'rates.*.base_rate' => 'nullable|numeric|min:0',
            'rates.*.rate_per_km' => 'nullable|numeric|min:0',
            'rates.*.rate_per_kg' => 'nullable|numeric|min:0',
            'rates.*.free_delivery_threshold' => 'nullable|numeric|min:0',
            'rates.*.is_active' => 'boolean',
        ]);

        foreach ($request->rates as $rateData) {
            SupplierDeliveryRate::updateOrCreate(
                [
                    'supplier_id' => $supplier->id,
                    'delivery_zone_id' => $rateData['delivery_zone_id'],
                ],
                [
                    'base_rate' => $rateData['base_rate'] ?? null,
                    'rate_per_km' => $rateData['rate_per_km'] ?? null,
                    'rate_per_kg' => $rateData['rate_per_kg'] ?? null,
                    'free_delivery_threshold' => $rateData['free_delivery_threshold'] ?? null,
                    'is_active' => $rateData['is_active'] ?? true,
                ]
            );
        }

        return back()->with('success', 'Delivery rates updated successfully!');
    }
}
