<?php
/**
 * Agentic Square / Enfhess Marketplace - High Performance Seller Sales & Orders Dashboard
 * Path: seller/sales-orders.php
 */
require_once __DIR__ . '/../config/config.php';

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

$user_id = (int)($_SESSION['user_id'] ?? 0);
if ($user_id <= 0 || ($_SESSION['user_role'] ?? '') !== 'seller') {
    header("Location: ../login.php");
    exit();
}

// Fetch seller mapping
$stmtSeller = $pdo->prepare("SELECT user_id FROM sellers WHERE user_id = ? LIMIT 1");
$stmtSeller->execute([$user_id]);
$currentSeller = $stmtSeller->fetch(PDO::FETCH_ASSOC);
$seller_order_lookup_id = $currentSeller ? (int)$currentSeller['user_id'] : 0;

// Pagination
$recordsPerPage = 10;
$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($currentPage - 1) * $recordsPerPage;

$countQuery = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE seller_id = ? AND payment_status = 'Paid'");
$countQuery->execute([$seller_order_lookup_id]);
$totalRecords = (int)$countQuery->fetchColumn();
$totalPages = ceil($totalRecords / $recordsPerPage);

$ordersQuery = $pdo->prepare("SELECT o.*, i.feature_image FROM orders o LEFT JOIN items i ON o.item_id = i.id WHERE o.seller_id = ? AND o.payment_status = 'Paid' ORDER BY o.id DESC LIMIT ? OFFSET ?");
$ordersQuery->bindValue(1, $seller_order_lookup_id, PDO::PARAM_INT);
$ordersQuery->bindValue(2, $recordsPerPage, PDO::PARAM_INT);
$ordersQuery->bindValue(3, $offset, PDO::PARAM_INT);
$ordersQuery->execute();
$salesRecords = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);

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

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php require_once __DIR__ . '/seller-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-7xl mx-auto space-y-8">
            
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-900/60 pb-6">
                <div>
                    <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// SALES OPERATIONS</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Sales & Checkout Orders Ledger</h1>
                    <p class="text-sm text-nftTextGray mt-1">Real-time analytical interface tracking paid catalog node transactions.</p>
                </div>
            </div>

            <?php require_once __DIR__ . '/seller-sales-card.php'; ?>

            <div class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-900 text-[11px] font-bold text-nftTextGray uppercase tracking-widest bg-slate-950/40">
                                <th class="px-6 py-4 w-12">SL</th>
                                <th class="px-6 py-4">Date Logged</th>
                                <th class="px-6 py-4 w-20">Preview</th>
                                <th class="px-6 py-4">Product Asset Specification</th>
                                <th class="px-6 py-4">Price</th>
                                <th class="px-6 py-4">Commission</th>
                                <th class="px-6 py-4">Net Income</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/50 text-xs text-slate-300 font-medium">
                            <?php if (empty($salesRecords)): ?>
                                <tr><td colspan="7" class="text-center py-10 text-nftTextGray font-mono">No records found.</td></tr>
                            <?php else: 
                                $sl = $offset + 1;
                                foreach ($salesRecords as $order): 
                                    $imagePath = !empty($order['feature_image']) ? '../' . $order['feature_image'] : '../assets/img/placeholder.png';
                            ?>
                                <tr class="hover:bg-slate-900/20 transition-colors border-b border-slate-900/40">
                                    <td class="px-6 py-4 font-mono font-bold text-slate-500"><?php echo $sl++; ?></td>
                                    <td class="px-6 py-4 font-mono text-slate-400"><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                    <td class="px-6 py-4">
                                        <div class="w-12 h-10 rounded-lg bg-slate-950 border border-slate-900 overflow-hidden shadow-md">
                                            <img src="<?php echo htmlspecialchars($imagePath); ?>" class="w-full h-full object-cover">
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 font-bold text-white max-w-xs truncate"><?php echo htmlspecialchars($order['item_name']); ?></td>
                                    <td class="px-6 py-4 font-extrabold font-mono text-slate-300"><?php echo htmlspecialchars(format_currency($order['price']), ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td class="px-6 py-4 font-bold font-mono text-rose-400">
                                        <?php echo $order['commission_rate'] . ($order['commission_type'] == 'percentage' ? '%' : ''); ?>
                                    </td>
                                    <td class="px-6 py-4 font-black font-mono text-emerald-400"><?php echo htmlspecialchars(format_currency($order['net_seller_income']), ENT_QUOTES, 'UTF-8'); ?></td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
</body>
</html>
