<?php
/*******************************************************************************************************************
| Rainforest Pay Donation Form for EasyStream
| User-friendly donation interface with Rainforest Pay integration
|*******************************************************************************************************************/

define('_ISVALID', true);
include_once '../../../f_core/config.core.php';

// Load Rainforest Pay handler
require_once __DIR__ . '/rainforest_pay.php';

$error_message = '';
$success_message = '';
$streamer_id = isset($_GET['streamer']) ? intval($_GET['streamer']) : 0;

if (!$streamer_id) {
    $error_message = 'Invalid streamer ID';
}

// Get streamer information
$streamer = null;
if ($streamer_id) {
    $sql = "SELECT usr_id, usr_user, usr_dname, ch_title, usr_photo 
            FROM db_accountuser WHERE usr_id = ? AND active = 1";
    $result = $class_database->execute($sql, [$streamer_id]);
    $streamer = $result->fields ?? null;
}

if (!$streamer) {
    $error_message = 'Streamer not found';
}

// Initialize Rainforest Pay handler
$rainforest = new RainforestPayHandler($class_database);
$payment_methods = $rainforest->getPaymentMethods();

// Handle form submission
if ($_POST && !$error_message) {
    $amount = floatval($_POST['amount'] ?? 0);
    $donor_name = $class_filter->clr_str($_POST['donor_name'] ?? '');
    $message = $class_filter->clr_str($_POST['message'] ?? '');
    $payment_method = $class_filter->clr_str($_POST['payment_method'] ?? 'card');
    
    if ($amount <= 0) {
        $error_message = 'Please enter a valid donation amount';
    } else {
        $result = $rainforest->createDonation($streamer_id, $amount, $donor_name, $message, $payment_method);
        
        if ($result['success']) {
            // Redirect to payment URL if provided
            if (isset($result['payment_url'])) {
                header('Location: ' . $result['payment_url']);
                exit;
            } else {
                $success_message = $result['message'];
            }
        } else {
            $error_message = $result['message'];
        }
    }
}

$config = require __DIR__ . '/config.rainforest.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Donate to <?php echo htmlspecialchars($streamer['ch_title'] ?: $streamer['usr_dname'] ?: $streamer['usr_user']); ?> - EasyStream</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .donation-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 500px;
            width: 90%;
            overflow: hidden;
        }
        
        .donation-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .streamer-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            border: 4px solid white;
            margin: 0 auto 1rem;
            display: block;
            object-fit: cover;
        }
        
        .streamer-name {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0 0 0.5rem 0;
        }
        
        .donation-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        .donation-form {
            padding: 2rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #495057;
        }
        
        .form-input {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.2s ease;
            box-sizing: border-box;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40,167,69,0.1);
        }
        
        .amount-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .amount-btn {
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }
        
        .amount-btn:hover {
            border-color: #28a745;
            background: #f8fff9;
        }
        
        .amount-btn.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }
        
        .payment-methods {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .payment-method {
            padding: 1rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            transition: all 0.2s ease;
            text-align: center;
        }
        
        .payment-method:hover {
            border-color: #28a745;
            background: #f8fff9;
        }
        
        .payment-method.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }
        
        .payment-method-icon {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }
        
        .payment-method-name {
            font-weight: 500;
            font-size: 0.875rem;
        }
        
        .donate-btn {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .donate-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(40,167,69,0.3);
        }
        
        .donate-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid #f5c6cb;
        }
        
        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid #c3e6cb;
        }
        
        .donation-info {
            background: #e3f2fd;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-size: 0.875rem;
            color: #1565c0;
        }
        
        .back-link {
            text-align: center;
            margin-top: 1rem;
        }
        
        .back-link a {
            color: #6c757d;
            text-decoration: none;
            font-size: 0.875rem;
        }
        
        .back-link a:hover {
            color: #28a745;
        }
        
        @media (max-width: 480px) {
            .donation-container {
                width: 95%;
                margin: 1rem;
            }
            
            .donation-form {
                padding: 1.5rem;
            }
            
            .amount-buttons {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .payment-methods {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="donation-container">
        <div class="donation-header">
            <img src="<?php echo $streamer['usr_photo'] ?: '/f_templates/tpl_frontend/img/default-avatar.png'; ?>" 
                 alt="<?php echo htmlspecialchars($streamer['usr_user']); ?>" 
                 class="streamer-avatar">
            <h1 class="streamer-name">
                <?php echo htmlspecialchars($streamer['ch_title'] ?: $streamer['usr_dname'] ?: $streamer['usr_user']); ?>
            </h1>
            <p class="donation-subtitle">Support this creator with a donation</p>
        </div>
        
        <div class="donation-form">
            <?php if ($error_message): ?>
                <div class="error-message">
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success_message): ?>
                <div class="success-message">
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
            <?php endif; ?>
            
            <?php if (!$error_message || $streamer): ?>
                <div class="donation-info">
                    💡 Your donation helps support content creation. 
                    Platform fee: <?php echo $config['rainforest']['platform_fee_percentage']; ?>% + 
                    $<?php echo $config['rainforest']['platform_fee_fixed']; ?>
                </div>
                
                <form method="POST" id="donation-form">
                    <!-- Donation Type Selection -->
                    <div class="form-group">
                        <label class="form-label">Donation Type</label>
                        <div class="donation-type-selector">
                            <button type="button" class="donation-type-btn active" data-type="usd">
                                💵 USD Donation
                            </button>
                            <button type="button" class="donation-type-btn" data-type="tokens">
                                🪙 Token Donation
                            </button>
                        </div>
                        <input type="hidden" name="donation_type" id="donation_type" value="usd">
                    </div>
                    
                    <!-- USD Donation Section -->
                    <div class="form-group" id="usd-section">
                        <label class="form-label">Donation Amount (USD)</label>
                        <div class="amount-buttons">
                            <button type="button" class="amount-btn" data-amount="5">$5</button>
                            <button type="button" class="amount-btn" data-amount="10">$10</button>
                            <button type="button" class="amount-btn" data-amount="25">$25</button>
                            <button type="button" class="amount-btn" data-amount="50">$50</button>
                            <button type="button" class="amount-btn" data-amount="100">$100</button>
                            <button type="button" class="amount-btn" data-amount="custom">Custom</button>
                        </div>
                        <input type="number" 
                               name="amount" 
                               id="amount" 
                               class="form-input" 
                               placeholder="Enter amount" 
                               min="<?php echo $config['rainforest']['min_donation']; ?>" 
                               max="<?php echo $config['rainforest']['max_donation']; ?>" 
                               step="0.01" 
                               required>
                    </div>
                    
                    <!-- Token Donation Section -->
                    <div class="form-group" id="token-section" style="display: none;">
                        <label class="form-label">Token Amount</label>
                        <div class="token-info">
                            <img src="/f_templates/tpl_frontend/img/default-token.svg" alt="Token" style="width: 24px; height: 24px; margin-right: 8px;">
                            <span>Send EasyCoins directly from your balance</span>
                        </div>
                        <div class="token-buttons">
                            <button type="button" class="token-btn" data-tokens="10">10 EC</button>
                            <button type="button" class="token-btn" data-tokens="25">25 EC</button>
                            <button type="button" class="token-btn" data-tokens="50">50 EC</button>
                            <button type="button" class="token-btn" data-tokens="100">100 EC</button>
                            <button type="button" class="token-btn" data-tokens="250">250 EC</button>
                            <button type="button" class="token-btn" data-tokens="custom">Custom</button>
                        </div>
                        <input type="number" 
                               name="token_amount" 
                               id="token_amount" 
                               class="form-input" 
                               placeholder="Enter token amount" 
                               min="1" 
                               step="1">
                        <div class="user-balance" id="user-balance" style="margin-top: 10px; font-size: 0.9em; color: #666;">
                            Your balance: <span id="balance-amount">Loading...</span>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Your Name (Optional)</label>
                        <input type="text" 
                               name="donor_name" 
                               class="form-input" 
                               placeholder="Enter your name or stay anonymous">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Message (Optional)</label>
                        <textarea name="message" 
                                  class="form-input" 
                                  rows="3" 
                                  placeholder="Leave a message for the creator"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Method</label>
                        <div class="payment-methods">
                            <?php foreach ($payment_methods as $method): ?>
                                <div class="payment-method" data-method="<?php echo $method['id']; ?>">
                                    <div class="payment-method-icon">
                                        <?php
                                        $icons = [
                                            'card' => '💳',
                                            'bank_transfer' => '🏦',
                                            'mobile_money' => '📱',
                                            'wallet' => '👛'
                                        ];
                                        echo $icons[$method['id']] ?? '💳';
                                        ?>
                                    </div>
                                    <div class="payment-method-name"><?php echo $method['name']; ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" name="payment_method" id="payment_method" value="card" required>
                    </div>
                    
                    <button type="submit" class="donate-btn" id="donate-btn">
                        💖 Donate Now
                    </button>
                </form>
                
                <div class="back-link">
                    <a href="javascript:history.back()">← Back to channel</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        // Amount button handling
        document.querySelectorAll('.amount-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.amount-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const amount = this.dataset.amount;
                const amountInput = document.getElementById('amount');
                
                if (amount === 'custom') {
                    amountInput.focus();
                } else {
                    amountInput.value = amount;
                }
                
                updateDonateButton();
            });
        });
        
        // Payment method handling
        document.querySelectorAll('.payment-method').forEach(method => {
            method.addEventListener('click', function() {
                document.querySelectorAll('.payment-method').forEach(m => m.classList.remove('active'));
                this.classList.add('active');
                document.getElementById('payment_method').value = this.dataset.method;
            });
        });
        
        // Set default payment method
        document.querySelector('.payment-method').classList.add('active');
        
        // Amount input handling
        document.getElementById('amount').addEventListener('input', function() {
            document.querySelectorAll('.amount-btn').forEach(b => b.classList.remove('active'));
            updateDonateButton();
        });
        
        function updateDonateButton() {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const btn = document.getElementById('donate-btn');
            
            if (amount > 0) {
                btn.textContent = `💖 Donate $${amount.toFixed(2)}`;
                btn.disabled = false;
            } else {
                btn.textContent = '💖 Donate Now';
                btn.disabled = true;
            }
        }
        
        // Form submission handling
        document.getElementById('donation-form').addEventListener('submit', function(e) {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const minAmount = <?php echo $config['rainforest']['min_donation']; ?>;
            const maxAmount = <?php echo $config['rainforest']['max_donation']; ?>;
            
            if (amount < minAmount || amount > maxAmount) {
                e.preventDefault();
                alert(`Donation amount must be between $${minAmount} and $${maxAmount}`);
                return;
            }
            
            // Show loading state
            const btn = document.getElementById('donate-btn');
            btn.disabled = true;
            btn.textContent = '⏳ Processing...';
        });
        
        // Initialize
        updateDonateButton();
    </script>
</body>
</html>        
  
      /* Token System Styles */
        .donation-type-selector {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .donation-type-btn {
            flex: 1;
            padding: 0.75rem;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }
        
        .donation-type-btn:hover {
            border-color: #28a745;
            background: #f8fff9;
        }
        
        .donation-type-btn.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }
        
        .token-info {
            display: flex;
            align-items: center;
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-size: 0.9rem;
            color: #495057;
        }
        
        .token-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .token-btn {
            padding: 0.75rem;
            border: 2px solid #FFD700;
            border-radius: 8px;
            background: linear-gradient(135deg, #FFD700, #FFA500);
            color: white;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }
        
        .token-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(255,215,0,0.3);
        }
        
        .token-btn.active {
            border-color: #B8860B;
            box-shadow: 0 0 0 3px rgba(255,215,0,0.2);
        }
        
        .user-balance {
            background: #e3f2fd;
            padding: 0.75rem;
            border-radius: 8px;
            text-align: center;
            font-weight: 500;
        }
        
        .insufficient-balance {
            background: #ffebee;
            color: #c62828;
        }
        
        @media (max-width: 480px) {
            .donation-type-selector {
                flex-direction: column;
            }
            
            .token-buttons {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        // Enhanced donation form JavaScript
        
        // Donation type switching
        document.querySelectorAll('.donation-type-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.donation-type-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const type = this.dataset.type;
                document.getElementById('donation_type').value = type;
                
                if (type === 'usd') {
                    document.getElementById('usd-section').style.display = 'block';
                    document.getElementById('token-section').style.display = 'none';
                    document.getElementById('amount').required = true;
                    document.getElementById('token_amount').required = false;
                } else {
                    document.getElementById('usd-section').style.display = 'none';
                    document.getElementById('token-section').style.display = 'block';
                    document.getElementById('amount').required = false;
                    document.getElementById('token_amount').required = true;
                    loadUserBalance();
                }
            });
        });
        
        // Token button handling
        document.querySelectorAll('.token-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.token-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const tokens = this.dataset.tokens;
                const tokenInput = document.getElementById('token_amount');
                
                if (tokens === 'custom') {
                    tokenInput.focus();
                } else {
                    tokenInput.value = tokens;
                }
                
                checkTokenBalance();
            });
        });
        
        // Token amount input handling
        document.getElementById('token_amount').addEventListener('input', function() {
            document.querySelectorAll('.token-btn').forEach(b => b.classList.remove('active'));
            checkTokenBalance();
        });
        
        function loadUserBalance() {
            // Load user's token balance via AJAX
            fetch('/api/user/token-balance')
                .then(response => response.json())
                .then(data => {
                    const balanceElement = document.getElementById('balance-amount');
                    if (data.success) {
                        balanceElement.innerHTML = `<img src="/f_templates/tpl_frontend/img/default-token.svg" style="width: 16px; height: 16px; margin-right: 4px;">${data.balance} EasyCoins`;
                    } else {
                        balanceElement.textContent = 'Unable to load balance';
                    }
                })
                .catch(error => {
                    document.getElementById('balance-amount').textContent = 'Error loading balance';
                });
        }
        
        function checkTokenBalance() {
            const tokenAmount = parseInt(document.getElementById('token_amount').value) || 0;
            const balanceElement = document.getElementById('user-balance');
            const donateBtn = document.getElementById('donate-btn');
            
            // This would check against actual user balance
            // For now, we'll assume they have sufficient balance
            if (tokenAmount > 0) {
                balanceElement.classList.remove('insufficient-balance');
                donateBtn.disabled = false;
                donateBtn.textContent = `🪙 Donate ${tokenAmount} EasyCoins`;
            } else {
                donateBtn.textContent = '🪙 Donate Tokens';
                donateBtn.disabled = true;
            }
        }
        
        // Update the main donate button text based on type
        function updateDonateButton() {
            const donationType = document.getElementById('donation_type').value;
            const btn = document.getElementById('donate-btn');
            
            if (donationType === 'tokens') {
                const tokenAmount = parseInt(document.getElementById('token_amount').value) || 0;
                if (tokenAmount > 0) {
                    btn.textContent = `🪙 Donate ${tokenAmount} EasyCoins`;
                } else {
                    btn.textContent = '🪙 Donate Tokens';
                }
            } else {
                const amount = parseFloat(document.getElementById('amount').value) || 0;
                if (amount > 0) {
                    btn.textContent = `💖 Donate $${amount.toFixed(2)}`;
                } else {
                    btn.textContent = '💖 Donate Now';
                }
            }
        }