<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\ShippingZone;
use Illuminate\Http\Request;

class ShippingController extends Controller {
    public function index() {
        $zones = ShippingZone::orderBy('name')->get();
        return view('admin.shipping.index', compact('zones'));
    }

    public function create() {
        return view('admin.shipping.form', ['zone' => new ShippingZone()]);
    }

    public function store(Request $request) {
        $data = $request->validate([
            'name'           => 'required|string|max:100',
            'charge'         => 'required|numeric|min:0',
            'free_above'     => 'required|numeric|min:0',
            'estimated_days' => 'required|integer|min:1',
            'pincodes'       => 'nullable|string',
        ]);
        $data['pincodes'] = $data['pincodes'] ? array_filter(array_map('trim', preg_split('/[\s,]+/', $data['pincodes']))) : [];
        $data['active'] = $request->boolean('active');
        ShippingZone::create($data);
        return redirect()->route('admin.shipping')->with('success', 'Shipping zone created!');
    }

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

    public function update(Request $request, ShippingZone $zone) {
        $data = $request->validate([
            'name'           => 'required|string|max:100',
            'charge'         => 'required|numeric|min:0',
            'free_above'     => 'required|numeric|min:0',
            'estimated_days' => 'required|integer|min:1',
            'pincodes'       => 'nullable|string',
        ]);
        $data['pincodes'] = $data['pincodes'] ? array_filter(array_map('trim', preg_split('/[\s,]+/', $data['pincodes']))) : [];
        $data['active'] = $request->boolean('active');
        $zone->update($data);
        return redirect()->route('admin.shipping')->with('success', 'Shipping zone updated!');
    }

    public function destroy(ShippingZone $zone) {
        $zone->delete();
        return back()->with('success', 'Zone deleted.');
    }
}
