<?php

declare(strict_types=1);

require_once __DIR__ . '/PlatformSettings.php';

/**
 * PlanManager
 * 
 * Manages subscription plans with multi-currency support
 */
class PlanManager
{
    /**
     * Get all active plans
     */
    public static function getActivePlans(string $currency = 'USD'): array
    {
        $pdo = getPDO();
        $stmt = $pdo->query('SELECT * FROM subscription_plans WHERE is_active = 1 ORDER BY sort_order, price');
        $plans = $stmt->fetchAll();

        return array_map(function($plan) use ($currency) {
            return self::formatPlan($plan, $currency);
        }, $plans);
    }

    /**
     * Get all plans (including inactive)
     */
    public static function getAllPlans(): array
    {
        $pdo = getPDO();
        $stmt = $pdo->query('SELECT * FROM subscription_plans ORDER BY price_monthly ASC');
        return $stmt->fetchAll();
    }

    /**
     * Get a single plan
     */
    public static function getPlan(int $planId, string $currency = 'USD'): ?array
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT * FROM subscription_plans WHERE id = ?');
        $stmt->execute([$planId]);
        $plan = $stmt->fetch();

        return $plan ? self::formatPlan($plan, $currency) : null;
    }

    /**
     * Format plan with currency-specific pricing
     */
    public static function formatPlan(array $plan, string $currency = 'USD'): array
    {
        $limits = json_decode($plan['limits'] ?? '{}', true) ?: [];
        
        // Get price based on currency (using existing column names)
        $monthlyPrice = $currency === 'INR' 
            ? ($plan['price_monthly_inr'] ?? ($plan['price_monthly'] ?? 0) * 83)
            : ($plan['price_monthly'] ?? 0);
            
        $yearlyPrice = $currency === 'INR'
            ? ($plan['price_yearly_inr'] ?? ($plan['price_yearly'] ?? 0) * 83)
            : ($plan['price_yearly'] ?? 0);

        return [
            'id' => (int)$plan['id'],
            'name' => $plan['name'],
            'description' => $plan['description'] ?? '',
            'monthly_price' => (float)$monthlyPrice,
            'yearly_price' => (float)$yearlyPrice,
            'yearly_monthly_price' => round($yearlyPrice / 12, 2),
            'currency' => $currency,
            'currency_symbol' => $currency === 'INR' ? '₹' : '$',
            'limits' => $limits,
            'features' => json_decode($plan['features'] ?? '[]', true) ?: [],
            'is_popular' => (bool)($plan['is_popular'] ?? false),
            'trial_days' => (int)($plan['trial_days'] ?? 0),
            'stripe_price_id_monthly' => $plan['stripe_price_id_monthly'] ?? null,
            'stripe_price_id_yearly' => $plan['stripe_price_id_yearly'] ?? null,
            'razorpay_plan_id_monthly' => $plan['razorpay_plan_id_monthly'] ?? null,
            'razorpay_plan_id_yearly' => $plan['razorpay_plan_id_yearly'] ?? null,
        ];
    }

    /**
     * Create a new plan
     */
    public static function createPlan(array $data): ?int
    {
        $pdo = getPDO();
        
        $stmt = $pdo->prepare('
            INSERT INTO subscription_plans (
                name, slug, description, price_monthly, price_yearly, 
                price_monthly_inr, price_yearly_inr, limits, features,
                trial_days, is_popular, is_active, sort_order
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ');

        $limits = is_array($data['limits'] ?? null) ? json_encode($data['limits']) : ($data['limits'] ?? '{}');
        $features = is_array($data['features'] ?? null) ? json_encode($data['features']) : ($data['features'] ?? '[]');
        $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $data['name']));

        $result = $stmt->execute([
            $data['name'],
            $slug,
            $data['description'] ?? '',
            $data['price_monthly'] ?? $data['price_usd'] ?? 0,
            $data['price_yearly'] ?? $data['yearly_price_usd'] ?? 0,
            $data['price_monthly_inr'] ?? $data['price_inr'] ?? 0,
            $data['price_yearly_inr'] ?? $data['yearly_price_inr'] ?? 0,
            $limits,
            $features,
            $data['trial_days'] ?? 0,
            $data['is_popular'] ?? 0,
            $data['is_active'] ?? 1,
            $data['sort_order'] ?? 0,
        ]);

        return $result ? (int)$pdo->lastInsertId() : null;
    }

    /**
     * Update a plan
     */
    public static function updatePlan(int $planId, array $data): bool
    {
        $pdo = getPDO();
        
        $fields = [];
        $values = [];

        $allowedFields = [
            'name', 'description', 'price_monthly', 'price_yearly',
            'price_monthly_inr', 'price_yearly_inr', 'limits', 'features',
            'trial_days', 'is_popular', 'is_active', 'sort_order'
        ];

        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $data)) {
                $fields[] = "$field = ?";
                $value = $data[$field];
                
                if (in_array($field, ['limits', 'features']) && is_array($value)) {
                    $value = json_encode($value);
                }
                
                $values[] = $value;
            }
        }

        if (empty($fields)) {
            return false;
        }

        $values[] = $planId;
        $sql = 'UPDATE subscription_plans SET ' . implode(', ', $fields) . ' WHERE id = ?';
        
        $stmt = $pdo->prepare($sql);
        return $stmt->execute($values);
    }

    /**
     * Delete a plan (soft delete by setting inactive)
     */
    public static function deletePlan(int $planId): bool
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('UPDATE subscription_plans SET is_active = 0 WHERE id = ?');
        return $stmt->execute([$planId]);
    }

    /**
     * Get plan limits
     */
    public static function getPlanLimits(int $planId): array
    {
        $plan = self::getPlan($planId);
        return $plan['limits'] ?? [];
    }

    /**
     * Get default limits structure
     */
    public static function getDefaultLimits(): array
    {
        return [
            'users' => 3,
            'clients' => 10,
            'templates' => 5,
            'storage_mb' => 100,
            'proposals_per_month' => 10,
            'contracts_per_month' => 10,
            'invoices_per_month' => 10,
        ];
    }

    /**
     * Get limit labels for display
     */
    public static function getLimitLabels(): array
    {
        return [
            'users' => 'Team Members',
            'clients' => 'Clients',
            'templates' => 'Templates',
            'storage_mb' => 'Storage (MB)',
            'proposals_per_month' => 'Proposals/Month',
            'contracts_per_month' => 'Contracts/Month',
            'invoices_per_month' => 'Invoices/Month',
        ];
    }
}
