<?php

namespace App\Http\Controllers\INSURANCE;

use App\Models\CRM\Entity;
use Illuminate\Http\Request;
use App\Models\INSURANCE\Insurer;
use App\Http\Controllers\Controller;
use App\Models\INSURANCE\InsurancePolicy;
use App\Http\Requests\INSURANCE\InsurancePolicyRequest;
use App\Models\INSURANCE\CommissionDefault;

class InsurancePolicyController extends Controller
{
    public function index(Entity $entity)
    {
        $policies = InsurancePolicy::with('entity.entityable', 'insurer')->where('entity_id', $entity->id)->get();
        return view('backend.insurance.insurance-policies.index', compact('entity', 'policies'));
    }

    public function create(Entity $entity)
    {
        $readonly = null;
        $insurers = Insurer::with('commissionDefaults')->orderBy('short_name', 'asc')->get();
        $idBroj = $entity->entityable->lastActiveIdCard->jmbg ?? $entity->entityable->lastActivePassport->jmbg ?? null;
        return view('backend.insurance.insurance-policies.create', compact('entity', 'insurers','idBroj', 'readonly'));
    }
    public function store(InsurancePolicyRequest $request, Entity $entity)
    {
        $data = $request->validated();
        $commission_pct_default = CommissionDefault::where('id', $data['commission_default_id'])->value('commission_rate');
        $expected_commission = $data['premium'] * ($commission_pct_default / 100);
        $data['entity_id'] = $entity->id;   
        $data['commission_pct_default'] = $commission_pct_default;
        $data['commission_pct'] = $commission_pct_default;
        $data['expected_commission'] = $expected_commission;
        $insurancePolicy = InsurancePolicy::create($data);
        return redirect()
            ->route('osiguranje.insurance-policies.edit', ['entity' => $entity, 'insurancePolicy' => $insurancePolicy])
            ->with('success', 'Insurance policy created successfully.');
    }


    public function edit(Entity $entity, InsurancePolicy $insurancePolicy)
    {
        $readonly = null;
 
        $idBroj = $entity->entityable->lastActiveIdCard->jmbg ?? $entity->entityable->lastActivePassport->jmbg ?? null;

        return view('backend.insurance.insurance-policies.edit', compact('entity', 'insurancePolicy', 'idBroj', 'readonly'));
    }

    public function update(InsurancePolicyRequest $request, Entity $entity, InsurancePolicy $insurancePolicy)
    {
        $data = $request->validated();

        $data['expected_commission'] = $data['premium'] * ($data['commission_pct'] / 100);

        $insurancePolicy->update($data);

        return redirect()
            ->back()
            ->with('success', 'Insurance policy updated successfully.');
    }

    public function destroy(Entity $entity, InsurancePolicy $insurancePolicy)
    {
        $insurancePolicy->delete();

        return redirect()
            ->route('osiguranje.insurance-policies.index', ['entity' => $entity->id])
            ->with('success', 'Insurance policy deleted successfully.');
    }
}
