<?php
/**
 * Admin Payment Settings - FIXED VERSION (No Duplicates)
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Payment Settings';

// FIXED: Ensure default gateways exist (only runs once)
$default_gateways = [
    'paypal' => ['client_id' => '', 'client_secret' => ''],
    'stripe' => ['publishable_key' => '', 'secret_key' => ''],
    'paystack' => ['public_key' => '', 'secret_key' => ''],
    'flutterwave' => ['public_key' => '', 'secret_key' => '', 'encryption_key' => ''],
    'eft' => ['bank_name' => '', 'account_number' => '', 'account_name' => '', 'branch_code' => ''],
    'bitcoin' => ['wallet_address' => '']
];

try {
    foreach ($default_gateways as $gateway_name => $config) {
        // FIXED: Use INSERT IGNORE to prevent duplicates
        $stmt = $pdo->prepare("INSERT IGNORE INTO payment_settings (gateway, is_active, test_mode, config, created_at, updated_at) 
                               VALUES (?, 0, 1, ?, NOW(), NOW())");
        $stmt->execute([$gateway_name, json_encode($config)]);
    }
} catch (PDOException $e) {
    // Silently continue
}

// Get all payment gateways
$gateways = [];
try {
    // FIXED: Use GROUP BY to ensure no duplicates
    $stmt = $pdo->query("SELECT * FROM payment_settings GROUP BY gateway ORDER BY gateway");
    $gateways = $stmt->fetchAll();
    
    foreach ($gateways as &$gateway) {
        $gateway['config'] = json_decode($gateway['config'], true) ?? [];
    }
    unset($gateway);
} catch (PDOException $e) {
    // Table might not exist
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request. Please try again.', 'error');
    } else {
        $gateway = sanitize($_POST['gateway'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $test_mode = isset($_POST['test_mode']) ? 1 : 0;
        
        // Build config based on gateway
        $config = [];
        switch ($gateway) {
            case 'paypal':
                $config = [
                    'client_id' => sanitize($_POST['client_id'] ?? ''),
                    'client_secret' => sanitize($_POST['client_secret'] ?? '')
                ];
                break;
            case 'stripe':
                $config = [
                    'publishable_key' => sanitize($_POST['publishable_key'] ?? ''),
                    'secret_key' => sanitize($_POST['secret_key'] ?? '')
                ];
                break;
            case 'paystack':
                $config = [
                    'public_key' => sanitize($_POST['public_key'] ?? ''),
                    'secret_key' => sanitize($_POST['secret_key'] ?? '')
                ];
                break;
            case 'flutterwave':
                $config = [
                    'public_key' => sanitize($_POST['public_key'] ?? ''),
                    'secret_key' => sanitize($_POST['secret_key'] ?? ''),
                    'encryption_key' => sanitize($_POST['encryption_key'] ?? '')
                ];
                break;
            case 'eft':
                $config = [
                    'bank_name' => sanitize($_POST['bank_name'] ?? ''),
                    'account_number' => sanitize($_POST['account_number'] ?? ''),
                    'account_name' => sanitize($_POST['account_name'] ?? ''),
                    'branch_code' => sanitize($_POST['branch_code'] ?? '')
                ];
                break;
            case 'bitcoin':
                $config = [
                    'wallet_address' => sanitize($_POST['wallet_address'] ?? '')
                ];
                break;
        }
        
        try {
            // FIXED: Use INSERT with ON DUPLICATE KEY UPDATE for single row per gateway
            $stmt = $pdo->prepare("INSERT INTO payment_settings (gateway, is_active, test_mode, config, created_at, updated_at) 
                                   VALUES (?, ?, ?, ?, NOW(), NOW()) 
                                   ON DUPLICATE KEY UPDATE 
                                   is_active = VALUES(is_active), 
                                   test_mode = VALUES(test_mode), 
                                   config = VALUES(config), 
                                   updated_at = NOW()");
            $stmt->execute([
                $gateway, $is_active, $test_mode, json_encode($config)
            ]);
            
            log_admin_activity($pdo, $admin_id, 'update_payment_settings', "Updated {$gateway} settings");
            set_flash_message('Payment settings saved successfully.', 'success');
            
            // Refresh gateways
            $stmt = $pdo->query("SELECT * FROM payment_settings GROUP BY gateway ORDER BY gateway");
            $gateways = $stmt->fetchAll();
            foreach ($gateways as &$gateway) {
                $gateway['config'] = json_decode($gateway['config'], true) ?? [];
            }
            unset($gateway);
            
        } catch (PDOException $e) {
            set_flash_message('Error saving settings: ' . $e->getMessage(), 'error');
        }
    }
}

// Handle quick toggle (enable/disable)
if (isset($_GET['toggle']) && in_array($_GET['toggle'], array_keys($default_gateways))) {
    $toggle_gateway = sanitize($_GET['toggle']);
    try {
        $stmt = $pdo->prepare("UPDATE payment_settings SET is_active = NOT is_active WHERE gateway = ?");
        $stmt->execute([$toggle_gateway]);
        
        $stmt = $pdo->prepare("SELECT is_active FROM payment_settings WHERE gateway = ?");
        $stmt->execute([$toggle_gateway]);
        $result = $stmt->fetch();
        
        $status = $result && $result['is_active'] ? 'enabled' : 'disabled';
        set_flash_message(ucfirst($toggle_gateway) . ' ' . $status . ' successfully.', 'success');
        
        header('Location: ' . ADMIN_URL . '/payment-settings.php');
        exit;
    } catch (PDOException $e) {
        set_flash_message('Error toggling gateway: ' . $e->getMessage(), 'error');
    }
}

// Get gateway for editing
$edit_gateway = null;
if (isset($_GET['gateway'])) {
    foreach ($gateways as $g) {
        if ($g['gateway'] === $_GET['gateway']) {
            $edit_gateway = $g;
            break;
        }
    }
}
?>

<div class="page-header">
    <div>
        <h1>Payment Settings</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Payment Settings</li>
            </ol>
        </nav>
    </div>
</div>

<?php echo get_flash_message(); ?>

<div class="row">
    <!-- Payment Gateways List -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-credit-card me-2"></i>Payment Gateways
            </div>
            <div class="list-group list-group-flush">
                <?php foreach ($gateways as $gateway): ?>
                <div class="list-group-item d-flex justify-content-between align-items-center <?php echo ($edit_gateway && $edit_gateway['gateway'] === $gateway['gateway']) ? 'active' : ''; ?>">
                    <a href="?gateway=<?php echo $gateway['gateway']; ?>" class="text-decoration-none flex-grow-1">
                        <i class="fas fa-<?php echo get_gateway_icon($gateway['gateway']); ?> me-2"></i>
                        <?php echo ucfirst($gateway['gateway']); ?>
                    </a>
                    <div class="d-flex align-items-center gap-2">
                        <?php if ($gateway['is_active']): ?>
                        <span class="badge bg-success">Active</span>
                        <?php else: ?>
                        <span class="badge bg-secondary">Inactive</span>
                        <?php endif; ?>
                        <a href="?toggle=<?php echo $gateway['gateway']; ?>" class="btn btn-sm <?php echo $gateway['is_active'] ? 'btn-outline-danger' : 'btn-outline-success'; ?>" 
                           title="<?php echo $gateway['is_active'] ? 'Disable' : 'Enable'; ?>">
                            <i class="fas fa-<?php echo $gateway['is_active'] ? 'times' : 'check'; ?>"></i>
                        </a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="card mt-4">
            <div class="card-header">
                <i class="fas fa-info-circle me-2"></i>Quick Info
            </div>
            <div class="card-body">
                <p class="mb-2"><strong>Active Gateways:</strong> <?php echo count(array_filter($gateways, fn($g) => $g['is_active'])); ?></p>
                <p class="mb-0"><strong>Test Mode:</strong> <?php echo count(array_filter($gateways, fn($g) => $g['test_mode'])); ?> enabled</p>
            </div>
        </div>
    </div>
    
    <!-- Gateway Configuration -->
    <div class="col-lg-8">
        <?php if ($edit_gateway): ?>
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <i class="fas fa-<?php echo get_gateway_icon($edit_gateway['gateway']); ?> me-2"></i>
                    <?php echo ucfirst($edit_gateway['gateway']); ?> Configuration
                </div>
                <?php if ($edit_gateway['is_active']): ?>
                <span class="badge bg-success">Active</span>
                <?php else: ?>
                <span class="badge bg-secondary">Inactive</span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="gateway" value="<?php echo $edit_gateway['gateway']; ?>">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-check form-switch">
                                <input type="checkbox" name="is_active" class="form-check-input" id="is_active" 
                                       <?php echo $edit_gateway['is_active'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="is_active">Enable <?php echo ucfirst($edit_gateway['gateway']); ?></label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check form-switch">
                                <input type="checkbox" name="test_mode" class="form-check-input" id="test_mode" 
                                       <?php echo $edit_gateway['test_mode'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="test_mode">Test Mode</label>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <?php if ($edit_gateway['gateway'] === 'paypal'): ?>
                    <div class="mb-3">
                        <label class="form-label">Client ID</label>
                        <input type="text" name="client_id" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['client_id'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Client Secret</label>
                        <input type="password" name="client_secret" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['client_secret'] ?? ''); ?>"
                               placeholder="Enter client secret">
                    </div>
                    
                    <?php elseif ($edit_gateway['gateway'] === 'stripe'): ?>
                    <div class="mb-3">
                        <label class="form-label">Publishable Key</label>
                        <input type="text" name="publishable_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['publishable_key'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Secret Key</label>
                        <input type="password" name="secret_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['secret_key'] ?? ''); ?>"
                               placeholder="Enter secret key">
                    </div>
                    
                    <?php elseif ($edit_gateway['gateway'] === 'paystack'): ?>
                    <div class="mb-3">
                        <label class="form-label">Public Key</label>
                        <input type="text" name="public_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['public_key'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Secret Key</label>
                        <input type="password" name="secret_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['secret_key'] ?? ''); ?>"
                               placeholder="Enter secret key">
                    </div>
                    
                    <?php elseif ($edit_gateway['gateway'] === 'flutterwave'): ?>
                    <div class="mb-3">
                        <label class="form-label">Public Key</label>
                        <input type="text" name="public_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['public_key'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Secret Key</label>
                        <input type="password" name="secret_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['secret_key'] ?? ''); ?>"
                               placeholder="Enter secret key">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Encryption Key</label>
                        <input type="password" name="encryption_key" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['encryption_key'] ?? ''); ?>"
                               placeholder="Enter encryption key">
                    </div>
                    
                    <?php elseif ($edit_gateway['gateway'] === 'eft'): ?>
                    <div class="mb-3">
                        <label class="form-label">Bank Name</label>
                        <input type="text" name="bank_name" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['bank_name'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Account Number</label>
                        <input type="text" name="account_number" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['account_number'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Account Name</label>
                        <input type="text" name="account_name" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['account_name'] ?? ''); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Branch Code</label>
                        <input type="text" name="branch_code" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['branch_code'] ?? ''); ?>">
                    </div>
                    
                    <?php elseif ($edit_gateway['gateway'] === 'bitcoin'): ?>
                    <div class="mb-3">
                        <label class="form-label">Bitcoin Wallet Address</label>
                        <input type="text" name="wallet_address" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_gateway['config']['wallet_address'] ?? ''); ?>">
                        <small class="text-muted">Your Bitcoin receiving address</small>
                    </div>
                    <?php endif; ?>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Save Settings
                    </button>
                </form>
            </div>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-credit-card fa-3x text-muted mb-3"></i>
                <h5>Select a Payment Gateway</h5>
                <p class="text-muted">Click on a payment gateway from the list to configure it.</p>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php
function get_gateway_icon($gateway) {
    $icons = [
        'paypal' => 'cc-paypal',
        'stripe' => 'cc-stripe',
        'paystack' => 'credit-card',
        'flutterwave' => 'credit-card',
        'eft' => 'university',
        'bitcoin' => 'bitcoin'
    ];
    return $icons[$gateway] ?? 'credit-card';
}

require_once __DIR__ . '/includes/footer.php';
?>
