<?php
/**
 * Agentic Square - Premium Payment Processor Integration Gateway Control
 * Path: admin/payment-setting.php
 */

// Inject Core Global Application Engine Paths
require_once __DIR__ . '/../config/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * STRICT SECURITY AUDIT GUARD (Envato Marketplace Compliant)
 */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

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

/**
 * SYSTEM SETTINGS METADATA UTILITY PARSER
 * Pulls and writes key-value items explicitly using the 'payment_settings' table.
 */
function getPaymentSetting($pdo, $key, $default = '') {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM payment_settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        return $row ? $row['setting_value'] : $default;
    } catch (Exception $e) {
        return $default;
    }
}

function updatePaymentSetting($pdo, $key, $value) {
    // Check if configuration cell row already exists
    $stmt = $pdo->prepare("SELECT id FROM payment_settings WHERE setting_key = ? LIMIT 1");
    $stmt->execute([$key]);
    if ($stmt->fetch()) {
        $update = $pdo->prepare("UPDATE payment_settings SET setting_value = ? WHERE setting_key = ?");
        $update->execute([$value, $key]);
    } else {
        $insert = $pdo->prepare("INSERT INTO payment_settings (setting_key, setting_value) VALUES (?, ?)");
        $insert->execute([$key, $value]);
    }
}

// Hydrate parameters safely from the database records map
$paypal_email   = getPaymentSetting($pdo, 'paypal_email', '');
$paypal_status  = getPaymentSetting($pdo, 'paypal_status', 'inactive');
$stripe_key     = getPaymentSetting($pdo, 'stripe_key', '');
$stripe_secret  = getPaymentSetting($pdo, 'stripe_secret', '');
$stripe_status  = getPaymentSetting($pdo, 'stripe_status', 'inactive');

/**
 * POST DISPATCH TRANSACTION INTERCEPT ENGINE
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Capture state values from clean text-inputs 
    $paypal_email   = trim($_POST['paypal_email'] ?? '');
    $paypal_status  = ($_POST['paypal_status'] === 'active') ? 'active' : 'inactive';
    
    $stripe_key     = trim($_POST['stripe_key'] ?? '');
    $stripe_secret  = trim($_POST['stripe_secret'] ?? '');
    $stripe_status  = ($_POST['stripe_status'] === 'active') ? 'active' : 'inactive';

    // Strict Framework Rules Validation
    if ($paypal_status === 'active' && empty($paypal_email)) {
        $error_msg = "PayPal checkout routing cannot be set to Active without a valid destination email address.";
    } elseif ($stripe_status === 'active' && (empty($stripe_key) || empty($stripe_secret))) {
        $error_msg = "Stripe infrastructure engine cannot be set to Active without filling in your platform integration keys.";
    } else {
        try {
            // Safe parametric persistence calls using your exact database mappings
            updatePaymentSetting($pdo, 'paypal_email', $paypal_email);
            updatePaymentSetting($pdo, 'paypal_status', $paypal_status);
            updatePaymentSetting($pdo, 'stripe_key', $stripe_key);
            updatePaymentSetting($pdo, 'stripe_secret', $stripe_secret);
            updatePaymentSetting($pdo, 'stripe_status', $stripe_status);

            $success_msg = "Global payment network rails synchronization updated successfully.";
        } catch (Exception $e) {
            $error_msg = "Database Sync Engine Interruption: " . $e->getMessage();
        }
    }
}

// Inject standard secure UI Header layout component
require_once __DIR__ . '/../sections/header.php';
?>

<div class="min-h-screen bg-nftDark text-white antialiased">
    
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-12 px-4 sm:px-6 lg:px-8 transition-all duration-300">
        <div class="max-w-4xl mx-auto space-y-8">
            
            <div class="flex items-center space-x-2 text-xs font-bold uppercase tracking-widest text-nftTextGray">
                <a href="dashboard.php" class="hover:text-nftAccentCyan transition-colors">Admin Hub</a>
                <span>/</span>
                <a href="settings.php" class="hover:text-nftAccentCyan transition-colors">System Settings</a>
                <span>/</span>
                <span class="text-emerald-400">Payment Gateways</span>
            </div>

            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-900 pb-6">
                <div>
                    <h1 class="text-3xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-emerald-400">Payment Engine Controls</h1>
                    <p class="text-sm text-nftTextGray mt-1">Configure global customer merchant routing layers, sandbox profiles, and transaction switches inside payment_settings rows.</p>
                </div>
            </div>

            <?php if (!empty($error_msg)): ?>
                <div class="p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs font-mono text-rose-400 flex items-center gap-2.5 shadow-md">
                    <i class="fa-solid fa-triangle-exclamation text-base"></i> <?php echo htmlspecialchars($error_msg); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success_msg)): ?>
                <div class="p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-xl text-xs font-medium text-emerald-400 flex items-center gap-2.5 shadow-md">
                    <i class="fa-solid fa-circle-check text-base"></i> <?php echo htmlspecialchars($success_msg); ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="" class="space-y-6">
                
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6 shadow-xl relative overflow-hidden">
                    <div class="flex items-center justify-between border-b border-slate-900 pb-4">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 rounded-lg bg-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-400 text-lg">
                                <i class="fa-brands fa-paypal"></i>
                            </div>
                            <div>
                                <h3 class="text-sm font-bold uppercase tracking-wider text-white">PayPal Merchant Module</h3>
                                <p class="text-[11px] text-nftTextGray">Receive client checkouts using PayPal smart merchant account structures.</p>
                            </div>
                        </div>

                        <div class="flex items-center space-x-2">
                            <select name="paypal_status" class="bg-slate-950 border border-slate-900 rounded-lg text-xs font-bold font-mono px-3 py-1.5 focus:outline-none focus:border-blue-400 text-slate-300">
                                <option value="active" <?php echo ($paypal_status === 'active') ? 'selected' : ''; ?>>ACTIVE</option>
                                <option value="inactive" <?php echo ($paypal_status === 'inactive') ? 'selected' : ''; ?>>INACTIVE</option>
                            </select>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Merchant Business Email Address Target</label>
                        <input type="email" name="paypal_email" value="<?php echo htmlspecialchars($paypal_email); ?>" class="w-full bg-slate-950 border border-slate-900 focus:border-blue-400 focus:outline-none rounded-xl px-4 py-3 text-xs font-mono transition-colors text-slate-200" placeholder="merchant-finance@yourdomain.com">
                        <span class="text-[10px] text-nftTextGray block leading-relaxed">All checkouts completed through standard application paths dispatch payments directly into this destination address.</span>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6 shadow-xl relative overflow-hidden">
                    <div class="flex items-center justify-between border-b border-slate-900 pb-4">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 rounded-lg bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center text-indigo-400 text-lg">
                                <i class="fa-brands fa-stripe-s"></i>
                            </div>
                            <div>
                                <h3 class="text-sm font-bold uppercase tracking-wider text-white">Stripe API Infrastructure Matrix</h3>
                                <p class="text-[11px] text-nftTextGray">Process immediate inline customer credit card transactions securely.</p>
                            </div>
                        </div>

                        <div class="flex items-center space-x-2">
                            <select name="stripe_status" class="bg-slate-950 border border-slate-900 rounded-lg text-xs font-bold font-mono px-3 py-1.5 focus:outline-none focus:border-indigo-400 text-slate-300">
                                <option value="active" <?php echo ($stripe_status === 'active') ? 'selected' : ''; ?>>ACTIVE</option>
                                <option value="inactive" <?php echo ($stripe_status === 'inactive') ? 'selected' : ''; ?>>INACTIVE</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 gap-4">
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Stripe Publishable Token Key (pk_live_... / pk_test_...)</label>
                            <input type="text" name="stripe_key" value="<?php echo htmlspecialchars($stripe_key); ?>" class="w-full bg-slate-950 border border-slate-900 focus:border-indigo-400 focus:outline-none rounded-xl px-4 py-3 text-xs font-mono transition-colors text-slate-200" placeholder="pk_live_51...">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Stripe Private Restricted Secret Token (sk_live_... / sk_test_...)</label>
                            <input type="password" name="stripe_secret" value="<?php echo htmlspecialchars($stripe_secret); ?>" class="w-full bg-slate-950 border border-slate-900 focus:border-indigo-400 focus:outline-none rounded-xl px-4 py-3 text-xs font-mono transition-colors text-slate-200" placeholder="••••••••••••••••••••••••••••••••">
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end space-x-4 pt-4 border-t border-slate-900">
                    <a href="settings.php" class="bg-slate-950 hover:bg-slate-900 border border-slate-900 text-slate-500 hover:text-white px-5 py-3 rounded-xl text-xs font-bold uppercase tracking-widest transition-colors">
                        Discard Changes
                    </a>
                    <button type="submit" class="bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-white px-6 py-3 rounded-xl text-xs font-bold uppercase tracking-widest transition-all shadow-md active:scale-[0.99]">
                        <i class="fa-solid fa-cloud-arrow-up mr-1.5"></i> Commit Configurations
                    </button>
                </div>

            </form>

        </div>
    </main>

</div>

<script>
    const navBarSidebar = document.getElementById('sidebar-nav-container');
    const overlayNavBackdrop = document.getElementById('sidebar-backdrop');
    
    if (navBarSidebar && overlayNavBackdrop) {
        const trackingConfigurationObserver = new MutationObserver(() => {
            if (!navBarSidebar.classList.contains('-translate-x-full')) {
                overlayNavBackdrop.classList.remove('hidden');
            } else {
                overlayNavBackdrop.classList.add('hidden');
            }
        });
        
        trackingConfigurationObserver.observe(navBarSidebar, { attributes: true, attributeFilter: ['class'] });
    }
</script>

</body>
</html>