<?php

/**
 * Price Calculator Helper Functions
 * Handles pricing calculations and validations for the marketplace
 */

/**
 * Calculate suggested sale price based on original price and usage
 * Must be at least 5% less than original price
 * Additional 2% depreciation per use (max 50%)
 */
if (!function_exists('calculateSalePrice')) {
    function calculateSalePrice(float $originalPrice, int $usedTimes): float
    {
        // Base discount: 5%
        $baseDiscountPercent = 5;
        
        // Additional depreciation: 2% per use, max 45% additional (total max 50%)
        $usageDepreciationPercent = min($usedTimes * 2, 45);
        
        // Total discount
        $totalDiscountPercent = $baseDiscountPercent + $usageDepreciationPercent;
        
        // Calculate price
        $suggestedPrice = $originalPrice * (1 - ($totalDiscountPercent / 100));
        
        // Ensure it's at least 5% less than original
        $maxPrice = $originalPrice * 0.95;
        
        return round(min($suggestedPrice, $maxPrice), 2);
    }
}

/**
 * Calculate suggested rental prices (deposit and rental cost)
 * Deposit: At least 10% less than original price
 * Rental: Max 40% of deposit amount
 */
if (!function_exists('calculateRentalPrices')) {
    function calculateRentalPrices(float $originalPrice, int $usedTimes): array
    {
        // Deposit calculation: Start at 90% of original, reduce by usage
        $depositPercent = 90 - min($usedTimes, 10); // Max 10% additional reduction
        $deposit = $originalPrice * ($depositPercent / 100);
        
        // Ensure deposit is at least 10% less than original
        $maxDeposit = $originalPrice * 0.90;
        $deposit = min($deposit, $maxDeposit);
        
        // Rental cost: 30-40% of deposit based on usage
        $rentalPercent = 30 + min($usedTimes * 0.5, 10); // 30% base + up to 10% more
        $rentalCost = $deposit * ($rentalPercent / 100);
        
        // Cap at 40% of deposit
        $maxRental = $deposit * 0.40;
        $rentalCost = min($rentalCost, $maxRental);
        
        return [
            'deposit' => round($deposit, 2),
            'rental_cost' => round($rentalCost, 2)
        ];
    }
}

/**
 * Validate that sale price is at least 5% less than original
 */
if (!function_exists('validateSalePrice')) {
    function validateSalePrice(float $originalPrice, float $salePrice): bool
    {
        $maxAllowed = $originalPrice * 0.95;
        return $salePrice <= $maxAllowed;
    }
}

/**
 * Validate that deposit is at least 10% less than original price
 */
if (!function_exists('validateDeposit')) {
    function validateDeposit(float $originalPrice, float $deposit): bool
    {
        $maxAllowed = $originalPrice * 0.90;
        return $deposit <= $maxAllowed;
    }
}

/**
 * Validate that rental cost doesn't exceed 40% of deposit
 */
if (!function_exists('validateRentalCost')) {
    function validateRentalCost(float $deposit, float $rentalCost): bool
    {
        $maxAllowed = $deposit * 0.40;
        return $rentalCost <= $maxAllowed;
    }
}

/**
 * Get subscription tier limits
 */
if (!function_exists('getSubscriptionLimits')) {
    function getSubscriptionLimits(string $tier): array
    {
        // Default static limits (fallback)
        $defaults = [
            'free' => [
                'max_products' => 3,
                'monthly_price' => 0,
                'yearly_price' => 0,
                'features' => ['3 Product uploads', 'Basic support']
            ],
            'basic' => [
                'max_products' => 10,
                'monthly_price' => 99,
                'yearly_price' => 999,
                'features' => ['10 Product uploads', 'Priority support', 'Analytics']
            ],
            'pro' => [
                'max_products' => 50,
                'monthly_price' => 299,
                'yearly_price' => 2999,
                'features' => ['50 Product uploads', '24/7 Support', 'Advanced analytics', 'Featured listings']
            ],
            'enterprise' => [
                'max_products' => 999,
                'monthly_price' => 999,
                'yearly_price' => 9999,
                'features' => ['Unlimited uploads', 'Dedicated manager', 'API access', 'Custom branding']
            ]
        ];

        // Try to read from DB table `subscription_tier_settings` when available
        try {
            $db = \Config\Database::connect();
            if ($db->tableExists('subscription_tier_settings')) {
                $row = $db->table('subscription_tier_settings')
                          ->where('tier', $tier)
                          ->get()
                          ->getRowArray();

                if ($row) {
                    $features = [];
                    if (!empty($row['features'])) {
                        // Features may be stored as comma-separated string
                        if (is_string($row['features'])) {
                            $parts = array_map('trim', explode(',', $row['features']));
                            $features = array_filter($parts, function($v) { return $v !== ''; });
                        }
                    }

                    return [
                        'max_products' => (int) ($row['max_products'] ?? ($defaults[$tier]['max_products'] ?? 0)),
                        'monthly_price' => (float) ($row['monthly_price'] ?? ($defaults[$tier]['monthly_price'] ?? 0)),
                        'yearly_price' => (float) ($row['yearly_price'] ?? ($defaults[$tier]['yearly_price'] ?? 0)),
                        'features' => $features ?: ($defaults[$tier]['features'] ?? []),
                    ];
                }
            }
        } catch (\Exception $e) {
            // If DB is not available or table missing, fall back to defaults
            log_message('error', 'getSubscriptionLimits: failed to read DB - ' . $e->getMessage());
        }

        return $defaults[$tier] ?? $defaults['free'];
    }
}
