<?php

namespace App\Libraries;

use Modules\Cancellation\Models\CancellationModel;
use Modules\Cancellation\Models\GlobalCancellationModel;

/**
 * Resolves cancellation slabs: global (passenger / online) vs company policy.
 *
 * Each row's `hours` is the notice window: "this charge applies while departure is at least
 * that many hours away" (wider windows = lower %). Pick the smallest tier with hours >= remaining
 * so e.g. 648h before trip uses the 2000h slab (10%), not the 24h slab (20%).
 * If the trip is farther out than every tier, use the widest tier (max hours, usually lowest fee).
 */
class CancellationPolicy
{
    public static function findSlab(float $remainingHours, string $bookbyUserType, int $companyId): ?object
    {
        if ($remainingHours <= 0) {
            return null;
        }

        if ($bookbyUserType === 'passanger') {
            $model = new GlobalCancellationModel();
            $row = $model->select('*')
                ->where('hours >=', $remainingHours)
                ->orderBy('hours', 'ASC')
                ->first();
            if (empty($row)) {
                $row = $model->select('*')->orderBy('hours', 'DESC')->first();
            }

            return $row ?: null;
        }

        $model = new CancellationModel();
        $row = $model->select('*')
            ->where('hours >=', $remainingHours)
            ->where('company_id', $companyId)
            ->orderBy('hours', 'ASC')
            ->first();
        if (empty($row)) {
            $row = $model->select('*')
                ->where('company_id', $companyId)
                ->orderBy('hours', 'DESC')
                ->first();
        }

        return $row ?: null;
    }

    /**
     * @return array{cancel_charge: float|int, refunded_amount: float|int}
     */
    public static function amountsFromSlab(?object $slab, float $totalAmount): array
    {
        if ($totalAmount <= 0) {
            return ['cancel_charge' => 0, 'refunded_amount' => 0];
        }
        if ($slab === null || $slab->charges === null || $slab->charges === '') {
            return ['cancel_charge' => 0, 'refunded_amount' => round($totalAmount)];
        }
        $percentage = (float) $slab->charges;
        $cancelCharge = round($totalAmount * $percentage / 100);
        $refunded = round($totalAmount - $cancelCharge);

        return [
            'cancel_charge' => $cancelCharge,
            'refunded_amount' => max(0, $refunded),
        ];
    }
}
