<?php

namespace App\Http\Controllers;

use App\Models\Rate;
use App\Models\Customer;
use Illuminate\Http\Request;

class RateController extends Controller
{
    public function index()
    {
        $rates = Rate::with('customer')->latest()->paginate(10);
        return view('rates.index', compact('rates'));
    }

    public function create()
    {
        $customers = Customer::where('is_active', true)->get();
        return view('rates.create', compact('customers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'nullable|exists:customers,id',
            'type' => 'required|in:domestic,international',
            'country' => 'nullable|required_if:type,international|string',
            'rate_type' => 'required|in:KG,CBM,Per Carton',
            'base_rate' => 'required|numeric',
            'special_rate' => 'nullable|numeric',
            'cargo_type' => 'required|string',
            'service_type' => 'required|string',
            'valid_from' => 'required|date',
            'valid_to' => 'nullable|date',
        ]);

        Rate::create($validated);
        return redirect()->route('rates.index')->with('success', 'Rate created successfully');
    }

    public function edit(Rate $rate)
    {
        $customers = Customer::where('is_active', true)->get();
        return view('rates.edit', compact('rate', 'customers'));
    }

    public function update(Request $request, Rate $rate)
    {
        $validated = $request->validate([
            'customer_id' => 'nullable|exists:customers,id',
            'type' => 'required|in:domestic,international',
            'country' => 'nullable|required_if:type,international|string',
            'rate_type' => 'required|in:KG,CBM,Per Carton',
            'base_rate' => 'required|numeric',
            'special_rate' => 'nullable|numeric',
            'cargo_type' => 'required|string',
            'service_type' => 'required|string',
            'valid_from' => 'required|date',
            'valid_to' => 'nullable|date',
            'is_active' => 'boolean',
        ]);

        $rate->update($validated);
        return redirect()->route('rates.index')->with('success', 'Rate updated successfully');
    }

    public function destroy(Rate $rate)
    {
        $rate->delete();
        return redirect()->route('rates.index')->with('success', 'Rate deleted successfully');
    }
}
