<?php
/**
 * Agentic Square - Premium Admin Control Center: Intercept & Mutate Order Metrics Workflow
 * Path: admin/update-order.php
 */

require_once __DIR__ . '/../config/config.php';
ensure_transaction_fee_schema();

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;
}

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

// Form Submission Context Layer Pipeline Execution Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_commit']) && $_POST['action_commit'] === 'mutate_order_record') {
    $targetOrderId = (int)$_POST['order_id'];
    $customerName  = trim($_POST['customer_name']);
    $customerEmail = trim($_POST['customer_email']);
    $customerPhone = trim($_POST['customer_phone']);
    $priceValue    = floatval($_POST['price']);
    $transactionFeeRate = max(0.00, floatval($_POST['transaction_fee_rate'] ?? 0));
    $transactionFeeAmount = round(($priceValue * $transactionFeeRate) / 100, 2);
    $totalAmount = round($priceValue + $transactionFeeAmount, 2);
    $paymentStatus = trim($_POST['payment_status']);
    $paymentMethod = trim($_POST['payment_method']);

    try {
        $updateQuery = "
            UPDATE orders 
            SET 
                customer_name = ?, 
                customer_email = ?, 
	                customer_phone = ?, 
	                price = ?, 
	                transaction_fee_rate = ?,
	                transaction_fee_amount = ?,
	                total_amount = ?,
	                payment_status = ?,
                payment_method = ?
            WHERE id = ?
	        ";
	        $updateStmt = $pdo->prepare($updateQuery);
	        $updateStmt->execute([$customerName, $customerEmail, $customerPhone, $priceValue, $transactionFeeRate, $transactionFeeAmount, $totalAmount, $paymentStatus, $paymentMethod, $targetOrderId]);
        
        $notificationStatePayload = ['success' => true, 'message' => 'Ledger record tracking matrix mutated successfully!'];
    } catch (\PDOException $ex) {
        $notificationStatePayload = ['success' => false, 'message' => 'Pipeline Mutation Exception: ' . $ex->getMessage()];
    }
}

// Extract base operational variables mapping definitions
try {
    $orderQuery = "
        SELECT o.*, s.seller_name 
        FROM orders o
        LEFT JOIN sellers s ON o.seller_id = s.id
        WHERE o.id = ?
    ";
    $orderStmt = $pdo->prepare($orderQuery);
    $orderStmt->execute([$order_id]);
    $orderRecord = $orderStmt->fetch(PDO::FETCH_ASSOC);

    if (!$orderRecord) {
        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-orders.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 Ledger Directory
                    </a>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Modify Order Settlement</h1>
                    <p class="text-sm text-nftTextGray mt-1">Order Index Reference Core Handle: <span class="font-mono text-white">#AS-ORD-<?php echo str_pad($orderRecord['id'], 6, '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 overflow-hidden">
                <form method="POST" action="update-order.php?id=<?php echo $order_id; ?>" class="space-y-6">
                    <input type="hidden" name="order_id" value="<?php echo $orderRecord['id']; ?>">
                    <input type="hidden" name="action_commit" value="mutate_order_record">

                    <div class="p-4 rounded-xl bg-slate-950 border border-slate-900 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <span class="text-[10px] font-bold text-nftTextGray uppercase block tracking-wider">Asset Product Destination</span>
                            <span class="text-sm font-bold text-white block mt-0.5"><?php echo htmlspecialchars($orderRecord['item_name']); ?></span>
                            <span class="text-[10px] font-mono text-slate-500 block">Item Link ID Mapping: #<?php echo $orderRecord['item_id']; ?></span>
                        </div>
                        <div>
                            <span class="text-[10px] font-bold text-nftTextGray uppercase block tracking-wider">Origin Vendor Account</span>
                            <span class="text-sm font-bold text-nftAccentCyan block mt-0.5"><?php echo htmlspecialchars($orderRecord['seller_name'] ?? 'System Core Platform'); ?></span>
                        </div>
                    </div>

	                    <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">Customer Full Name</label>
                            <input type="text" name="customer_name" required value="<?php echo htmlspecialchars($orderRecord['customer_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">Customer Corporate Email</label>
                            <input type="email" name="customer_email" required value="<?php echo htmlspecialchars($orderRecord['customer_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="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">Customer Telephone Contact</label>
                            <input type="text" name="customer_phone" value="<?php echo htmlspecialchars($orderRecord['customer_phone'] ?? ''); ?>" 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">Settled Gross License Value ($)</label>
	                            <input type="number" step="0.01" name="price" required value="<?php echo htmlspecialchars($orderRecord['price']); ?>" class="w-full bg-slate-950 text-xs text-emerald-400 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-mono font-bold transition-colors">
	                        </div>
	                    </div>

	                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
	                        <div class="space-y-2">
	                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Transaction Fee Rate (%)</label>
	                            <input type="number" step="0.01" min="0" name="transaction_fee_rate" value="<?php echo htmlspecialchars($orderRecord['transaction_fee_rate'] ?? '0.00'); ?>" class="w-full bg-slate-950 text-xs text-amber-300 p-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan font-mono font-bold transition-colors">
	                        </div>
	                        <div class="space-y-2">
	                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Transaction Fee Amount ($)</label>
	                            <input type="number" step="0.01" readonly value="<?php echo htmlspecialchars($orderRecord['transaction_fee_amount'] ?? '0.00'); ?>" class="w-full bg-slate-950/60 text-xs text-amber-300 p-3.5 rounded-xl border border-slate-900 font-mono font-bold cursor-not-allowed">
	                        </div>
	                        <div class="space-y-2">
	                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Total Paid / Payable ($)</label>
	                            <input type="number" step="0.01" readonly value="<?php echo htmlspecialchars(!empty($orderRecord['total_amount']) ? $orderRecord['total_amount'] : $orderRecord['price']); ?>" class="w-full bg-slate-950/60 text-xs text-emerald-400 p-3.5 rounded-xl border border-slate-900 font-mono font-bold cursor-not-allowed">
	                        </div>
	                    </div>

                    <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">Payment Validation Channel Method</label>
                            <input type="text" name="payment_method" value="<?php echo htmlspecialchars($orderRecord['payment_method'] ?? 'Stripe API Gateway'); ?>" 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" placeholder="e.g. Crypto, Credit Card, PayPal">
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-bold text-nftTextGray uppercase tracking-wider block">Settlement Payment Operational Status</label>
                            <select name="payment_status" 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-bold transition-colors cursor-pointer">
                                <option value="Paid" <?php echo ($orderRecord['payment_status'] === 'Paid') ? 'selected' : ''; ?>>PAID — Settlement Verified Clear</option>
                                <option value="Pending" <?php echo ($orderRecord['payment_status'] === 'Pending') ? 'selected' : ''; ?>>PENDING — Review Queue Locked</option>
                                <option value="Failed" <?php echo ($orderRecord['payment_status'] === 'Failed') ? 'selected' : ''; ?>>FAILED — Transaction Settlement Fault</option>
                            </select>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-4 pt-4 border-t border-slate-900/40">
                        <a href="all-orders.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">Abort Alterations</a>
                        <button type="submit" id="updateOrderBtnSubmit" 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">
                            Commit Entry Adjustments
                        </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() {
        // Evaluate payload arrays parameters passed back across native post operational state pipelines
        <?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>
