<?php
/**
 * Agentic Square - Premium Admin Control Center: Intercept & Mutate Vendor Metadata
 * Path: admin/update-seller.php
 */

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$seller_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$notificationStatePayload = null;

// Form Submission Database Layer Interception Execution Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_commit']) && $_POST['action_commit'] === 'mutate_seller_record') {
    $targetSellerId = (int)$_POST['seller_id'];
    $sellerName     = trim($_POST['seller_name']);
    $sellerEmail    = trim($_POST['email']);
    $addressVal     = trim($_POST['address']);
    $cityVal        = trim($_POST['city']);
    $countryVal     = trim($_POST['country']);
    $balanceVal     = floatval($_POST['current_balance']);
    $aboutVal       = trim($_POST['about']);

    try {
        $updateQuery = "
            UPDATE sellers 
            SET 
                seller_name = ?, 
                email = ?, 
                address = ?, 
                city = ?, 
                country = ?, 
                current_balance = ?, 
                about = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ";
        $updateStmt = $pdo->prepare($updateQuery);
        $updateStmt->execute([$sellerName, $sellerEmail, $addressVal, $cityVal, $countryVal, $balanceVal, $aboutVal, $targetSellerId]);
        
        $notificationStatePayload = ['success' => true, 'message' => 'Merchant parameters and financial ledger updated successfully!'];
    } catch (\PDOException $ex) {
        $notificationStatePayload = ['success' => false, 'message' => 'Database Mutation Exception: ' . $ex->getMessage()];
    }
}

// Extract base vendor configurations tracking values
try {
    $sellerQuery = "SELECT * FROM sellers WHERE id = ?";
    $sellerStmt = $pdo->prepare($sellerQuery);
    $sellerStmt->execute([$seller_id]);
    $sellerRecord = $sellerStmt->fetch(PDO::FETCH_ASSOC);

    if (!$sellerRecord) {
        die('System Fault Context: Requested target entry key sequence maps empty.');
    }
} catch (\PDOException $e) {
    die('Database pipeline exception context trace code failure: ' . $e->getMessage());
}

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">

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

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-3xl mx-auto space-y-8">
            
            <div class="flex items-center justify-between border-b border-slate-900/60 pb-6">
                <div>
                    <a href="all-sellers.php" class="text-xs font-bold uppercase tracking-wider text-nftAccentCyan hover:underline inline-flex items-center gap-1.5 mb-2">
                        <i class="fa-solid fa-arrow-left text-[10px]"></i> Return To Merchant Directory
                    </a>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Modify Merchant Account</h1>
                    <p class="text-sm text-nftTextGray mt-1">Merchant Index Tracking Reference: <span class="font-mono text-white">#AS-SEL-<?php echo str_pad($sellerRecord['id'], 5, '0', STR_PAD_LEFT); ?></span></p>
                </div>
            </div>

            <div class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20 relative">
                <form method="POST" action="update-seller.php?id=<?php echo $seller_id; ?>" class="space-y-6">
                    <input type="hidden" name="seller_id" value="<?php echo $sellerRecord['id']; ?>">
                    <input type="hidden" name="action_commit" value="mutate_seller_record">

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Merchant Brand/Public Name</label>
                            <input type="text" name="seller_name" required value="<?php echo htmlspecialchars($sellerRecord['seller_name']); ?>" class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-medium transition-colors">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Merchant Login/Contact Email</label>
                            <input type="email" name="email" required value="<?php echo htmlspecialchars($sellerRecord['email']); ?>" class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-mono font-medium transition-colors">
                        </div>
                    </div>

                    <div class="p-4 rounded-xl bg-slate-950 border border-slate-900 space-y-2">
                        <label class="text-xs font-bold text-nftAccentPurple uppercase tracking-wider block">Withdrawable Payout Ledger Balance ($)</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-4 font-mono text-xs text-slate-500 font-bold">$</span>
                            <input type="number" step="0.01" name="current_balance" required value="<?php echo htmlspecialchars($sellerRecord['current_balance']); ?>" class="w-full bg-slate-900 text-sm text-emerald-400 pl-8 p-3.5 rounded-xl border border-slate-800 focus:outline-none focus:border-nftAccentCyan font-mono font-extrabold transition-colors">
                        </div>
                        <span class="text-[10px] text-slate-500 block">Modifying this parameter overrides the merchant's live balance ledger tracking variables. Use caution.</span>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Street Address</label>
                            <input type="text" name="address" value="<?php echo htmlspecialchars($sellerRecord['address'] ?? ''); ?>" class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-medium transition-colors">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">City/Region</label>
                            <input type="text" name="city" value="<?php echo htmlspecialchars($sellerRecord['city'] ?? ''); ?>" class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-medium transition-colors">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Country Jurisdiction</label>
                            <input type="text" name="country" value="<?php echo htmlspecialchars($sellerRecord['country'] ?? ''); ?>" class="w-full bg-slate-950 text-xs text-slate-200 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-medium transition-colors">
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">About Description / Merchant Narrative Profile</label>
                        <textarea name="about" rows="4" class="w-full bg-slate-950 text-xs text-slate-300 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-colors resize-none leading-relaxed"><?php echo htmlspecialchars($sellerRecord['about'] ?? ''); ?></textarea>
                    </div>

                    <div class="flex items-center justify-end gap-4 pt-4 border-t border-slate-900/40">
                        <a href="all-sellers.php" class="px-5 py-3 rounded-xl text-xs font-bold uppercase tracking-wider text-slate-400 bg-slate-950 border border-slate-900 hover:text-white transition-all">Cancel Changes</a>
                        <button type="submit" class="px-6 py-3 rounded-xl text-xs font-bold uppercase tracking-wider text-slate-950 bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple shadow-lg hover:opacity-90 font-black transition-all">
                            Save Vendor Matrix Parameters
                        </button>
                    </div>
                </form>
            </div>

        </div>
    </main>

    <div id="portalToastNotification" class="fixed top-5 right-5 z-[10000] hidden transform translate-y-[-20px] opacity-0 transition-all duration-300 flex items-center p-4 w-full max-w-xs text-slate-300 bg-slate-900 border rounded-xl shadow-2xl" role="alert">
        <div id="toastIconContainer" class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg"></div>
        <div id="toastContentMessage" class="ms-3 text-xs font-bold tracking-wide"></div>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        <?php if ($notificationStatePayload): ?>
            const msg = <?php echo json_encode($notificationStatePayload['message']); ?>;
            const statusType = <?php echo $notificationStatePayload['success'] ? "'success'" : "'error'"; ?>;
            
            const toastElement = document.getElementById('portalToastNotification');
            const toastIcon = document.getElementById('toastIconContainer');
            const toastMsg = document.getElementById('toastContentMessage');

            toastMsg.textContent = msg;
            if (statusType === 'success') {
                toastElement.style.borderColor = 'rgba(16, 185, 129, 0.3)';
                toastIcon.style.backgroundColor = 'rgba(16, 185, 129, 0.1)';
                toastIcon.style.color = '#10b981';
                toastIcon.innerHTML = '&#x2713;'; 
            } else {
                toastElement.style.borderColor = 'rgba(239, 68, 68, 0.3)';
                toastIcon.style.backgroundColor = 'rgba(239, 68, 68, 0.1)';
                toastIcon.style.color = '#ef4444';
                toastIcon.innerHTML = '&#x26A0;';
            }

            toastElement.classList.remove('hidden');
            setTimeout(() => {
                toastElement.style.opacity = '1';
                toastElement.style.transform = 'translateY(0)';
            }, 10);

            setTimeout(() => {
                toastElement.style.opacity = '0';
                toastElement.style.transform = 'translateY(-20px)';
                setTimeout(() => { toastElement.classList.add('hidden'); }, 300);
            }, 4000);
        <?php endif; ?>
    });
    </script>
</body>
</html>