<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsSetting;
use Modules\Bms\Services\Booking\CancellationService;
use Modules\Bms\Services\Finance\PaymentPlanService;

/**
 * P1 editor for the booking financial policy: the cancellation/reschedule
 * penalty tiers (days + %), the payment-schedule template, and the
 * deposit-before-contract gate. All persisted per-business to bms_settings;
 * the engine falls back to config defaults when unset.
 */
class BookingPolicyController extends BmsBaseController
{
    public function edit()
    {
        $this->guard('bms.settings.access');
        $biz = $this->businessId();

        return view('bms::settings.booking_policy', [
            'policy'   => app(CancellationService::class)->policy($biz),
            'reasons'  => app(CancellationService::class)->reasons($biz),
            'schedule' => (array) (BmsSetting::get($biz, 'payment_schedule_template', null)
                ?: config('bms.payment_schedule_template', [])),
            'enforceDeposit' => (bool) BmsSetting::get($biz, 'enforce_deposit_gate', config('bms.enforce_deposit_gate', false)),
        ]);
    }

    public function update(Request $request)
    {
        $this->guard('bms.settings.access');
        $biz = $this->businessId();

        // ---- Cancellation policy -----------------------------------------
        $tiers = [];
        foreach ((array) $request->input('tier_days', []) as $i => $days) {
            $days = (int) $days;
            $pct = (float) ($request->input('tier_pct')[$i] ?? 0);
            if ($days > 0) {
                $tiers[] = ['days_before' => $days, 'penalty_percent' => max(0, min(100, $pct))];
            }
        }
        // Most severe first when applied; store sorted ascending for clarity.
        usort($tiers, fn ($a, $b) => $a['days_before'] <=> $b['days_before']);

        BmsSetting::put($biz, 'cancellation_policy', [
            'enabled'                 => $request->boolean('enabled'),
            'basis'                   => 'invoice_total',
            'default_penalty_percent' => max(0, min(100, (float) $request->input('default_penalty_percent', 0))),
            'reschedule_uses_policy'  => $request->boolean('reschedule_uses_policy'),
            'tiers'                   => $tiers,
        ]);

        // ---- Payment schedule template -----------------------------------
        $schedule = [];
        foreach ((array) $request->input('sched_label', []) as $i => $label) {
            $pct = (float) ($request->input('sched_pct')[$i] ?? 0);
            $label = trim((string) $label);
            if ($label !== '' && $pct > 0) {
                $schedule[] = [
                    'label'       => $label,
                    'kind'        => $request->input('sched_kind')[$i] ?? 'installment',
                    'percent'     => $pct,
                    'offset_days' => (int) ($request->input('sched_offset')[$i] ?? 0),
                ];
            }
        }
        if (! empty($schedule)) {
            BmsSetting::put($biz, 'payment_schedule_template', $schedule);
        }

        // ---- Cancellation reasons -----------------------------------------
        $reasons = [];
        foreach ((array) $request->input('reason_code', []) as $i => $code) {
            $code = trim((string) $code);
            $en = trim((string) ($request->input('reason_en')[$i] ?? ''));
            if ($code !== '' && $en !== '') {
                $reasons[] = ['code' => \Illuminate\Support\Str::slug($code, '_'), 'en' => $en, 'ar' => trim((string) ($request->input('reason_ar')[$i] ?? ''))];
            }
        }
        if (! empty($reasons)) {
            BmsSetting::put($biz, 'cancellation_reasons', $reasons);
        }

        // ---- Deposit gate -------------------------------------------------
        BmsSetting::put($biz, 'enforce_deposit_gate', $request->boolean('enforce_deposit_gate') ? 1 : 0);

        return redirect()->route('bms.booking-policy.edit')
            ->with('status', ['success' => 1, 'msg' => __('bms::lang.success')]);
    }
}
