<?php
/**
 * GEM ACC v27.42 shared-account price helper.
 *
 * Important rule:
 * - Windscribe prices in this project are already stored in plans.price exactly like the bot uses them.
 *   The mini app must NOT divide Windscribe prices again unless the admin explicitly enables
 *   windscribe_unit_sale_enabled=1.
 * - ExpressVPN/OpenVPN unit-sale compatibility remains available through *_sale_seats settings.
 * - Purchase/cost calculation uses *_purchase_seats separately and must not affect customer sale price.
 */
if (!function_exists('gemacc_plan_price_service_type')) {
    function gemacc_plan_price_service_type(array $plan): string {
        $raw = strtolower(trim((string)($plan['protocol'] ?? $plan['service_type'] ?? $plan['category_service_type'] ?? 'openvpn_l2tp')));
        $hint = strtolower(trim((string)(($plan['service_name'] ?? '') . ' ' . ($plan['category_service_name'] ?? '') . ' ' . ($plan['category_name'] ?? '') . ' ' . ($plan['title'] ?? '') . ' ' . ($plan['code'] ?? '') . ' ' . ($plan['category_code'] ?? ''))));
        if (in_array($raw, ['windscribe','ws'], true) || strpos($hint, 'windscribe') !== false || strpos($hint, 'ویندسکرایب') !== false || strpos($hint, 'ws_') !== false) return 'windscribe';
        if (in_array($raw, ['expressvpn','express','express vpn'], true) || strpos($hint, 'express') !== false || strpos($hint, 'اکسپرس') !== false || strpos($hint, 'exp_') !== false) return 'expressvpn';
        if (in_array($raw, ['v2ray','v2','vmess','vless','trojan'], true) || strpos($hint, 'v2ray') !== false || strpos($hint, 'v2_') !== false || strpos($hint, 'vmess') !== false || strpos($hint, 'vless') !== false || strpos($hint, 'trojan') !== false || strpos($hint, 'ویتوری') !== false || strpos($hint, 'وی تو ری') !== false) return 'v2ray';
        return 'openvpn_l2tp';
    }
}
if (!function_exists('gemacc_plan_price_setting')) {
    function gemacc_plan_price_setting(string $key, $default = null) {
        try {
            if (function_exists('getSetting')) return getSetting($key, $default);
        } catch (Throwable $e) {}
        return $default;
    }
}
if (!function_exists('gemacc_plan_price_bool_setting')) {
    function gemacc_plan_price_bool_setting(string $key, bool $default = false): bool {
        $v = gemacc_plan_price_setting($key, $default ? '1' : '0');
        if (is_bool($v)) return $v;
        $s = strtolower(trim((string)$v));
        return in_array($s, ['1','true','yes','on','enabled'], true);
    }
}
if (!function_exists('gemacc_plan_price_month_bucket')) {
    function gemacc_plan_price_month_bucket(array $plan): string {
        $months = max(1, (int)($plan['months'] ?? $plan['category_months'] ?? 1));
        return $months >= 12 ? 'year' : 'month';
    }
}
if (!function_exists('gemacc_plan_price_prefixes')) {
    function gemacc_plan_price_prefixes(string $svc): array {
        $prefixes = [$svc];
        if ($svc === 'expressvpn') $prefixes[] = 'express';
        if ($svc === 'openvpn_l2tp') $prefixes[] = 'openvpn';
        return $prefixes;
    }
}
if (!function_exists('gemacc_plan_sale_divisor')) {
    function gemacc_plan_sale_divisor(array $plan): int {
        $svc = gemacc_plan_price_service_type($plan);
        $bucket = gemacc_plan_price_month_bucket($plan);

        // Windscribe is the historical path used by the bot: plans.price is already the final customer price.
        // Dividing it again in the mini app caused prices such as 45,000/90,000 while the bot showed the correct value.
        // Keep division disabled for Windscribe unless the admin intentionally enables it in settings.
        if ($svc === 'windscribe' && !gemacc_plan_price_bool_setting('windscribe_unit_sale_enabled', false)) {
            return 1;
        }

        $divisor = 1;
        foreach (gemacc_plan_price_prefixes($svc) as $prefix) {
            $saleSeats = (int)gemacc_plan_price_setting($prefix . '_' . $bucket . '_sale_seats', 0);
            if ($saleSeats > 1) $divisor = max($divisor, $saleSeats);
        }

        // Optional explicit per-plan override if a future migration adds it.
        foreach (['unit_price_divisor','sale_seats','price_divisor'] as $field) {
            if (isset($plan[$field]) && (int)$plan[$field] > 1) $divisor = max($divisor, (int)$plan[$field]);
        }
        return max(1, $divisor);
    }
}
if (!function_exists('gemacc_plan_purchase_divisor')) {
    function gemacc_plan_purchase_divisor(array $plan): int {
        $svc = gemacc_plan_price_service_type($plan);
        $bucket = gemacc_plan_price_month_bucket($plan);
        $divisor = max(1, (int)($plan['user_count'] ?? 0), (int)($plan['seats'] ?? 0), (int)($plan['requested_seats'] ?? 0));
        foreach (gemacc_plan_price_prefixes($svc) as $prefix) {
            $purchaseSeats = (int)gemacc_plan_price_setting($prefix . '_' . $bucket . '_purchase_seats', 0);
            if ($purchaseSeats > 1) $divisor = max($divisor, $purchaseSeats);
        }
        return max(1, $divisor);
    }
}
// Backward-compatible name: sale divisor.
if (!function_exists('gemacc_plan_unit_divisor')) {
    function gemacc_plan_unit_divisor(array $plan): int {
        return gemacc_plan_sale_divisor($plan);
    }
}
if (!function_exists('gemacc_plan_effective_sale_price')) {
    function gemacc_plan_effective_sale_price(array $plan): int {
        $raw = max(0, (int)($plan['price'] ?? 0));
        $div = gemacc_plan_sale_divisor($plan);
        return $div > 1 ? (int)ceil($raw / $div) : $raw;
    }
}
if (!function_exists('gemacc_plan_effective_purchase_price')) {
    function gemacc_plan_effective_purchase_price(array $plan): int {
        $raw = max(0, (int)($plan['purchase_price'] ?? 0));
        if ($raw <= 0) return 0;
        $div = gemacc_plan_purchase_divisor($plan);
        return $div > 1 ? (int)ceil($raw / $div) : $raw;
    }
}
if (!function_exists('gemacc_plan_apply_unit_price_fields')) {
    function gemacc_plan_apply_unit_price_fields(array $plan): array {
        $rawSale = max(0, (int)($plan['price'] ?? 0));
        $rawPurchase = max(0, (int)($plan['purchase_price'] ?? 0));
        $saleDiv = gemacc_plan_sale_divisor($plan);
        $purchaseDiv = gemacc_plan_purchase_divisor($plan);
        $unitSale = $saleDiv > 1 ? (int)ceil($rawSale / $saleDiv) : $rawSale;
        $unitPurchase = $purchaseDiv > 1 ? (int)ceil($rawPurchase / $purchaseDiv) : $rawPurchase;
        $plan['total_price'] = $rawSale;
        $plan['raw_total_price'] = $rawSale;
        $plan['unit_sale_price'] = $unitSale;
        $plan['unit_price_divisor'] = $saleDiv;
        $plan['purchase_price_divisor'] = $purchaseDiv;
        $plan['is_unit_price'] = $saleDiv > 1 ? 1 : 0;
        $plan['price'] = $unitSale;
        $plan['total_purchase_price'] = $rawPurchase;
        $plan['unit_purchase_price'] = $unitPurchase;
        return $plan;
    }
}
