<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryDriver;
use App\Models\User;
use Illuminate\Http\Request;

class DeliveryDriverController extends Controller
{
    public function index()
    {
        $items = DeliveryDriver::with('user')->latest()->paginate(10);
        return view('admin.delivery.delivery-drivers.index', compact('items'));
    }

    public function create()
    {
        $users = User::all();
        return view('admin.delivery.delivery-drivers.create', compact('users'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'vehicle_type' => 'required|max:255',
            'vehicle_number' => 'required|max:255',
            'license_number' => 'required|max:255',
            'license_expiry' => 'required|date',
            'is_active' => 'boolean',
            'is_available' => 'boolean',
        ]);

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

        DeliveryDriver::create($validated);

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

    public function edit(DeliveryDriver $deliveryDriver)
    {
        $item = $deliveryDriver;
        $users = User::all();
        return view('admin.delivery.delivery-drivers.edit', compact('item', 'users'));
    }

    public function update(Request $request, DeliveryDriver $deliveryDriver)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'vehicle_type' => 'required|max:255',
            'vehicle_number' => 'required|max:255',
            'license_number' => 'required|max:255',
            'license_expiry' => 'required|date',
            'is_active' => 'boolean',
            'is_available' => 'boolean',
        ]);

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

        $deliveryDriver->update($validated);

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

    public function destroy(DeliveryDriver $deliveryDriver)
    {
        $deliveryDriver->delete();

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