<?php
// Payment Configuration Page Content
require_once '../config_paystack.php';

// Set page variables for header
$page_title = 'Payment Configuration';
$page_description = 'Configure payment settings, Paystack integration, and contact information';

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

// Check for success parameter from redirect
if (isset($_GET['success']) && $_GET['success'] == '1') {
    $success_message = 'Payment configuration updated successfully!';
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment_config'])) {
    $paystack_public_key = trim($_POST['paystack_public_key'] ?? '');
    $paystack_secret_key = trim($_POST['paystack_secret_key'] ?? '');
    $paystack_base_url = trim($_POST['paystack_base_url'] ?? 'https://api.paystack.co');
    $payment_phone_number = trim($_POST['payment_phone_number'] ?? '');
    $payment_name = trim($_POST['payment_name'] ?? '');
    $whatsapp_contact = trim($_POST['whatsapp_contact'] ?? '');
    $whatsapp_group_link = trim($_POST['whatsapp_group_link'] ?? '');
    $contact_email = trim($_POST['contact_email'] ?? '');
    $business_address = trim($_POST['business_address'] ?? '');
    $company_name = trim($_POST['company_name'] ?? '');
    
    if (empty($payment_phone_number) || empty($payment_name)) {
        $error_message = 'Payment phone number and name are required.';
    } else {
        try {
            $conn->begin_transaction();
            
            $updates = [
                'paystack_public_key' => $paystack_public_key,
                'paystack_secret_key' => $paystack_secret_key,
                'paystack_base_url' => $paystack_base_url,
                'payment_phone_number' => $payment_phone_number,
                'payment_name' => $payment_name,
                'whatsapp_contact' => $whatsapp_contact,
                'whatsapp_group_link' => $whatsapp_group_link,
                'contact_email' => $contact_email,
                'business_address' => $business_address,
                'company_name' => $company_name
            ];
            
            foreach ($updates as $key => $value) {
                // Check if the configuration key exists
                $check_stmt = $conn->prepare("SELECT id FROM payment_config WHERE config_key = ?");
                $check_stmt->bind_param("s", $key);
                $check_stmt->execute();
                $result = $check_stmt->get_result();
                
                if ($result->num_rows > 0) {
                    // Update existing configuration
                    $update_stmt = $conn->prepare("UPDATE payment_config SET config_value = ? WHERE config_key = ?");
                    $update_stmt->bind_param("ss", $value, $key);
                    $update_stmt->execute();
                    $update_stmt->close();
                } else {
                    // Insert new configuration
                    $insert_stmt = $conn->prepare("INSERT INTO payment_config (config_key, config_value, description) VALUES (?, ?, ?)");
                    $description = ucwords(str_replace('_', ' ', $key)) . ' configuration';
                    $insert_stmt->bind_param("sss", $key, $value, $description);
                    $insert_stmt->execute();
                    $insert_stmt->close();
                }
                $check_stmt->close();
            }
            
            // Paystack configuration is now loaded dynamically from database
            // No need to update config files - keys are fetched at runtime
            
            // Clear the Paystack configuration cache to ensure fresh data
            if (function_exists('clearPaystackConfigCache')) {
                clearPaystackConfigCache();
            }
            /*
            // Update the config_paystack.php file with new values
            if (!empty($paystack_public_key) && !empty($paystack_secret_key)) {
                $config_content = "<?php\n";
                $config_content .= "// Paystack configuration\n";
                $config_content .= "// Updated from admin dashboard on " . date('Y-m-d H:i:s') . "\n";
                $config_content .= "\$PAYSTACK_PUBLIC_KEY = getenv('PAYSTACK_PUBLIC_KEY') ?: '$paystack_public_key';\n";
                $config_content .= "\$PAYSTACK_SECRET_KEY = getenv('PAYSTACK_SECRET_KEY') ?: '$paystack_secret_key';\n";
                $config_content .= "\$PAYSTACK_BASE_URL = '$paystack_base_url';\n\n";
                
                // Read existing config file and preserve other settings
                $config_file = '../config_paystack.php';
                if (file_exists($config_file)) {
                    $existing_content = file_get_contents($config_file);
                    $config_content = preg_replace('/\$PAYSTACK_PUBLIC_KEY = .*?;/', '', $existing_content);
                    $config_content = preg_replace('/\$PAYSTACK_SECRET_KEY = .*?;/', '', $config_content);
                    $config_content = preg_replace('/\$PAYSTACK_BASE_URL = .*?;/', '', $config_content);
                    $config_content = preg_replace('/<\?php.*?\n/', '', $config_content);
                    
                    $final_config = "<?php\n";
                    $final_config .= "// Paystack configuration\n";
                    $final_config .= "// Updated from admin dashboard on " . date('Y-m-d H:i:s') . "\n";
                    $final_config .= "\$PAYSTACK_PUBLIC_KEY = getenv('PAYSTACK_PUBLIC_KEY') ?: '$paystack_public_key';\n";
                    $final_config .= "\$PAYSTACK_SECRET_KEY = getenv('PAYSTACK_SECRET_KEY') ?: '$paystack_secret_key';\n";
                    $final_config .= "\$PAYSTACK_BASE_URL = '$paystack_base_url';\n\n";
                    $final_config .= $config_content;
                    $config_content = $final_config;
                }
                
                file_put_contents($config_file, $config_content);
            }
            */
            
                $conn->commit();
                $success_message = 'Payment configuration updated successfully!';
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = 'Failed to update payment configuration: ' . $e->getMessage();
        }
    }
}

// Fetch payment configurations
$payment_configs = [];
$config_keys = ['paystack_public_key', 'paystack_secret_key', 'paystack_base_url', 'payment_phone_number', 'payment_name', 'whatsapp_contact', 'whatsapp_group_link', 'contact_email', 'business_address', 'company_name'];

foreach ($config_keys as $key) {
    $stmt = $conn->prepare("SELECT config_value FROM payment_config WHERE config_key = ?");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $payment_configs[$key] = $row ? $row['config_value'] : '';
    $stmt->close();
}
?>

<!-- Payment Configuration Content -->
<div class="space-y-6">
    <?php if ($success_message): ?>
    <div class="p-4 rounded-lg bg-green-100 text-green-800 border border-green-200">
        <i class="fas fa-check-circle mr-2"></i><?= htmlspecialchars($success_message) ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="p-4 rounded-lg bg-red-100 text-red-800 border border-red-200">
        <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($error_message) ?>
    </div>
    <?php endif; ?>
    
    <div class="bg-gray-800 rounded-xl shadow-lg p-6 border border-gray-700">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold text-gray-100">
                <i class="fas fa-credit-card text-blue-500 mr-3"></i>Payment Configuration
        </h2>
            <button onclick="testPaystackConnection()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
                <i class="fas fa-plug mr-2"></i>Test Connection
            </button>
        </div>

        <!-- Payment Configuration Form -->
        <form method="POST" action="" class="space-y-6">
            <input type="hidden" name="update_payment_config" value="1">
            
            <!-- Paystack Configuration Section -->
            <div class="bg-blue-900/20 rounded-lg p-6 border border-blue-700/50 config-section">
                <h3 class="text-lg font-semibold text-blue-300 mb-4">
                    <i class="fas fa-credit-card mr-2"></i>Paystack Configuration
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Paystack Public Key</label>
                        <input type="text" name="paystack_public_key" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['paystack_public_key']) ?>" 
                               placeholder="pk_test_xxxxxxxxxx">
                        <p class="text-xs text-blue-400 mt-1">Your Paystack public key for frontend integration</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Paystack Secret Key</label>
                        <input type="password" name="paystack_secret_key" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['paystack_secret_key']) ?>" 
                               placeholder="sk_test_xxxxxxxxxx">
                        <p class="text-xs text-blue-400 mt-1">Your Paystack secret key for server-side operations</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-300 mb-2">Paystack Base URL</label>
                        <input type="url" name="paystack_base_url" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['paystack_base_url'] ?: 'https://api.paystack.co') ?>" 
                               placeholder="https://api.paystack.co">
                        <p class="text-xs text-blue-400 mt-1">Paystack API base URL (usually https://api.paystack.co)</p>
                    </div>
                </div>
            </div>

            <!-- Mobile Money Configuration Section -->
            <div class="bg-green-900/20 rounded-lg p-6 border border-green-700/50 config-section">
                <h3 class="text-lg font-semibold text-green-300 mb-4">
                    <i class="fas fa-mobile-alt mr-2"></i>Mobile Money Configuration
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Payment Phone Number</label>
                        <input type="tel" name="payment_phone_number" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-green-500 focus:ring-1 focus:ring-green-500" 
                               value="<?= htmlspecialchars($payment_configs['payment_phone_number']) ?>" 
                               placeholder="+233XXXXXXXXX" required>
                        <p class="text-xs text-green-400 mt-1">Phone number for manual mobile money payments</p>
                </div>
                
                <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Account Holder Name</label>
                        <input type="text" name="payment_name" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-green-500 focus:ring-1 focus:ring-green-500" 
                               value="<?= htmlspecialchars($payment_configs['payment_name']) ?>" 
                               placeholder="John Doe" required>
                        <p class="text-xs text-green-400 mt-1">Name associated with the payment phone number</p>
                    </div>
                </div>
            </div>

            <!-- Support Configuration Section -->
            <div class="bg-purple-900/20 rounded-lg p-6 border border-purple-700/50 config-section">
                <h3 class="text-lg font-semibold text-purple-300 mb-4">
                    <i class="fab fa-whatsapp mr-2"></i>Support Configuration
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">WhatsApp Contact</label>
                        <input type="tel" name="whatsapp_contact" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-purple-500 focus:ring-1 focus:ring-purple-500" 
                               value="<?= htmlspecialchars($payment_configs['whatsapp_contact']) ?>" 
                               placeholder="+233XXXXXXXXX">
                        <p class="text-xs text-purple-400 mt-1">WhatsApp number for customer support</p>
                </div>
                
                <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">WhatsApp Group Link</label>
                        <input type="url" name="whatsapp_group_link" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-purple-500 focus:ring-1 focus:ring-purple-500" 
                               value="<?= htmlspecialchars($payment_configs['whatsapp_group_link']) ?>" 
                               placeholder="https://chat.whatsapp.com/xxxxxxxxxx">
                        <p class="text-xs text-purple-400 mt-1">WhatsApp group invite link for customers</p>
                    </div>
                </div>
                
                <!-- Additional Contact Information -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Contact Email</label>
                        <input type="email" name="contact_email" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['contact_email']) ?>" 
                               placeholder="support@megabytehub.com">
                        <p class="text-xs text-blue-400 mt-1">Email address for customer support</p>
                </div>
                
                <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Business Address</label>
                        <input type="text" name="business_address" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['business_address']) ?>" 
                               placeholder="Ghana">
                        <p class="text-xs text-blue-400 mt-1">Business location or address</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-300 mb-2">Company Name</label>
                        <input type="text" name="company_name" class="w-full rounded-lg p-3 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" 
                               value="<?= htmlspecialchars($payment_configs['company_name']) ?>" 
                               placeholder="D-Bundles Stores">
                        <p class="text-xs text-blue-400 mt-1">Company name displayed in footer and branding</p>
                    </div>
                </div>
            </div>
            
            <!-- Submit Button -->
            <div class="flex justify-end">
                <button type="submit" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors">
                    <i class="fas fa-save mr-2"></i>Save Configuration
                </button>
            </div>
        </form>

        <!-- Configuration Preview -->
        <div class="mt-8 bg-gray-700/50 rounded-lg p-6 border border-gray-600 config-preview">
            <h3 class="text-lg font-semibold text-gray-100 mb-4">
                <i class="fas fa-eye mr-2"></i>Current Configuration Preview
        </h3>
            <div class="overflow-x-auto">
                <table class="min-w-full bg-gray-800 border border-gray-600 rounded-lg">
                    <thead class="bg-gray-700">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Setting</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Value</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Status</th>
                        </tr>
                    </thead>
                    <tbody class="bg-gray-800 divide-y divide-gray-600">
                        <?php foreach ($payment_configs as $key => $value): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-200">
                                <?= ucwords(str_replace('_', ' ', $key)) ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-200">
                                <?php if (strpos($key, 'secret') !== false): ?>
                                    <span class="text-gray-400">••••••••••••</span>
                                <?php else: ?>
                                    <?= htmlspecialchars($value ?: 'Not set') ?>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <?php if (empty($value)): ?>
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-900/50 text-red-300 border border-red-700">Not Configured</span>
                    <?php else: ?>
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-900/50 text-green-300 border border-green-700">Configured</span>
                    <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Test Paystack connection
function testPaystackConnection() {
    const publicKey = document.querySelector('input[name="paystack_public_key"]').value;
    const secretKey = document.querySelector('input[name="paystack_secret_key"]').value;
    
    if (!publicKey || !secretKey) {
        showMessage('Please enter both Paystack public and secret keys before testing', 'error');
        return;
    }
    
    showMessage('Testing Paystack connection...', 'info');
    
    // Create test payload
    const testData = {
        public_key: publicKey,
        secret_key: secretKey
    };
    
    fetch('pages/test_paystack_connection.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(testData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('✅ Paystack connection successful! ' + data.message, 'success');
        } else {
            showMessage('❌ Paystack connection failed: ' + data.message, 'error');
        }
    })
    .catch(error => {
        showMessage('❌ Error testing Paystack connection: ' + error.message, 'error');
    });
}

// Message display function (matching admin dashboard style)
function showMessage(message, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-md w-full mx-4`;
    messageDiv.innerHTML = `
        <div class="bg-${type === 'success' ? 'green' : 'red'}-50 border border-${type === 'success' ? 'green' : 'red'}-200 text-${type === 'success' ? 'green' : 'red'}-700 px-4 py-3 rounded-xl shadow-lg flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-3"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(messageDiv);
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        messageDiv.style.transform = 'translate(-50%, -100%)';
        setTimeout(() => messageDiv.remove(), 300);
    }, 5000);
}
</script>