<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/currency.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_rates'])) {
        // Update exchange rates
        $rates = [];
        foreach (SUPPORTED_CURRENCIES as $code => $info) {
            if ($code !== 'USD') {
                $rate = floatval($_POST["rate_{$code}"] ?? 1.0);
                if ($rate > 0) {
                    $rates[$code] = $rate;
                }
            }
        }

        try {
            CurrencyHelper::updateExchangeRates($rates);
            $success = 'Exchange rates updated successfully!';
        } catch (Exception $e) {
            $error = 'Error updating exchange rates: ' . $e->getMessage();
        }

    } elseif (isset($_POST['update_default_currency'])) {
        // Update default currency
        $defaultCurrency = trim($_POST['default_currency']);

        if (CurrencyHelper::isValidCurrency($defaultCurrency)) {
            try {
                updateSiteSetting('default_currency', $defaultCurrency);
                $success = 'Default currency updated successfully!';
            } catch (Exception $e) {
                $error = 'Error updating default currency: ' . $e->getMessage();
            }
        } else {
            $error = 'Invalid currency selected.';
        }
    }
}

// Get current default currency
$currentDefaultCurrency = getSiteSetting('default_currency') ?: DEFAULT_CURRENCY;

// Get current exchange rates
$currentRates = [];
foreach (SUPPORTED_CURRENCIES as $code => $info) {
    if ($code !== 'USD') {
        $currentRates[$code] = CurrencyHelper::getExchangeRate($code);
    }
}

$page_title = 'Currency Settings';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="currency-settings-section">
    <h2>Currency Settings</h2>
    <p class="settings-description">Configure multi-currency support, exchange rates, and payment gateway currency compatibility.</p>

    <!-- Default Currency Settings -->
    <div class="settings-card">
        <h3>Default Currency</h3>
        <p class="settings-description">Set the default currency for new courses and system-wide use.</p>

        <form method="POST">
            <div class="form-group">
                <label for="default_currency">Default Currency:</label>
                <?php echo CurrencyHelper::getCurrencySelector($currentDefaultCurrency, 'default_currency', 'form-select'); ?>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_default_currency" class="btn btn-primary">Update Default Currency</button>
            </div>
        </form>
    </div>

    <!-- Exchange Rates -->
    <div class="settings-card">
        <h3>Exchange Rates</h3>
        <p class="settings-description">Manage currency exchange rates (base: USD). These rates are used for currency conversion calculations.</p>

        <form method="POST">
            <div class="exchange-rates-grid">
                <div class="rate-item header">
                    <span>Currency</span>
                    <span>Symbol</span>
                    <span>Current Rate (1 USD = ?)</span>
                    <span>New Rate</span>
                </div>

                <?php foreach (SUPPORTED_CURRENCIES as $code => $info): ?>
                    <?php if ($code === 'USD') continue; ?>
                    <div class="rate-item">
                        <span class="currency-name">
                            <strong><?php echo htmlspecialchars($code); ?></strong>
                            <?php echo htmlspecialchars($info['name']); ?>
                        </span>
                        <span class="currency-symbol"><?php echo htmlspecialchars($info['symbol']); ?></span>
                        <span class="current-rate"><?php echo number_format($currentRates[$code], 4); ?></span>
                        <input type="number" name="rate_<?php echo $code; ?>" value="<?php echo number_format($currentRates[$code], 4); ?>"
                               step="0.0001" min="0.0001" class="form-control rate-input" required>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="form-actions">
                <button type="submit" name="update_rates" class="btn btn-primary">Update Exchange Rates</button>
                <small class="text-muted">Rates are updated immediately and affect all currency conversions.</small>
            </div>
        </form>
    </div>

    <!-- Currency Support Matrix -->
    <div class="settings-card">
        <h3>Payment Gateway Currency Support</h3>
        <p class="settings-description">Overview of which currencies are supported by each payment gateway.</p>

        <div class="support-matrix">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Currency</th>
                        <th>PayPal</th>
                        <th>Paynow</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (SUPPORTED_CURRENCIES as $code => $info): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($code); ?></strong>
                                <?php echo htmlspecialchars($info['name']); ?>
                                <small class="text-muted">(<?php echo htmlspecialchars($info['symbol']); ?>)</small>
                            </td>
                            <td>
                                <?php if ($info['paypal_supported']): ?>
                                    <span class="badge bg-success">Supported</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Not Supported</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($info['paynow_supported']): ?>
                                    <span class="badge bg-success">Supported</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Not Supported</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $paypalSupport = $info['paypal_supported'];
                                $paynowSupport = $info['paynow_supported'];

                                if ($paypalSupport && $paynowSupport): ?>
                                    <span class="badge bg-success">Fully Supported</span>
                                <?php elseif ($paypalSupport || $paynowSupport): ?>
                                    <span class="badge bg-warning">Partially Supported</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Not Supported</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Currency Usage Statistics -->
    <div class="settings-card">
        <h3>Currency Usage Statistics</h3>
        <p class="settings-description">Overview of currency usage across courses and transactions.</p>

        <div class="stats-grid">
            <?php
            // Get currency usage statistics
            $currencyStats = $db->query("
                SELECT
                    currency,
                    COUNT(*) as course_count,
                    SUM(price) as total_pricing
                FROM courses
                WHERE is_free = 0 AND status = 'published'
                GROUP BY currency
                ORDER BY course_count DESC
            ")->fetchAll();

            $transactionStats = $db->query("
                SELECT
                    currency,
                    COUNT(*) as transaction_count,
                    SUM(final_amount) as total_amount
                FROM payment_transactions
                WHERE status = 'completed'
                GROUP BY currency
                ORDER BY transaction_count DESC
            ")->fetchAll();
            ?>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-graduation-cap"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo count($currencyStats); ?></h3>
                    <p>Currencies Used in Courses</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-credit-card"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo count($transactionStats); ?></h3>
                    <p>Currencies Used in Payments</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo htmlspecialchars($currentDefaultCurrency); ?></h3>
                    <p>Default Currency</p>
                </div>
            </div>
        </div>

        <?php if (!empty($currencyStats)): ?>
            <h4>Course Currency Distribution</h4>
            <div class="currency-breakdown">
                <?php foreach ($currencyStats as $stat): ?>
                    <div class="currency-stat">
                        <span class="currency-code"><?php echo htmlspecialchars($stat['currency']); ?></span>
                        <span class="currency-count"><?php echo $stat['course_count']; ?> courses</span>
                        <div class="currency-bar">
                            <div class="currency-fill" style="width: <?php echo $stat['course_count'] / max(array_column($currencyStats, 'course_count')) * 100; ?>%"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.currency-settings-section {
    max-width: 1400px;
}

.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1rem;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    font-weight: 600;
    color: #374151;
    margin-bottom: 0.5rem;
}

.form-select,
.form-control {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

.form-actions {
    margin-top: 1.5rem;
    padding-top: 1.5rem;
    border-top: 1px solid #e5e7eb;
}

.btn {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background-color: #2563eb;
    color: white;
}

.btn-primary:hover {
    background-color: #1d4ed8;
}

.exchange-rates-grid {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr;
    gap: 1rem;
    margin-bottom: 1rem;
}

.rate-item {
    display: contents;
}

.rate-item.header {
    font-weight: 600;
    color: #374151;
    border-bottom: 2px solid #e5e7eb;
    padding-bottom: 0.5rem;
}

.rate-item.header span {
    padding: 0.5rem;
    background-color: #f8f9fa;
    border-radius: 0.25rem;
}

.rate-item:not(.header) {
    align-items: center;
}

.currency-name {
    padding: 0.5rem;
    display: flex;
    flex-direction: column;
}

.currency-name strong {
    color: #1f2937;
}

.currency-symbol,
.current-rate {
    padding: 0.5rem;
    text-align: center;
    background-color: #f8f9fa;
    border-radius: 0.25rem;
}

.rate-input {
    max-width: 120px;
}

.support-matrix {
    overflow-x: auto;
}

.table {
    margin-bottom: 0;
    width: 100%;
}

.table th {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #374151;
    border-top: none;
    padding: 1rem;
    white-space: nowrap;
}

.table td {
    padding: 1rem;
    vertical-align: middle;
}

.badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    border-radius: 0.25rem;
}

.badge-success {
    background-color: #10b981;
    color: white;
}

.badge-secondary {
    background-color: #6b7280;
    color: white;
}

.badge-warning {
    background-color: #f59e0b;
    color: white;
}

.badge-danger {
    background-color: #dc2626;
    color: white;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    padding: 1.5rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stat-icon {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e5e7eb;
    color: #6b7280;
    font-size: 1.25rem;
}

.stat-info h3 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

.stat-info p {
    color: #6b7280;
    font-size: 0.875rem;
    margin: 0.25rem 0 0 0;
}

.currency-breakdown {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.currency-stat {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.currency-code {
    font-weight: 600;
    min-width: 60px;
}

.currency-count {
    min-width: 100px;
    color: #6b7280;
}

.currency-bar {
    flex: 1;
    height: 8px;
    background-color: #e5e7eb;
    border-radius: 4px;
    overflow: hidden;
}

.currency-fill {
    height: 100%;
    background-color: #2563eb;
    border-radius: 4px;
    transition: width 0.3s ease;
}

.alert {
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
}

.alert-error {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.alert-success {
    background-color: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #16a34a;
}

@media (max-width: 768px) {
    .exchange-rates-grid {
        grid-template-columns: 1fr;
        gap: 0.5rem;
    }

    .rate-item.header {
        display: none;
    }

    .rate-item:not(.header) {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
        padding: 1rem;
        border: 1px solid #e5e7eb;
        border-radius: 0.5rem;
        background-color: #f8f9fa;
    }

    .stats-grid {
        grid-template-columns: 1fr;
    }

    .currency-stat {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }
}
</style>

<?php include 'includes/admin_footer.php'; ?>