<?php
declare(strict_types=1);

namespace App\Modules\Members\Services;

use App\Core\App;

final class BoardOfferService
{
    public static function getActiveOffers(string $type = ''): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');

        $where = "is_active = 1 AND effective_from <= ? AND effective_to >= ?";
        $params = [$today, $today];

        if ($type !== '') {
            $where .= " AND offer_type = ?";
            $params[] = $type;
        }

        return $db->select("SELECT * FROM board_offers WHERE {$where} ORDER BY effective_from DESC", $params);
    }

    public static function getCashDiscount(): ?array
    {
        $offers = self::getActiveOffers('cash_discount');
        return $offers[0] ?? null;
    }

    public static function getInstallmentTermsOverride(): ?array
    {
        $offers = self::getActiveOffers('installment_terms');
        return $offers[0] ?? null;
    }

    public static function getSubscriptionDiscount(): ?array
    {
        $offers = self::getActiveOffers('subscription_discount');
        return $offers[0] ?? null;
    }

    public static function applyCashDiscount(string $amount): array
    {
        $offer = self::getCashDiscount();
        if (!$offer) {
            return ['amount' => $amount, 'discount' => '0.00', 'offer' => null];
        }

        $pct = $offer['discount_percentage'] ?? '0';
        $discount = bcdiv(bcmul($amount, $pct, 4), '100', 2);
        $final = bcsub($amount, $discount, 2);

        return [
            'amount'   => $final,
            'discount' => $discount,
            'offer'    => $offer,
        ];
    }

    public static function getInstallmentOverrides(): array
    {
        $offer = self::getInstallmentTermsOverride();
        if (!$offer) {
            return [];
        }

        $overrides = [];
        if ($offer['custom_months']) {
            $overrides['max_months'] = (int) $offer['custom_months'];
        }
        if ($offer['custom_interest_rate'] !== null) {
            $overrides['interest_rate'] = $offer['custom_interest_rate'];
        }

        $overrides['offer'] = $offer;
        return $overrides;
    }
}
