<?php

namespace App\Http\Controllers;

use App\Models\Tariff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class TariffController extends Controller
{
    public function index()
    {
        $tariffs = Tariff::all();
        return view('modules.edit.tariff-list', compact('tariffs'));
    }

    public function create()
    {
        $lawyers = \App\Models\Lawyer::all();
        $lawyerTiers = \App\Models\LawyerTier::all();
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyerTypes = \App\Models\LawyerType::all();
        $currencies = \App\Models\Currency::all();
        return view('modules.edit.tariff', compact('lawyers', 'lawyerTiers', 'lawyerGroups', 'lawyerTypes', 'currencies'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'lawyer_id' => 'required|string|max:20',
            'tier_id' => 'nullable|integer',
            'group_id' => 'nullable|integer',
            'service_code' => 'required|string|max:30|unique:tariffs,service_code',
            'service_name' => 'required|string|max:150',
            'service_category' => 'required|in:legal_advice,drafting,court_appearance,research,correspondence,filing,consultation,negotiation,conveyancing,other',
            'billing_method' => 'required|in:HOURLY,FIXED_FEE,PER_APPEARANCE,PER_STAGE,RETAINER_PLUS,CONTINGENCY,SUBSCRIPTION',
            'rate_type' => 'required|in:PER_HOUR,PER_CASE,PER_DOCUMENT,PER_APPEARANCE,PER_CONSULTATION,PER_MONTH,PERCENTAGE',
            'rate_amount' => 'required|numeric|min:0',
            'currency_id' => 'required|integer|exists:currencies,currency_id',
            'effective_from' => 'required|date',
            'minimum_fee' => 'nullable|numeric|min:0',
            'maximum_fee' => 'nullable|numeric|min:0',
            'billing_increment' => 'nullable|integer|in:6,15,30,60',
            'minimum_billable_mins' => 'nullable|integer|min:1',
            'retainer_required' => 'boolean',
            'retainer_amount' => 'nullable|numeric|min:0',
            'court_level' => 'nullable|in:MAGISTRATES,HIGH_COURT,SUPREME_COURT,CONSTITUTIONAL_COURT',
            'complexity_level' => 'nullable|in:LOW,MEDIUM,HIGH',
            'tax_inclusive' => 'boolean',
            'vat_rate' => 'nullable|numeric|min:0|max:100',
            'effective_to' => 'nullable|date|after:effective_from',
            'description' => 'nullable|string',
            'notes' => 'nullable|string',
            'is_active' => 'nullable|boolean',
        ]);

        $validated['created_by'] = Auth::id();
        $validated['updated_by'] = Auth::id();
        if (!array_key_exists('is_active', $validated)) {
            $validated['is_active'] = 1;
        }

        Tariff::create($validated);

        return redirect()->route('tariffs.index')->with('success', 'Tariff created successfully.');
    }

    public function show($id)
    {
        $tariff = Tariff::findOrFail($id);
        return view('modules.edit.tariff-show', compact('tariff'));
    }

    public function edit($id)
    {
        $tariff = Tariff::findOrFail($id);
        $lawyers = \App\Models\Lawyer::all();
        $lawyerTiers = \App\Models\LawyerTier::all();
        $lawyerGroups = \App\Models\LawyerGroup::all();
        $lawyerTypes = \App\Models\LawyerType::all();
        $currencies = \App\Models\Currency::all();
        return view('modules.edit.edit-tariff', compact('tariff', 'lawyers', 'lawyerTiers', 'lawyerGroups', 'lawyerTypes', 'currencies'));
    }

    public function update(Request $request, $id)
    {
        $tariff = Tariff::findOrFail($id);

        $validated = $request->validate([
            'lawyer_id' => 'required|string|max:20',
            'tier_id' => 'nullable|integer',
            'group_id' => 'nullable|integer',
            'service_code' => [
                'required',
                'string',
                'max:30',
                Rule::unique('tariffs', 'service_code')->ignore($tariff->tariff_id, 'tariff_id'),
            ],
            'service_name' => 'required|string|max:150',
            'service_category' => 'required|in:legal_advice,drafting,court_appearance,research,correspondence,filing,consultation,negotiation,conveyancing,other',
            'billing_method' => 'required|in:HOURLY,FIXED_FEE,PER_APPEARANCE,PER_STAGE,RETAINER_PLUS,CONTINGENCY,SUBSCRIPTION',
            'rate_type' => 'required|in:PER_HOUR,PER_CASE,PER_DOCUMENT,PER_APPEARANCE,PER_CONSULTATION,PER_MONTH,PERCENTAGE',
            'rate_amount' => 'required|numeric|min:0',
            'currency_id' => 'required|integer|exists:currencies,currency_id',
            'effective_from' => 'required|date',
            'minimum_fee' => 'nullable|numeric|min:0',
            'maximum_fee' => 'nullable|numeric|min:0',
            'billing_increment' => 'nullable|integer|in:6,15,30,60',
            'minimum_billable_mins' => 'nullable|integer|min:1',
            'retainer_required' => 'boolean',
            'retainer_amount' => 'nullable|numeric|min:0',
            'court_level' => 'nullable|in:MAGISTRATES,HIGH_COURT,SUPREME_COURT,CONSTITUTIONAL_COURT',
            'complexity_level' => 'nullable|in:LOW,MEDIUM,HIGH',
            'tax_inclusive' => 'boolean',
            'vat_rate' => 'nullable|numeric|min:0|max:100',
            'effective_to' => 'nullable|date|after:effective_from',
            'description' => 'nullable|string',
            'notes' => 'nullable|string',
            'is_active' => 'nullable|boolean',
        ]);

        $validated['updated_by'] = Auth::id();

        $rateChanged = (string) $tariff->rate_amount !== (string) $validated['rate_amount'];
        if ($rateChanged) {
            $today = now()->toDateString();
            $tariff->update([
                'effective_to' => $today,
                'is_active' => 0,
                'updated_by' => Auth::id(),
            ]);

            $newTariff = $validated;
            $newTariff['effective_from'] = $today;
            $newTariff['effective_to'] = null;
            $newTariff['is_active'] = 1;
            $newTariff['created_by'] = Auth::id();
            Tariff::create($newTariff);

            return redirect()->route('tariffs.index')->with('success', 'Tariff rate updated with version history.');
        }

        $tariff->update($validated);

        return redirect()->route('tariffs.index')->with('success', 'Tariff updated successfully.');
    }

    public function destroy($id)
    {
        $tariff = Tariff::findOrFail($id);
        $tariff->update([
            'deleted_at' => now(),
            'is_active' => 0,
            'updated_by' => Auth::id(),
        ]);

        return redirect()->route('tariffs.index')->with('success', 'Tariff archived successfully.');
    }
}
