<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

final class DiscountCalculatorService
{
    /**
     * Calculate all applicable discounts for a subscription amount.
     */
    public static function calculateDiscounts(
        float $subscriptionAmount,
        int $months,
        bool $hasSibling,
        ?string $academyCode = null
    ): array {
        $discounts = [];
        $totalDiscount = 0.0;

        if ($months >= 3) {
            $advance = self::getAdvanceDiscount($subscriptionAmount);
            if ($advance) {
                $totalDiscount += $advance['amount'];
                $discounts[] = $advance;
            }
        }

        if ($hasSibling) {
            $remaining = $subscriptionAmount - $totalDiscount;
            $sibling = self::getSiblingDiscount($remaining, $academyCode);
            if ($sibling) {
                $totalDiscount += $sibling['amount'];
                $discounts[] = $sibling;
            }
        }

        return [
            'discounts' => $discounts,
            'total_discount' => round($totalDiscount, 2),
            'final_amount' => round($subscriptionAmount - $totalDiscount, 2),
        ];
    }

    private static function getAdvanceDiscount(float $amount): ?array
    {
        $db = App::getInstance()->db();

        $rule = $db->selectOne(
            "SELECT * FROM sa_discount_rules WHERE rule_code = 'ADVANCE_3MONTHS_15PCT' AND is_active = 1",
            []
        );

        if (!$rule) {
            return null;
        }

        $discountAmount = $amount * ((float) $rule['discount_value'] / 100);

        return [
            'code' => 'ADVANCE_3MONTHS_15PCT',
            'name_ar' => $rule['name_ar'],
            'amount' => round($discountAmount, 2),
            'percentage' => (float) $rule['discount_value'],
        ];
    }

    private static function getSiblingDiscount(float $remainingAmount, ?string $academyCode): ?array
    {
        $db = App::getInstance()->db();

        $rule = $db->selectOne(
            "SELECT * FROM sa_discount_rules WHERE condition_type = 'sibling' AND is_active = 1",
            []
        );

        if (!$rule) {
            return null;
        }

        $ruleAcademy = $rule['academy_code'] ?? null;
        if ($ruleAcademy && $academyCode && $ruleAcademy !== $academyCode) {
            return null;
        }

        $discountAmount = $remainingAmount * ((float) $rule['discount_value'] / 100);

        return [
            'code' => $rule['rule_code'],
            'name_ar' => $rule['name_ar'],
            'amount' => round($discountAmount, 2),
            'percentage' => (float) $rule['discount_value'],
        ];
    }
}
