<?php

/**
 * Test Mode Manager - Handles test/demo mode for billing without payment gateways
 */
class TestModeManager {
    
    /**
     * Check if test mode is enabled
     */
    public static function isTestMode(): bool
    {
        return ($_ENV['APP_ENV'] ?? 'development') === 'development' || 
               isset($_GET['test_mode']) || 
               isset($_SESSION['test_mode']);
    }
    
    /**
     * Enable test mode
     */
    public static function enableTestMode(): void
    {
        $_SESSION['test_mode'] = true;
    }
    
    /**
     * Disable test mode
     */
    public static function disableTestMode(): void
    {
        unset($_SESSION['test_mode']);
    }
    
    /**
     * Create test subscription without payment
     */
    public static function createTestSubscription(int $companyId, int $planId, string $billingCycle = 'monthly'): array
    {
        if (!self::isTestMode()) {
            throw new Exception('Test mode is not enabled');
        }
        
        $pdo = getPDO();
        
        // Get plan details
        $planStmt = $pdo->prepare('SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1');
        $planStmt->execute([$planId]);
        $plan = $planStmt->fetch();
        
        if (!$plan) {
            throw new Exception('Invalid plan');
        }
        
        // Create test subscription
        $subscriptionData = [
            'company_id' => $companyId,
            'plan_id' => $planId,
            'status' => 'active',
            'billing_cycle' => $billingCycle,
            'current_period_start' => date('Y-m-d H:i:s'),
            'current_period_end' => date('Y-m-d H:i:s', strtotime('+30 days')),
            'trial_ends_at' => null,
            'canceled_at' => null,
            'payment_method_id' => null,
            'stripe_subscription_id' => 'test_sub_' . uniqid(),
            'razorpay_subscription_id' => 'test_sub_' . uniqid(),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        $fields = array_keys($subscriptionData);
        $placeholders = array_fill(0, count($fields), '?');
        
        $stmt = $pdo->prepare(
            'INSERT INTO subscriptions (' . implode(', ', $fields) . ') 
             VALUES (' . implode(', ', $placeholders) . ')'
        );
        
        $stmt->execute(array_values($subscriptionData));
        $subscriptionId = $pdo->lastInsertId();
        
        // Update company with subscription info
        $updateStmt = $pdo->prepare(
            'UPDATE companies SET 
                plan_id = ?, 
                subscription_status = ?, 
                subscription_expires_at = ?,
                billing_cycle = ?,
                updated_at = NOW()
             WHERE id = ?'
        );
        
        $updateStmt->execute([
            $planId,
            'active',
            $subscriptionData['current_period_end'],
            $billingCycle,
            $companyId
        ]);
        
        return [
            'success' => true,
            'subscription_id' => $subscriptionId,
            'message' => 'Test subscription created successfully',
            'plan' => $plan,
            'test_mode' => true
        ];
    }
    
    /**
     * Generate test payment method
     */
    public static function generateTestPaymentMethod(int $companyId): array
    {
        if (!self::isTestMode()) {
            throw new Exception('Test mode is not enabled');
        }
        
        return [
            'id' => 0,
            'type' => 'card',
            'brand' => 'visa',
            'last_four' => '4242',
            'expires_month' => 12,
            'expires_year' => date('Y') + 2,
            'is_default' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ];
    }
    
    /**
     * Get test billing history
     */
    public static function getTestBillingHistory(int $companyId): array
    {
        if (!self::isTestMode()) {
            throw new Exception('Test mode is not enabled');
        }
        
        return [
            [
                'invoice_number' => 'TEST-' . date('Ym') . '-0001',
                'amount' => 29.00,
                'currency' => 'USD',
                'status' => 'paid',
                'description' => 'Starter Plan - Monthly',
                'created_at' => date('Y-m-d H:i:s', strtotime('-30 days')),
                'test_mode' => true
            ],
            [
                'invoice_number' => 'TEST-' . date('Ym') . '-0002',
                'amount' => 29.00,
                'currency' => 'USD',
                'status' => 'paid',
                'description' => 'Starter Plan - Monthly',
                'created_at' => date('Y-m-d H:i:s', strtotime('-60 days')),
                'test_mode' => true
            ]
        ];
    }
    
    /**
     * Get test usage metrics
     */
    public static function getTestUsageMetrics(int $companyId): array
    {
        if (!self::isTestMode()) {
            throw new Exception('Test mode is not enabled');
        }
        
        $pdo = getPDO();
        
        // Get company plan
        $stmt = $pdo->prepare('SELECT plan_id FROM companies WHERE id = ?');
        $stmt->execute([$companyId]);
        $company = $stmt->fetch();
        
        if (!$company || !$company['plan_id']) {
            return [];
        }
        
        // Get plan limits
        $planStmt = $pdo->prepare('SELECT limits FROM subscription_plans WHERE id = ?');
        $planStmt->execute([$company['plan_id']]);
        $plan = $planStmt->fetch();
        
        if (!$plan) {
            return [];
        }
        
        $limits = json_decode($plan['limits'], true) ?? [];
        
        // Generate test usage data
        return [
            'proposals' => [
                'used' => rand(5, min(25, $limits['proposals_per_month'] ?? 50)),
                'limit' => $limits['proposals_per_month'] ?? 50,
                'percentage' => 0
            ],
            'clients' => [
                'used' => rand(3, min(15, $limits['clients'] ?? 25)),
                'limit' => $limits['clients'] ?? 25,
                'percentage' => 0
            ],
            'team_members' => [
                'used' => rand(1, min(3, $limits['team_members'] ?? 3)),
                'limit' => $limits['team_members'] ?? 3,
                'percentage' => 0
            ],
            'storage' => [
                'used' => rand(100, min(500, $limits['storage_mb'] ?? 1000)),
                'limit' => $limits['storage_mb'] ?? 1000,
                'percentage' => 0
            ]
        ];
    }
}
