<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcInsuranceClaim;
use Modules\Vrc\Entities\VrcInsuranceCompany;
use Modules\Vrc\Entities\VrcRepairOrder;

/**
 * Insurance claims live on a repair order (spec §6.11). Approving a claim with
 * an excess makes the excess the customer's payable on the ERP invoice
 * (applied by ErpInvoiceService at invoice generation).
 */
class InsuranceClaimController extends VrcBaseController
{
    public function store(Request $request, $repairOrderId)
    {
        $this->guard('vrc.insurance.manage');
        $ro = VrcRepairOrder::where('business_id', $this->businessId())->findOrFail($repairOrderId);
        $data = $this->rules($request);

        try {
            $data['business_id'] = $this->businessId();
            $data['repair_order_id'] = $ro->id;
            if (($data['status'] ?? 'draft') === 'submitted' && empty($data['submitted_at'])) {
                $data['submitted_at'] = now();
            }
            VrcInsuranceClaim::create($data);
            return $this->ok(__('vrc::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function update(Request $request, $id)
    {
        $this->guard('vrc.insurance.manage');
        $claim = VrcInsuranceClaim::where('business_id', $this->businessId())->findOrFail($id);
        $data = $this->rules($request);

        try {
            if (in_array($data['status'] ?? null, ['settled']) && empty($claim->settled_at)) {
                $data['settled_at'] = now();
            }
            $claim->update($data);
            return $this->ok(__('vrc::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    /** Claim form (modal) for a repair order. */
    public function form($repairOrderId)
    {
        $this->guard('vrc.insurance.manage');
        $ro = VrcRepairOrder::where('business_id', $this->businessId())->findOrFail($repairOrderId);
        $claim = VrcInsuranceClaim::where('repair_order_id', $ro->id)->latest('id')->first();
        $companies = VrcInsuranceCompany::where('business_id', $this->businessId())->where('is_active', true)->pluck('name', 'id')->toArray();

        return view('vrc::insurance.claim_form', compact('ro', 'claim', 'companies'));
    }

    protected function rules(Request $request): array
    {
        return $this->validate($request, [
            'insurance_company_id' => 'required|integer',
            'policy_no'            => 'nullable|string|max:80',
            'claim_no'             => 'nullable|string|max:80',
            'status'               => 'required|in:draft,submitted,approved,partially_approved,rejected,settled',
            'approved_amount'      => 'nullable|numeric|min:0',
            'excess_amount'        => 'nullable|numeric|min:0',
            'notes'                => 'nullable|string',
        ]);
    }
}
