<?php
declare(strict_types=1);

namespace App\Modules\Reservations\Services;

use App\Core\App;

final class FacilityPricingService
{
    private static ?array $memberPricing = null;
    private static ?array $nonMemberPricing = null;
    private static ?array $generalFees = null;

    public static function calculateRate(int $facilityId, bool $isMember, string $timeTier = 'AM'): ?float
    {
        $db = App::getInstance()->db();
        $facility = $db->selectOne("SELECT * FROM facilities WHERE id = ?", [$facilityId]);
        if (!$facility) {
            return null;
        }

        $rateCol = $timeTier === 'PM'
            ? ($isMember ? 'hourly_rate_member_pm' : 'hourly_rate_nonmember_pm')
            : ($isMember ? 'hourly_rate_member' : 'hourly_rate_nonmember');

        $directRate = (float) ($facility[$rateCol] ?? 0);
        if ($directRate > 0) {
            return $directRate;
        }

        $facilityType = $facility['facility_type'] ?? '';
        if (empty($facilityType)) {
            return null;
        }

        $pricing = $isMember ? self::loadMemberPricing() : self::loadNonMemberPricing();

        foreach ($pricing as $rule) {
            if (($rule['facility_type'] ?? '') === $facilityType) {
                return (float) ($timeTier === 'PM'
                    ? ($rule['price_evening'] ?? 0)
                    : ($rule['price_morning'] ?? 0));
            }
        }

        return null;
    }

    public static function getEntryTicketPrice(string $dayType, bool $isAbove12): ?float
    {
        $db = App::getInstance()->db();
        $json = $db->selectOne(
            "SELECT config_value FROM system_config WHERE config_key = 'entry_tickets_non_member'"
        );
        if (!$json) {
            return null;
        }

        $tickets = json_decode($json['config_value'], true) ?: [];
        foreach ($tickets as $ticket) {
            if (($ticket['day_type'] ?? '') === $dayType) {
                return (float) ($isAbove12 ? $ticket['age_above_12'] : $ticket['age_6_to_12']);
            }
        }

        return null;
    }

    public static function getGeneralFee(string $feeCode): ?float
    {
        $fees = self::loadGeneralFees();
        foreach ($fees as $fee) {
            if (($fee['code'] ?? '') === $feeCode) {
                return (float) ($fee['amount'] ?? 0);
            }
        }
        return null;
    }

    public static function getAllPricingForFacilityType(string $facilityType): array
    {
        $memberPricing = self::loadMemberPricing();
        $nonMemberPricing = self::loadNonMemberPricing();

        $result = ['member' => null, 'non_member' => null];

        foreach ($memberPricing as $rule) {
            if (($rule['facility_type'] ?? '') === $facilityType) {
                $result['member'] = $rule;
                break;
            }
        }

        foreach ($nonMemberPricing as $rule) {
            if (($rule['facility_type'] ?? '') === $facilityType) {
                $result['non_member'] = $rule;
                break;
            }
        }

        return $result;
    }

    private static function loadMemberPricing(): array
    {
        if (self::$memberPricing !== null) {
            return self::$memberPricing;
        }

        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = 'sports_pricing_member'");
        self::$memberPricing = $row ? (json_decode($row['config_value'], true) ?: []) : [];
        return self::$memberPricing;
    }

    private static function loadNonMemberPricing(): array
    {
        if (self::$nonMemberPricing !== null) {
            return self::$nonMemberPricing;
        }

        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = 'sports_pricing_non_member'");
        self::$nonMemberPricing = $row ? (json_decode($row['config_value'], true) ?: []) : [];
        return self::$nonMemberPricing;
    }

    private static function loadGeneralFees(): array
    {
        if (self::$generalFees !== null) {
            return self::$generalFees;
        }

        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT config_value FROM system_config WHERE config_key = 'general_fees'");
        self::$generalFees = $row ? (json_decode($row['config_value'], true) ?: []) : [];
        return self::$generalFees;
    }
}
