<?php
// Initialize session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';

// Strict Auth Check
if (empty($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

// CSRF Protection
if (empty($_SESSION['admin_csrf_token'])) {
    $_SESSION['admin_csrf_token'] = bin2hex(random_bytes(32));
}

$success_msg = '';
$error_msg = '';

// =========================================================
// MASS UPDATE HANDLER
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payments'])) {
    if (!hash_equals($_SESSION['admin_csrf_token'], $_POST['csrf_token'] ?? '')) {
        $error_msg = "Security Error: Invalid CSRF Token Submission.";
    } elseif (isset($_POST['settings']) && is_array($_POST['settings'])) {
        try {
            $pdo->beginTransaction();
            $update_stmt = $pdo->prepare("UPDATE payment_settings SET key_value = ? WHERE key_name = ?");
            
            foreach ($_POST['settings'] as $key => $value) {
                $clean_value = trim(htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
                $clean_key = trim(htmlspecialchars($key, ENT_QUOTES, 'UTF-8'));
                $update_stmt->execute([$clean_value, $clean_key]);
            }
            
            $pdo->commit();
            $success_msg = "Payment Gateway APIs synchronized securely.";
        } catch (PDOException $e) {
            $pdo->rollBack();
            error_log("Payment Settings Sync Failed: " . $e->getMessage());
            $error_msg = "Matrix sync failed. Please check the system logs.";
        }
    }
}

// =========================================================
// FETCH ALL PAYMENT GATEWAYS
// =========================================================
$gateways = [];
try {
    $stmt = $pdo->query("SELECT * FROM payment_settings ORDER BY gateway_name ASC, id ASC");
    $content_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($content_rows as $row) {
        $gateway = $row['gateway_name'];
        $gateways[$gateway][] = $row;
    }
} catch (PDOException $e) {
    $error_msg = "Database Error: Ensure the `payment_settings` table exists.";
}

// Count active gateways
$active_gateways = 0;
foreach ($gateways as $g) {
    foreach ($g as $field) {
        if ($field['key_name'] === strtolower(str_replace(' ', '_', $field['gateway_name'])) . '_status' && $field['key_value'] === 'active') {
            $active_gateways++;
            break;
        }
    }
}
$total_gateways = count($gateways);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Payment Gateway Integration</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .gateway-card {
            transition: all 0.2s ease;
        }
        .gateway-card:hover {
            transform: translateY(-2px);
        }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <div class="inline-flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-emerald-400 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                    <span>API Integrations</span>
                </div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Payment Gateways</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Manage API keys and active status securely.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Total Gateways</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total_gateways; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Active</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $active_gateways; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Inactive</span>
                <span class="text-2xl font-extrabold text-rose-600 dark:text-rose-500 mt-1 block"><?php echo $total_gateways - $active_gateways; ?></span>
            </div>
        </div>

        <!-- ========== MAIN FORM ========== -->
        <form action="payment-integration.php" method="POST" class="w-full space-y-6">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['admin_csrf_token']); ?>">
            
            <?php if(empty($gateways)): ?>
                <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-12 text-center shadow-sm">
                    <span class="text-slate-500 text-xs font-bold uppercase tracking-widest block mb-2">No Gateways Configured</span>
                    <p class="text-slate-400 text-sm">Please populate the `payment_settings` table.</p>
                </div>
            <?php else: ?>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <?php foreach ($gateways as $gateway_name => $fields): 
                        // Determine gateway type for styling
                        $gateway_lower = strtolower($gateway_name);
                        $accent_color = 'emerald';
                        $icon = '💳';
                        if (strpos($gateway_lower, 'paystack') !== false) {
                            $accent_color = 'blue';
                            $icon = '💳';
                        } elseif (strpos($gateway_lower, 'stripe') !== false) {
                            $accent_color = 'indigo';
                            $icon = '🏦';
                        } elseif (strpos($gateway_lower, 'nowpayments') !== false) {
                            $accent_color = 'amber';
                            $icon = '🌐';
                        } elseif (strpos($gateway_lower, 'manual') !== false) {
                            $accent_color = 'emerald';
                            $icon = '🧠';
                        }
                        
                        // Check if this gateway is active (look for status key)
                        $is_active = false;
                        foreach ($fields as $f) {
                            if (strpos($f['key_name'], 'status') !== false && $f['key_value'] === 'active') {
                                $is_active = true;
                                break;
                            }
                        }
                    ?>
                        <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 sm:p-6 shadow-sm gateway-card transition-colors duration-300">
                            <div class="flex items-center justify-between mb-5 border-b border-slate-200 dark:border-slate-800 pb-3">
                                <div class="flex items-center gap-3">
                                    <span class="text-2xl"><?php echo $icon; ?></span>
                                    <h3 class="font-black text-lg text-slate-900 dark:text-white tracking-tight">
                                        <?php echo htmlspecialchars($gateway_name); ?>
                                    </h3>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="w-2 h-2 rounded-full <?php echo $is_active ? 'bg-emerald-500' : 'bg-rose-500'; ?> animate-pulse"></span>
                                    <span class="text-[9px] font-black <?php echo $is_active ? 'text-emerald-500' : 'text-rose-500'; ?> uppercase tracking-wider">
                                        <?php echo $is_active ? 'Live' : 'Offline'; ?>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="space-y-4">
                                <?php foreach ($fields as $field): ?>
                                    <div>
                                        <div class="flex justify-between items-center mb-1.5">
                                            <label class="text-[10px] text-slate-500 dark:text-gray-400 tracking-wider uppercase font-bold">
                                                <?php echo htmlspecialchars($field['display_name']); ?>
                                            </label>
                                            <span class="text-[8px] font-mono text-slate-400 dark:text-gray-500 bg-slate-100 dark:bg-slate-800 px-2 py-0.5 rounded"><?php echo htmlspecialchars($field['key_name']); ?></span>
                                        </div>
                                        
                                        <?php if ($field['field_type'] === 'status'): ?>
                                            <select name="settings[<?php echo htmlspecialchars($field['key_name']); ?>]" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white font-bold text-xs uppercase tracking-wider focus:outline-none focus:ring-2 focus:ring-<?php echo $accent_color; ?>-500/50 focus:border-<?php echo $accent_color; ?>-500 transition-all cursor-pointer">
                                                <option value="active" class="text-emerald-500 font-bold" <?php echo ($field['key_value'] === 'active') ? 'selected' : ''; ?>>🟢 Active</option>
                                                <option value="inactive" class="text-rose-500 font-bold" <?php echo ($field['key_value'] !== 'active') ? 'selected' : ''; ?>>🔴 Inactive</option>
                                            </select>
                                        
                                        <?php elseif ($field['field_type'] === 'password'): ?>
                                            <input type="password" name="settings[<?php echo htmlspecialchars($field['key_name']); ?>]" value="<?php echo htmlspecialchars($field['key_value'] ?? ''); ?>" placeholder="Enter <?php echo htmlspecialchars($field['display_name']); ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-rose-500/50 focus:border-rose-500 text-sm font-mono transition-all">
                                        
                                        <?php else: ?>
                                            <input type="text" name="settings[<?php echo htmlspecialchars($field['key_name']); ?>]" value="<?php echo htmlspecialchars($field['key_value'] ?? ''); ?>" placeholder="Enter <?php echo htmlspecialchars($field['display_name']); ?>" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-<?php echo $accent_color; ?>-500/50 focus:border-<?php echo $accent_color; ?>-500 text-sm font-mono transition-all">
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Sticky Save Button -->
                <div class="sticky bottom-6 mt-4 flex justify-end z-40">
                    <button type="submit" name="update_payments" class="bg-gradient-to-r from-emerald-600 to-cyan-600 hover:from-emerald-500 hover:to-cyan-500 text-white font-black py-4 px-8 rounded-xl transition-all shadow-xl shadow-emerald-900/30 text-xs tracking-widest uppercase flex items-center gap-3 border border-emerald-400/20 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-slate-900">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                        <span>Update Gateways</span>
                    </button>
                </div>
            <?php endif; ?>
            
        </form>

    </main>
</body>
</html>