<?php
require_once '../config/database.php';
require_once '../config/auth.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_gateway'])) {
        // Update gateway settings
        $gatewayId = (int)$_POST['gateway_id'];
        $gatewayName = trim($_POST['gateway_name']);
        $gatewayType = trim($_POST['gateway_type']);
        $apiKey = trim($_POST['api_key'] ?? '');
        $apiSecret = trim($_POST['api_secret'] ?? '');
        $merchantId = trim($_POST['merchant_id'] ?? '');
        $merchantEmail = trim($_POST['merchant_email'] ?? '');
        $webhookUrl = trim($_POST['webhook_url'] ?? '');
        $returnUrl = trim($_POST['return_url'] ?? '');
        $cancelUrl = trim($_POST['cancel_url'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        $testMode = isset($_POST['test_mode']) ? 1 : 0;
        $additionalSettings = trim($_POST['additional_settings'] ?? '');

        try {
            $stmt = $db->prepare("
                UPDATE payment_gateway_settings
                SET api_key = ?, api_secret = ?, merchant_id = ?, merchant_email = ?,
                    webhook_url = ?, return_url = ?, cancel_url = ?,
                    additional_settings = ?, is_active = ?, test_mode = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $additionalSettingsJson = !empty($additionalSettings) ? $additionalSettings : null;

            $stmt->execute([
                $apiKey, $apiSecret, $merchantId, $merchantEmail,
                $webhookUrl, $returnUrl, $cancelUrl,
                $additionalSettingsJson, $isActive, $testMode, $gatewayId
            ]);

            $success = ucfirst($gatewayName) . ' ' . $gatewayType . ' settings updated successfully!';

        } catch (PDOException $e) {
            $error = 'Error updating gateway settings: ' . $e->getMessage();
        }

    } elseif (isset($_POST['test_connection'])) {
        // Test gateway connection
        $gatewayId = (int)$_POST['gateway_id'];
        $gatewayName = trim($_POST['gateway_name']);
        $gatewayType = trim($_POST['gateway_type']);

        // Get gateway settings
        $stmt = $db->prepare("SELECT * FROM payment_gateway_settings WHERE id = ?");
        $stmt->execute([$gatewayId]);
        $gateway = $stmt->fetch();

        if ($gateway) {
            // Basic validation - check if required fields are filled
            $isValid = true;
            $missingFields = [];

            if (empty($gateway['api_key'])) {
                $isValid = false;
                $missingFields[] = 'API Key';
            }

            if ($gatewayName === 'paypal' && empty($gateway['api_secret'])) {
                $isValid = false;
                $missingFields[] = 'API Secret';
            }

            if ($gatewayName === 'paynow' && empty($gateway['merchant_id'])) {
                $isValid = false;
                $missingFields[] = 'Merchant ID';
            }

            if ($isValid) {
                $success = ucfirst($gatewayName) . ' ' . $gatewayType . ' connection test passed! Settings appear to be configured correctly.';
            } else {
                $error = 'Connection test failed. Missing required fields: ' . implode(', ', $missingFields);
            }
        } else {
            $error = 'Gateway settings not found.';
        }
    }
}

// Get all gateway settings
$stmt = $db->query("SELECT * FROM payment_gateway_settings ORDER BY gateway_name, gateway_type");
$gateways = $stmt->fetchAll();

$page_title = 'Payment Gateway 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="gateway-settings-section">
    <h2>Payment Gateway Settings</h2>
    <p class="settings-description">Configure payment gateway integrations for course and exam purchases. Each gateway supports both sandbox (testing) and live (production) environments.</p>

    <?php if (empty($gateways)): ?>
        <div class="alert alert-info">
            No payment gateways configured. Default gateway settings have been created in the database.
        </div>
    <?php else: ?>
        <?php foreach ($gateways as $gateway): ?>
            <div class="settings-card">
                <div class="gateway-header">
                    <h3>
                        <?php echo ucfirst(htmlspecialchars($gateway['gateway_name'])); ?> -
                        <?php echo ucfirst(htmlspecialchars($gateway['gateway_type'])); ?> Environment
                        <?php if ($gateway['is_active']): ?>
                            <span class="badge badge-success">Active</span>
                        <?php else: ?>
                            <span class="badge badge-secondary">Inactive</span>
                        <?php endif; ?>
                        <?php if ($gateway['test_mode']): ?>
                            <span class="badge badge-warning">Test Mode</span>
                        <?php endif; ?>
                    </h3>
                </div>

                <form method="POST">
                    <input type="hidden" name="gateway_id" value="<?php echo $gateway['id']; ?>">
                    <input type="hidden" name="gateway_name" value="<?php echo htmlspecialchars($gateway['gateway_name']); ?>">
                    <input type="hidden" name="gateway_type" value="<?php echo htmlspecialchars($gateway['gateway_type']); ?>">

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>API Key:</label>
                            <input type="text" name="api_key" value="<?php echo htmlspecialchars($gateway['api_key'] ?? ''); ?>"
                                   placeholder="Enter API Key">
                            <small>The API key provided by <?php echo ucfirst($gateway['gateway_name']); ?>.</small>
                        </div>

                        <?php if ($gateway['gateway_name'] === 'paypal'): ?>
                            <div class="form-group col-md-6">
                                <label>API Secret:</label>
                                <input type="password" name="api_secret" value="<?php echo htmlspecialchars($gateway['api_secret'] ?? ''); ?>"
                                       placeholder="Enter API Secret">
                                <small>The API secret provided by PayPal.</small>
                            </div>
                        <?php elseif ($gateway['gateway_name'] === 'paynow'): ?>
                            <div class="form-group col-md-6">
                                <label>Merchant ID:</label>
                                <input type="text" name="merchant_id" value="<?php echo htmlspecialchars($gateway['merchant_id'] ?? ''); ?>"
                                       placeholder="Enter Merchant ID">
                                <small>The merchant ID provided by Paynow.</small>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Merchant Email:</label>
                            <input type="email" name="merchant_email" value="<?php echo htmlspecialchars($gateway['merchant_email'] ?? ''); ?>"
                                   placeholder="merchant@example.com">
                            <small>The email associated with your merchant account.</small>
                        </div>

                        <div class="form-group col-md-6">
                            <label>Webhook URL:</label>
                            <input type="url" name="webhook_url" value="<?php echo htmlspecialchars($gateway['webhook_url'] ?? ''); ?>"
                                   placeholder="https://yourdomain.com/webhooks/<?php echo $gateway['gateway_name']; ?>">
                            <small>URL where <?php echo ucfirst($gateway['gateway_name']); ?> will send payment notifications.</small>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Return URL:</label>
                            <input type="url" name="return_url" value="<?php echo htmlspecialchars($gateway['return_url'] ?? ''); ?>"
                                   placeholder="https://yourdomain.com/payment/success">
                            <small>URL where users are redirected after successful payment.</small>
                        </div>

                        <div class="form-group col-md-6">
                            <label>Cancel URL:</label>
                            <input type="url" name="cancel_url" value="<?php echo htmlspecialchars($gateway['cancel_url'] ?? ''); ?>"
                                   placeholder="https://yourdomain.com/payment/cancelled">
                            <small>URL where users are redirected when payment is cancelled.</small>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Additional Settings (JSON):</label>
                        <textarea name="additional_settings" rows="3" placeholder='{"timeout": 30, "retry_count": 3}'><?php
                            echo htmlspecialchars($gateway['additional_settings'] ?? '');
                        ?></textarea>
                        <small>Optional JSON settings for advanced configuration.</small>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <div class="checkbox-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" name="is_active" value="1" <?php echo $gateway['is_active'] ? 'checked' : ''; ?>>
                                    <span class="checkmark"></span>
                                    Active
                                </label>
                                <small>Enable this gateway for processing payments.</small>
                            </div>
                        </div>

                        <div class="form-group col-md-6">
                            <div class="checkbox-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" name="test_mode" value="1" <?php echo $gateway['test_mode'] ? 'checked' : ''; ?>>
                                    <span class="checkmark"></span>
                                    Test Mode
                                </label>
                                <small>Use test/sandbox environment for this gateway.</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" name="update_gateway" class="btn btn-primary">Update Settings</button>
                        <button type="submit" name="test_connection" class="btn btn-secondary">Test Connection</button>
                    </div>
                </form>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- Gateway Status Overview -->
    <div class="settings-card">
        <h3>Gateway Status Overview</h3>
        <div class="gateway-status-grid">
            <?php
            $gatewayStats = $db->query("
                SELECT gateway_name, gateway_type, is_active, test_mode
                FROM payment_gateway_settings
                ORDER BY gateway_name, gateway_type
            ")->fetchAll();

            foreach ($gatewayStats as $stat):
            ?>
                <div class="status-item">
                    <div class="status-icon">
                        <?php if ($stat['is_active']): ?>
                            <i class="fas fa-check-circle text-success"></i>
                        <?php else: ?>
                            <i class="fas fa-times-circle text-muted"></i>
                        <?php endif; ?>
                    </div>
                    <div class="status-details">
                        <strong><?php echo ucfirst($stat['gateway_name']); ?> (<?php echo ucfirst($stat['gateway_type']); ?>)</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo $stat['is_active'] ? 'Active' : 'Inactive'; ?>
                            <?php if ($stat['test_mode']): echo ' - Test Mode'; endif; ?>
                        </small>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<style>
.gateway-settings-section {
    max-width: 1200px;
}

.gateway-settings-section h2 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 1rem;
}

.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;
}

.gateway-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
}

.gateway-header h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin: 0;
}

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

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

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

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

.form-row {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
}

.form-group {
    flex: 1;
    margin-bottom: 1rem;
}

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

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

.form-group textarea {
    resize: vertical;
}

.form-group small {
    display: block;
    color: #6b7280;
    font-size: 0.75rem;
    margin-top: 0.25rem;
}

.checkbox-group {
    margin-top: 0.5rem;
}

.checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-weight: normal;
}

.checkbox-label input[type="checkbox"] {
    margin-right: 0.5rem;
}

.form-actions {
    display: flex;
    gap: 1rem;
    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;
    transition: all 0.2s;
}

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

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

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

.btn-secondary:hover {
    background-color: #4b5563;
}

.gateway-status-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
}

.status-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    background: #f9fafb;
}

.status-icon {
    font-size: 1.5rem;
}

.status-details strong {
    color: #1f2937;
}

.status-details small {
    color: #6b7280;
}

.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;
}

.alert-info {
    background-color: #eff6ff;
    border: 1px solid #bfdbfe;
    color: #2563eb;
}

@media (max-width: 768px) {
    .form-row {
        flex-direction: column;
        gap: 0;
    }

    .gateway-status-grid {
        grid-template-columns: 1fr;
    }
}
</style>

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