<?php

namespace App\Http\Controllers\INSURANCE;

use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\INSURANCE\Insurer;
use App\Http\Controllers\Controller;
use App\Models\INSURANCE\InsuranceType;
use App\Models\INSURANCE\CommissionDefault;
use App\Http\Requests\INSURANCE\CommissionDefaultRequest;

class CommissionDefaultController extends Controller
{
    public function index(Insurer $insurer)
    {
        // assumes Insurer model has commissionDefaults() WITH insuranceType()
        $defaults = $insurer
            ->commissionDefaults()
            ->with('insuranceType')
            ->orderBy('insurance_type_id')
            ->get()
            ->map(function (CommissionDefault $cd) {
                return [
                    'id'              => $cd->id,
                    'type_name'       => $cd->insuranceType->description,      // adjust your column
                    'commission_rate' => $cd->commission_rate,
                ];
            });

        return response()->json($defaults);
    }


    /**
     * Show the form for creating new commission defaults for an insurer.
     */
    public function create(Insurer $insurer)
    {
        $insuranceTypes = InsuranceType::whereNull('parent_id')
            ->with('childrenRecursive')
            ->get();
        $defaults = collect(); // No defaults yet for create

        // Set form action and method for creation.
        $formAction = route('osiguranje.commission-defaults.store', $insurer);
        $method = 'POST';

        return view('backend.insurance.commission-defaults.create', compact('insurer', 'insuranceTypes', 'defaults', 'formAction', 'method'));
    }

    /**
     * Store the new commission defaults.
     */
    public function store(Request $request, Insurer $insurer)
    {
        $data = $request->validate([
            // commission_defaults must be an array.
            'commission_defaults'   => 'required|array',
            // Each commission default should be numeric (or null) and between 0 and 100.
            'commission_defaults.*' => 'nullable|numeric|min:0|max:100',
        ]);

        // Use the existing insurer (do not create a new one).
        // Handle commission defaults – insert only non-empty values.
        foreach ($data['commission_defaults'] as $insuranceTypeId => $commissionRate) {
            if ($commissionRate === null || $commissionRate === '') {
                continue;  // Skip empty commission default fields.
            }
            // Create a commission default record for this insurer.
            $insurer->commissionDefaults()->create([
                'insurance_type_id' => $insuranceTypeId,
                'commission_rate'   => $commissionRate,
            ]);
        }

        return redirect()->route('osiguranje.commission-defaults.edit', $insurer)
            ->with('success', 'Commission defaults created successfully.');
    }

    /**
     * Show the form for editing commission defaults for an insurer.
     */
    public function edit(Insurer $insurer)
    {
        $insuranceTypes = InsuranceType::whereNull('parent_id')
            ->with('childrenRecursive')
            ->get();
        $defaults = CommissionDefault::where('insurer_id', $insurer->id)
            ->get()
            ->keyBy('insurance_type_id');

        // Set form action and method for update.
        $formAction = route('osiguranje.commission-defaults.update', $insurer);
        $method = 'PUT';

        return view('backend.insurance.commission-defaults.edit', compact('insurer', 'insuranceTypes', 'defaults', 'formAction', 'method'));
    }

    /**
     * Update the commission defaults for an insurer.
     *
     * In edit mode:
     * - A non-empty value will create or update a record.
     * - An empty value will delete an existing record.
     */
    public function update(Request $request, Insurer $insurer)
    {
        $data = $request->validate([
            'commission_defaults'   => 'required|array',
            'commission_defaults.*' => 'nullable|numeric|min:0|max:100',
        ]);
        $insurer->update(Arr::except($data, ['commission_defaults']));

        // Loop through all submitted commission default fields.
        foreach ($data['commission_defaults'] as $insuranceTypeId => $commissionRate) {
            if ($commissionRate === null || $commissionRate === '') {
                // If the field is empty, remove any existing default from the DB.
                $insurer->commissionDefaults()->where('insurance_type_id', $insuranceTypeId)->delete();
                continue;
            }
            // Otherwise, update existing or create a new default.
            $insurer->commissionDefaults()->updateOrCreate(
                ['insurance_type_id' => $insuranceTypeId],
                ['commission_rate' => $commissionRate]
            );
        }

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