<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Courier;
use App\Models\Outlet;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Http\RedirectResponse;

class CourierController extends Controller
{
    public function index(): Response
    {
        $couriers = Courier::with(['outlet'])->latest()->get();
        $outlets = Outlet::select('id', 'name')->get();

        return Inertia::render('CafePOS/Couriers/Index', [
            'couriers' => $couriers,
            'outlets' => $outlets,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:50'],
            'vehicle_number' => ['required', 'string', 'max:50'],
            'outlet_id' => ['required', 'integer', 'exists:outlets,id'],
            'is_active' => ['required', 'boolean'],
        ]);

        Courier::create($request->only(['name', 'phone', 'vehicle_number', 'outlet_id', 'is_active']));

        return redirect()->back()->with('success', 'Kurir berhasil ditambahkan.');
    }

    public function update(Request $request, Courier $courier): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:50'],
            'vehicle_number' => ['required', 'string', 'max:50'],
            'outlet_id' => ['required', 'integer', 'exists:outlets,id'],
            'is_active' => ['required', 'boolean'],
        ]);

        $courier->update($request->only(['name', 'phone', 'vehicle_number', 'outlet_id', 'is_active']));

        return redirect()->back()->with('success', 'Data kurir berhasil diperbarui.');
    }

    public function destroy(Courier $courier): RedirectResponse
    {
        $courier->delete();
        return redirect()->back()->with('success', 'Kurir berhasil dihapus.');
    }
}
