<?php
/**
 * Admin Payments Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Payment Gateways';

$errors = [];
$success = false;

// Get payment gateways
$gateways = get_active_payment_gateways();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        foreach ($_POST['gateways'] as $gateway => $config) {
            $is_active = isset($config['is_active']) ? 1 : 0;
            unset($config['is_active']);
            
            // Save config as JSON
            $config_json = json_encode($config);
            
            try {
                $stmt = $pdo->prepare("INSERT INTO payment_settings (gateway, config, is_active, created_at, updated_at) 
                                       VALUES (?, ?, ?, NOW(), NOW()) 
                                       ON DUPLICATE KEY UPDATE config = ?, is_active = ?, updated_at = NOW()");
                $stmt->execute([$gateway, $config_json, $is_active, $config_json, $is_active]);
            } catch (PDOException $e) {
                $errors[] = "Failed to save {$gateway} settings: " . $e->getMessage();
            }
        }
        
        if (empty($errors)) {
            $success = true;
            set_flash_message('Payment settings updated successfully!', 'success');
            
            // Refresh gateways
            $gateways = get_active_payment_gateways();
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header">
        <h1><i class="fas fa-credit-card me-2"></i>Payment Gateways</h1>
    </div>
    
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $error): ?>
                <p class="mb-1"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <form method="POST">
        <?php echo csrf_field(); ?>
        
        <div class="row g-4">
            <!-- PayPal -->
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fab fa-paypal me-2"></i>PayPal</h5>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" name="gateways[paypal][is_active]" 
                                   <?php echo ($gateways['paypal']['is_active'] ?? false) ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Mode</label>
                            <select name="gateways[paypal][mode]" class="form-select">
                                <option value="sandbox" <?php echo ($gateways['paypal']['config']['mode'] ?? '') === 'sandbox' ? 'selected' : ''; ?>>Sandbox (Test)</option>
                                <option value="live" <?php echo ($gateways['paypal']['config']['mode'] ?? '') === 'live' ? 'selected' : ''; ?>>Live</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Client ID</label>
                            <input type="text" name="gateways[paypal][client_id]" class="form-control" 
                                   value="<?php echo sanitize($gateways['paypal']['config']['client_id'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Client Secret</label>
                            <input type="password" name="gateways[paypal][client_secret]" class="form-control" 
                                   value="<?php echo sanitize($gateways['paypal']['config']['client_secret'] ?? ''); ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Stripe -->
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fab fa-stripe me-2"></i>Stripe</h5>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" name="gateways[stripe][is_active]" 
                                   <?php echo ($gateways['stripe']['is_active'] ?? false) ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Mode</label>
                            <select name="gateways[stripe][mode]" class="form-select">
                                <option value="test" <?php echo ($gateways['stripe']['config']['mode'] ?? '') === 'test' ? 'selected' : ''; ?>>Test</option>
                                <option value="live" <?php echo ($gateways['stripe']['config']['mode'] ?? '') === 'live' ? 'selected' : ''; ?>>Live</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Publishable Key</label>
                            <input type="text" name="gateways[stripe][publishable_key]" class="form-control" 
                                   value="<?php echo sanitize($gateways['stripe']['config']['publishable_key'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Secret Key</label>
                            <input type="password" name="gateways[stripe][secret_key]" class="form-control" 
                                   value="<?php echo sanitize($gateways['stripe']['config']['secret_key'] ?? ''); ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Bank Transfer -->
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-university me-2"></i>Bank Transfer</h5>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" name="gateways[bank_transfer][is_active]" 
                                   <?php echo ($gateways['bank_transfer']['is_active'] ?? false) ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Bank Name</label>
                            <input type="text" name="gateways[bank_transfer][bank_name]" class="form-control" 
                                   value="<?php echo sanitize($gateways['bank_transfer']['config']['bank_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Account Name</label>
                            <input type="text" name="gateways[bank_transfer][account_name]" class="form-control" 
                                   value="<?php echo sanitize($gateways['bank_transfer']['config']['account_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Account Number</label>
                            <input type="text" name="gateways[bank_transfer][account_number]" class="form-control" 
                                   value="<?php echo sanitize($gateways['bank_transfer']['config']['account_number'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Routing Number / IBAN</label>
                            <input type="text" name="gateways[bank_transfer][routing_number]" class="form-control" 
                                   value="<?php echo sanitize($gateways['bank_transfer']['config']['routing_number'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Instructions</label>
                            <textarea name="gateways[bank_transfer][instructions]" class="form-control" rows="3"><?php echo sanitize($gateways['bank_transfer']['config']['instructions'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Cash on Delivery -->
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-money-bill-wave me-2"></i>Cash on Delivery</h5>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" name="gateways[cod][is_active]" 
                                   <?php echo ($gateways['cod']['is_active'] ?? false) ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Instructions</label>
                            <textarea name="gateways[cod][instructions]" class="form-control" rows="3"><?php echo sanitize($gateways['cod']['config']['instructions'] ?? 'Pay when you receive your order.'); ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="mt-4">
            <button type="submit" class="btn btn-primary btn-lg">
                <i class="fas fa-save me-2"></i>Save Payment Settings
            </button>
        </div>
    </form>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
