<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryType;
use App\Models\Setting;
use Illuminate\Http\Request;

class DeliveryTypeController extends Controller
{
    public function index()
    {
        $types = DeliveryType::all();
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';
        return view('admin.delivery_types.index', compact('types', 'currencySymbol'));
    }

    public function create()
    {
        return view('admin.delivery_types.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'cost' => 'required|numeric|min:0',
            'estimated_time' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        DeliveryType::create([
            'name' => $request->name,
            'cost' => $request->cost,
            'estimated_time' => $request->estimated_time,
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

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

    public function edit(DeliveryType $deliveryType)
    {
        return view('admin.delivery_types.edit', compact('deliveryType'));
    }

    public function update(Request $request, DeliveryType $deliveryType)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'cost' => 'required|numeric|min:0',
            'estimated_time' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        $deliveryType->update([
            'name' => $request->name,
            'cost' => $request->cost,
            'estimated_time' => $request->estimated_time,
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

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

    public function destroy(DeliveryType $deliveryType)
    {
        $deliveryType->delete();
        return redirect()->route('admin.delivery-types.index')->with('success', 'Delivery Type deleted successfully.');
    }
}
