<?php

namespace App\Service;

use A7kz\Platform\Models\UniModel;
use Illuminate\Support\Carbon;

class DepositService
{
    public function calcWithoutDeposit($deposit, $day): float {
        $percentRates = [
            3.00, 3.00, 3.00, 4.05, 5.10, 6.15, 7.20, 8.25, 9.30,
            10.35, 11.40, 12.45, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00,
            13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00, 13.00,
            13.44, 13.88, 14.32, 14.76, 15.20
        ];

        $ndsRate = 0.12;
        $lastKnownRate = 15.20;

        $index = $day - 1;

        $percent = $percentRates[$index] ?? $lastKnownRate;

        if ($percent === null) {
            return 0.0;
        }

        $sum = $deposit * ($percent / 100) * (1 + $ndsRate);
        return round($sum, 2);
    }

    /**
     * @throws \Exception
     */
    public function calculateSummary(int $markId, $start, $end): array
    {
        $fullDays = $start->copy()->diffInDays($end); // 7
        $totalHours = $start->copy()->diffInHours($end); // 191 часов
        $hoursRemainder = $totalHours - ($fullDays * 24); // остаток: 191 - 7*24 = 191 - 168 = 23

        $threshold = 9; // если остаток по часам больше этого порога, то добавим день

        $days = $fullDays + ($hoursRemainder > $threshold ? 1 : 0);

        $tariffs = UniModel::model('pipi_auto_tariffs')
            ->where('model_id', $markId)
            ->get();

        if ($tariffs->isEmpty()) {
            throw new \Exception(__('Отсутствуют данные по машине'));
        }

        $basePrice = null;
        $discountRate = null;
        $deposit = null;

        foreach ($tariffs as $range) {
            if ($range->day_range_start == 1 && $range->day_range_end == 2) {
                $basePrice = $range->base_rate;
            }

            if (isset($range->deposit)) {
                $deposit = $range->deposit;
            }

            if ($days >= $range->day_range_start && $days <= $range->day_range_end) {
                $discountRate = $range->base_rate;
            }
        }

        // Если не нашли скидку, но дней > 30
        if (is_null($discountRate) && $days > 30 && $basePrice) {
            $discountRate = round($basePrice * 0.6);
        }

        $baseSum = $basePrice ? $basePrice * $days : null;
        $discountedSum = $discountRate ? $discountRate * $days : null;

        return [
            'days' => $days,
            'base_price_per_day' => $basePrice,
            'discount_price_per_day' => $discountRate,
            'base_sum' => $baseSum,
            'discounted_sum' => $discountedSum,
            'deposit_base' => $deposit,
            'without_deposit' => $this->calcWithoutDeposit($deposit, $days),
        ];
    }
}
