<?php
/**
 * Paystack Charge Configuration Page
 * Allows admin to configure charges for Paystack top-ups
 */

require_once __DIR__ . '/../../app/classes/PaystackChargeManager.php';

// Set page variables for header
$page_title = 'Paystack Charge Configuration';
$page_description = 'Configure charges applied to Paystack top-ups';

$success_message = '';
$error_message = '';

// Initialize charge manager
$chargeManager = new PaystackChargeManager($conn);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_charge'])) {
        $chargeAmount = floatval($_POST['charge_amount']);
        $chargeType = trim($_POST['charge_type']);
        $adminId = $_SESSION['admin_id'] ?? 1;
        
        $result = $chargeManager->updateChargeConfig($chargeAmount, $chargeType, $adminId);
        
        if ($result['success']) {
            $success_message = $result['message'];
        } else {
            $error_message = $result['message'];
        }
    } elseif (isset($_POST['disable_charge'])) {
        $result = $chargeManager->disableCharge();
        
        if ($result['success']) {
            $success_message = $result['message'];
        } else {
            $error_message = $result['message'];
        }
    }
}

// Get current configuration
$currentConfig = $chargeManager->getChargeConfig();
$configHistory = $chargeManager->getConfigurationHistory(10);
?>

<!-- Paystack Charge Configuration Content -->
<div class="space-y-6">
    <!-- Success/Error Messages -->
    <?php if ($success_message): ?>
    <div class="p-4 rounded-lg bg-green-100 text-green-800 border border-green-200 flex items-center">
        <i class="fas fa-check-circle mr-3 text-xl"></i>
        <span><?= htmlspecialchars($success_message) ?></span>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="p-4 rounded-lg bg-red-100 text-red-800 border border-red-200 flex items-center">
        <i class="fas fa-exclamation-circle mr-3 text-xl"></i>
        <span><?= htmlspecialchars($error_message) ?></span>
    </div>
    <?php endif; ?>
    
    <!-- Current Status Card -->
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-bold text-gray-100">
                <i class="fas fa-dollar-sign text-green-500 mr-3"></i>Current Charge Status
            </h2>
            <span class="px-4 py-2 rounded-full text-sm font-semibold <?= $currentConfig['is_active'] ? 'bg-green-900/50 text-green-300 border border-green-700' : 'bg-red-900/50 text-red-300 border border-red-700' ?>">
                <?= $currentConfig['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
            <div class="bg-gray-700/50 rounded-lg p-4">
                <div class="text-gray-400 text-sm mb-1">Charge Amount</div>
                <div class="text-2xl font-bold text-gray-100">
                    <?php if ($currentConfig['charge_type'] === 'percentage'): ?>
                        <?= number_format($currentConfig['charge_amount'], 2) ?>%
                    <?php else: ?>
                        GHS <?= number_format($currentConfig['charge_amount'], 4) ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="bg-gray-700/50 rounded-lg p-4">
                <div class="text-gray-400 text-sm mb-1">Charge Type</div>
                <div class="text-2xl font-bold text-gray-100 capitalize">
                    <?= htmlspecialchars($currentConfig['charge_type']) ?>
                </div>
            </div>
            
            <div class="bg-gray-700/50 rounded-lg p-4">
                <div class="text-gray-400 text-sm mb-1">Example (GHS 10 top-up)</div>
                <?php 
                $example = $chargeManager->calculateChargedAmount(10.00);
                ?>
                <div class="text-2xl font-bold text-blue-400">
                    GHS <?= number_format($example['total_amount'], 2) ?>
                </div>
                <div class="text-xs text-gray-400 mt-1">
                    (Base: GHS 10.00 + Charge: GHS <?= number_format($example['charge_amount'], 2) ?>)
                </div>
            </div>
        </div>
    </div>
    
    <!-- Configuration Form -->
    <div class="bg-gray-800 rounded-xl shadow-lg border border-gray-700">
        <div class="bg-gradient-to-r from-blue-900/50 to-purple-900/50 p-6 rounded-t-xl border-b border-gray-700">
            <h2 class="text-2xl font-bold text-gray-100">
                <i class="fas fa-cog text-blue-400 mr-3"></i>Configure Paystack Charges
            </h2>
            <p class="text-gray-300 mt-2">
                Set charges applied when users top up via Paystack. The user will be credited the amount they enter, but Paystack will charge the total amount including the charge.
            </p>
        </div>
        
        <div class="p-6">
            <form method="POST" class="space-y-6">
                <!-- Charge Type Selection -->
                <div>
                    <label for="charge_type" class="block text-sm font-medium dark-text-primary mb-2">
                        <i class="fas fa-list mr-2"></i>Charge Type
                    </label>
                    <select id="charge_type" 
                            name="charge_type" 
                            class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 bg-gray-700 text-gray-100 border-gray-600"
                            onchange="updateChargeTypeHelp()" 
                            required>
                        <option value="fixed" <?= $currentConfig['charge_type'] === 'fixed' ? 'selected' : '' ?>>Fixed Amount (GHS)</option>
                        <option value="percentage" <?= $currentConfig['charge_type'] === 'percentage' ? 'selected' : '' ?>>Percentage (%)</option>
                    </select>
                    <p class="mt-2 text-sm dark-text-muted" id="charge_type_help">
                        <i class="fas fa-info-circle mr-1"></i>
                        <span id="charge_type_text">A fixed amount in GHS will be added to all top-ups</span>
                    </p>
                </div>
                
                <!-- Charge Amount -->
                <div>
                    <label for="charge_amount" class="block text-sm font-medium dark-text-primary mb-2">
                        <i class="fas fa-money-bill-wave mr-2"></i>Charge Amount
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <span class="text-gray-500 sm:text-sm" id="currency_symbol">GHS</span>
                        </div>
                        <input type="number" 
                               id="charge_amount" 
                               name="charge_amount" 
                               value="<?= number_format($currentConfig['charge_amount'], 4, '.', '') ?>" 
                               step="0.0001"
                               min="0"
                               max="1000"
                               class="pl-16 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 bg-gray-700 text-gray-100 border-gray-600" 
                               oninput="updateExample()"
                               required>
                    </div>
                    <p class="mt-2 text-sm dark-text-muted">
                        <i class="fas fa-info-circle mr-1"></i>
                        Example: Enter 0.008 for 0.8 pesewas (GHS 0.008) or enter 2.5 for 2.5% charge
                    </p>
                </div>
                
                <!-- Live Example Calculator -->
                <div class="bg-blue-900/20 border border-blue-700/50 rounded-lg p-4">
                    <h4 class="text-sm font-semibold text-blue-300 mb-3">
                        <i class="fas fa-calculator mr-2"></i>Live Calculation Example
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="text-xs text-gray-400 mb-1 block">Test Amount (GHS)</label>
                            <input type="number" 
                                   id="test_amount" 
                                   value="10.00" 
                                   step="0.01"
                                   min="1"
                                   class="w-full rounded border-gray-600 bg-gray-700 text-gray-100" 
                                   oninput="updateExample()">
                        </div>
                        <div class="bg-gray-700/50 rounded p-3">
                            <div class="text-xs text-gray-400 mb-1">Amount Charged via Paystack</div>
                            <div class="text-xl font-bold text-green-400" id="example_result">GHS 10.00</div>
                            <div class="text-xs text-gray-400 mt-1" id="example_breakdown">
                                Base: GHS 10.00 + Charge: GHS 0.00
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Important Notice -->
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <h4 class="font-semibold text-yellow-800 mb-2">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Important Information
                    </h4>
                    <ul class="text-sm text-yellow-700 space-y-2">
                        <li><i class="fas fa-check mr-2"></i>Users will be <strong>credited the amount they enter</strong> (e.g., GHS 10)</li>
                        <li><i class="fas fa-check mr-2"></i>Paystack will charge the <strong>total amount including the charge</strong> (e.g., GHS 10.008)</li>
                        <li><i class="fas fa-check mr-2"></i>The charge helps cover Paystack transaction fees or your processing costs</li>
                        <li><i class="fas fa-check mr-2"></i>Users will see the charge breakdown before confirming payment</li>
                    </ul>
                </div>
                
                <!-- Action Buttons -->
                <div class="flex gap-4">
                    <button type="submit" 
                            name="update_charge" 
                            class="flex-1 bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors font-semibold">
                        <i class="fas fa-save mr-2"></i>Save Configuration
                    </button>
                    
                    <?php if ($currentConfig['is_active']): ?>
                    <button type="submit" 
                            name="disable_charge" 
                            onclick="return confirm('Are you sure you want to disable Paystack charges? This will remove charges from all future top-ups.')"
                            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors font-semibold">
                        <i class="fas fa-ban mr-2"></i>Disable Charge
                    </button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Configuration History -->
    <?php if (!empty($configHistory)): ?>
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <h3 class="text-xl font-bold text-gray-100 mb-4">
            <i class="fas fa-history text-purple-500 mr-3"></i>Configuration History
        </h3>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-700">
                <thead class="bg-gray-700/50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Date</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Charge Amount</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Type</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Created By</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-700">
                    <?php foreach ($configHistory as $config): ?>
                    <tr class="hover:bg-gray-700/30">
                        <td class="px-6 py-4 text-sm text-gray-200">
                            <?= date('M d, Y H:i', strtotime($config['created_at'])) ?>
                        </td>
                        <td class="px-6 py-4 text-sm font-semibold text-gray-100">
                            <?php if ($config['charge_type'] === 'percentage'): ?>
                                <?= number_format($config['charge_amount'], 2) ?>%
                            <?php else: ?>
                                GHS <?= number_format($config['charge_amount'], 4) ?>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-200 capitalize">
                            <?= htmlspecialchars($config['charge_type']) ?>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full <?= $config['is_active'] ? 'bg-green-900/50 text-green-300 border border-green-700' : 'bg-gray-700 text-gray-400' ?>">
                                <?= $config['is_active'] ? 'Active' : 'Inactive' ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-200">
                            Admin #<?= htmlspecialchars($config['created_by']) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Update charge type help text
function updateChargeTypeHelp() {
    const chargeType = document.getElementById('charge_type').value;
    const helpText = document.getElementById('charge_type_text');
    const currencySymbol = document.getElementById('currency_symbol');
    const chargeAmountInput = document.getElementById('charge_amount');
    
    if (chargeType === 'fixed') {
        helpText.textContent = 'A fixed amount in GHS will be added to all top-ups';
        currencySymbol.textContent = 'GHS';
        chargeAmountInput.max = '1000';
        chargeAmountInput.step = '0.0001';
    } else {
        helpText.textContent = 'A percentage of the top-up amount will be added as charge';
        currencySymbol.textContent = '%';
        chargeAmountInput.max = '100';
        chargeAmountInput.step = '0.01';
    }
    
    updateExample();
}

// Update live example calculation
function updateExample() {
    const chargeType = document.getElementById('charge_type').value;
    const chargeAmount = parseFloat(document.getElementById('charge_amount').value) || 0;
    const testAmount = parseFloat(document.getElementById('test_amount').value) || 0;
    
    let calculatedCharge = 0;
    
    if (chargeType === 'fixed') {
        calculatedCharge = chargeAmount;
    } else {
        calculatedCharge = (testAmount * chargeAmount) / 100;
    }
    
    const totalAmount = testAmount + calculatedCharge;
    
    document.getElementById('example_result').textContent = 'GHS ' + totalAmount.toFixed(2);
    document.getElementById('example_breakdown').textContent = 
        'Base: GHS ' + testAmount.toFixed(2) + ' + Charge: GHS ' + calculatedCharge.toFixed(2);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    updateChargeTypeHelp();
    updateExample();
});
</script>

