<?php
// sell.php - Seller Dashboard & Product Upload Form
require_once 'db_connect.php';

// RBAC: Require login first
if (!isLoggedIn()) {
    header("Location: login.php?redirect=sell.php&error=" . urlencode("Please log in to access the Seller Dashboard."));
    exit();
}

$user = getLoggedInUser();

// RBAC: Only seller and admin can access this page
if (!canSell()) {
    // Buyer sees an upgrade prompt instead of a hard redirect
    renderHeader(__('sell_become_title'));
    ?>
    <div class="max-w-2xl mx-auto my-16 text-center px-4">
        <div class="bg-white rounded-3xl shadow-xl border border-gray-100 p-10 sm:p-14 relative overflow-hidden">
            <!-- Decorative gradient blob -->
            <div class="absolute -top-20 -right-20 w-64 h-64 bg-gradient-to-br from-orange-100 to-rose-100 rounded-full opacity-60 blur-3xl pointer-events-none"></div>
            <div class="absolute -bottom-20 -left-20 w-64 h-64 bg-gradient-to-tr from-emerald-100 to-cyan-100 rounded-full opacity-60 blur-3xl pointer-events-none"></div>

            <div class="relative z-10">
                <div class="w-16 h-16 bg-orange-50 text-orange-600 rounded-2xl flex items-center justify-center mx-auto mb-5 border border-orange-100">
                    <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>
                </div>
                <h1 class="text-3xl font-extrabold text-gray-900 tracking-tight mb-3"><?php echo __('sell_upgrade_heading'); ?></h1>
                <p class="text-gray-500 text-sm leading-relaxed mb-8 max-w-md mx-auto">
                    <?php echo __('sell_upgrade_desc'); ?>
                </p>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8 text-left">
                    <div class="bg-orange-50 rounded-2xl p-4">
                        <svg class="w-6 h-6 text-orange-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>
                        <h3 class="font-bold text-gray-900 text-sm"><?php echo __('sell_feat_list'); ?></h3>
                        <p class="text-xs text-gray-500 mt-1"><?php echo __('sell_feat_list_desc'); ?></p>
                    </div>
                    <div class="bg-emerald-50 rounded-2xl p-4">
                        <svg class="w-6 h-6 text-emerald-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        <h3 class="font-bold text-gray-900 text-sm"><?php echo __('sell_feat_earn'); ?></h3>
                        <p class="text-xs text-gray-500 mt-1"><?php echo __('sell_feat_earn_desc'); ?></p>
                    </div>
                    <div class="bg-blue-50 rounded-2xl p-4">
                        <svg class="w-6 h-6 text-blue-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                        <h3 class="font-bold text-gray-900 text-sm"><?php echo __('sell_feat_dash'); ?></h3>
                        <p class="text-xs text-gray-500 mt-1"><?php echo __('sell_feat_dash_desc'); ?></p>
                    </div>
                </div>

                <a href="upgrade_to_seller.php" 
                   class="inline-flex items-center gap-2 px-8 py-3.5 bg-gradient-to-r from-orange-500 to-rose-500 text-white font-bold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-200 hover:-translate-y-0.5 text-sm">
                    <?php echo __('sell_upgrade_btn'); ?>
                </a>
                <p class="text-xs text-gray-400 mt-4"><?php echo __('sell_instant'); ?></p>
            </div>
        </div>
    </div>
    <?php
    renderFooter();
    exit();
}
$errorMsg = "";
$successMsg = "";

$action = $_GET['action'] ?? '';
$editProduct = null;

// Handle Edit Mode pre-fill
if ($action === 'edit' && isset($_GET['id'])) {
    $editId = intval($_GET['id']);
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND seller_id = ?");
    $stmt->execute([$editId, $user['id']]);
    $editProduct = $stmt->fetch();
}

// Handle Form Submissions (Create or Update Product)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $prodId = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $category = trim($_POST['category'] ?? 'Electronics');
        $price = floatval($_POST['price'] ?? 0);
        $stock = intval($_POST['stock'] ?? 0);
        $sizes = trim($_POST['sizes'] ?? '');
        $colors = trim($_POST['colors'] ?? '');

        $bannedFound = checkProhibitedKeywords($title, $description);

        if (!empty($bannedFound)) {
            $errorMsg = "Listing rejected! Contains prohibited terms: (" . implode(', ', $bannedFound) . "). Items involving weapons, narcotics, gambling, or counterfeit documents are strictly forbidden.";
        } elseif (empty($title) || empty($description) || $price <= 0 || $stock < 0) {
            $errorMsg = "Title, description, valid price, and stock are required.";
        } elseif (empty($category)) {
            $errorMsg = "Please select or specify a category.";
        } else {
            // Handle product images upload
            $uploadedImages = [];
            
            // Check if it's an update and load existing images
            if ($prodId > 0) {
                $checkStmt = $pdo->prepare("SELECT images FROM products WHERE id = ? AND seller_id = ?");
                $checkStmt->execute([$prodId, $user['id']]);
                $existing = $checkStmt->fetch();
                if ($existing) {
                    $uploadedImages = json_decode($existing['images'], true) ?: [];
                }
            }

            if (isset($_FILES['images']) && $_FILES['images']['name'] !== '') {
                if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
                    $tmpName = $_FILES['images']['tmp_name'];
                    $name = $_FILES['images']['name'];
                    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
                        $uploadDir = 'uploads/';
                        if (!is_dir($uploadDir)) {
                            if (!@mkdir($uploadDir, 0777, true)) {
                                $errorMsg = "Failed to create 'uploads' directory. Please create it manually on the server via FileZilla and set permissions to 777 or 755.";
                            }
                        }
                        if (empty($errorMsg)) {
                            $newName = 'prod_' . time() . '.' . $ext;
                            if (move_uploaded_file($tmpName, $uploadDir . $newName)) {
                                $uploadedImages = ['/uploads/' . $newName]; // replace/set as main image
                            } else {
                                $errorMsg = "Failed to upload image. Please check the permissions of the 'uploads' folder (set to 777 or 755 via FileZilla).";
                            }
                        }
                    } else {
                        $errorMsg = "Only JPG, PNG, and WEBP images are allowed.";
                    }
                } else {
                    $uploadError = $_FILES['images']['error'];
                    switch ($uploadError) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $errorMsg = "The uploaded image file size is too large. Please upload a smaller image.";
                            break;
                        case UPLOAD_ERR_PARTIAL:
                            $errorMsg = "The image file was only partially uploaded.";
                            break;
                        case UPLOAD_ERR_NO_TMP_DIR:
                            $errorMsg = "Missing a temporary folder on the server. Please check your PHP settings.";
                            break;
                        case UPLOAD_ERR_CANT_WRITE:
                            $errorMsg = "Failed to write image file to disk. Check server disk space or folder permissions.";
                            break;
                        default:
                            $errorMsg = "File upload failed with error code: " . $uploadError;
                            break;
                    }
                }
            }

            if (empty($uploadedImages) && $prodId === 0) {
                $uploadedImages[] = '/uploads/placeholder-product.jpg'; // fallback
            }

            if (empty($errorMsg)) {
                $imagesJson = json_encode($uploadedImages);

                if ($prodId > 0) {
                    // Update — set status to pending if seller modified listing details
                    $newStatus = ($user['role'] === 'admin') ? 'approved' : 'pending';
                    $stmt = $pdo->prepare("
                        UPDATE products 
                        SET title = ?, description = ?, price = ?, stock = ?, category = ?, images = ?, sizes = ?, colors = ?, status = ?
                        WHERE id = ? AND seller_id = ?
                    ");
                    try {
                        $stmt->execute([$title, $description, $price, $stock, $category, $imagesJson, $sizes, $colors, $newStatus, $prodId, $user['id']]);
                        $msg = ($newStatus === 'pending') ? "Listing updated and submitted for Admin review." : "Product listing updated successfully!";
                        header("Location: sell.php?success=" . urlencode($msg));
                        exit();
                    } catch (PDOException $e) {
                        $errorMsg = "Failed to update listing: " . $e->getMessage();
                    }
                } else {
                    // Create — default status is 'pending' for regular sellers, 'approved' for admins
                    $initialStatus = ($user['role'] === 'admin') ? 'approved' : 'pending';
                    $stmt = $pdo->prepare("
                        INSERT INTO products (seller_id, title, description, price, stock, category, images, sizes, colors, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    try {
                        $stmt->execute([$user['id'], $title, $description, $price, $stock, $category, $imagesJson, $sizes, $colors, $initialStatus]);
                        $msg = ($initialStatus === 'pending') ? "Product submitted for Admin review. It will be published once approved." : "Product listed successfully!";
                        header("Location: sell.php?success=" . urlencode($msg));
                        exit();
                    } catch (PDOException $e) {
                        $errorMsg = "Failed to list item: " . $e->getMessage();
                    }
                }
            }
        }
    }
}

// Handle Delete Action
if ($action === 'delete' && isset($_GET['id'])) {
    $delId = intval($_GET['id']);
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ? AND seller_id = ?");
    $stmt->execute([$delId, $user['id']]);
    header("Location: sell.php?success=" . urlencode("Listing deleted successfully."));
    exit();
}

// Fetch listed products owned by user
$stmt = $pdo->prepare("SELECT * FROM products WHERE seller_id = ? ORDER BY created_at DESC");
$stmt->execute([$user['id']]);
$myProducts = $stmt->fetchAll();

// Calculate total earnings
$earningsStmt = $pdo->prepare("
    SELECT SUM(oi.quantity * oi.price) as total 
    FROM order_items oi
    JOIN products p ON oi.product_id = p.id
    JOIN orders o ON oi.order_id = o.id
    WHERE p.seller_id = ? AND o.status != 'Cancelled'
");
$earningsStmt->execute([$user['id']]);
$earnings = $earningsStmt->fetch()['total'] ?? 0.00;

// Fetch sales orders for seller items
$ordersStmt = $pdo->prepare("
    SELECT DISTINCT o.*, u.username as buyer_name 
    FROM orders o
    JOIN order_items oi ON o.id = oi.order_id
    JOIN products p ON oi.product_id = p.id
    JOIN users u ON o.buyer_id = u.id
    WHERE p.seller_id = ?
    ORDER BY o.created_at DESC
");
$ordersStmt->execute([$user['id']]);
$salesOrders = $ordersStmt->fetchAll();

// Add items belonging specifically to this seller inside the orders
foreach ($salesOrders as &$sOrd) {
    $itemsStmt = $pdo->prepare("
        SELECT oi.*, p.title 
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE oi.order_id = ? AND p.seller_id = ?
    ");
    $itemsStmt->execute([$sOrd['id'], $user['id']]);
    $sOrd['my_items'] = $itemsStmt->fetchAll();
}

renderHeader(__('sell_page_title'));
?>

<!-- Quick Mode Switch Header Banner -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between bg-white p-4 sm:p-5 rounded-2xl border border-gray-100 shadow-sm mb-8 gap-4">
    <div class="flex items-center gap-3">
        <div class="w-10 h-10 bg-orange-50 text-orange-600 rounded-xl flex items-center justify-center flex-shrink-0 border border-orange-100">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>
        </div>
        <div>
            <h1 class="font-extrabold text-gray-900 text-lg sm:text-xl"><?php echo __('sell_page_title'); ?></h1>
            <p class="text-xs text-gray-500"><?php echo __('nav_hello'); ?> <strong class="text-gray-900"><?php echo sanitize($user['username']); ?></strong> — <?php echo __('role_seller_label'); ?></p>
        </div>
    </div>
    <a href="index.php?action=switch_role&to=buyer" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold text-xs rounded-xl transition-all shadow-sm flex items-center gap-1.5 self-start sm:self-auto border border-gray-200">
        <svg class="w-3.5 h-3.5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
        <span><?php echo __('nav_switch_to_buyer'); ?></span>
    </a>
</div>

<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
    
    <!-- Left panel: upload form -->
    <div class="lg:col-span-5 bg-white p-6 sm:p-8 rounded-3xl border border-gray-100 shadow-sm space-y-6">
        <h2 class="text-xl font-bold text-gray-900 pb-3 border-b border-gray-100">
            <?php echo $editProduct ? __('sell_form_edit') : __('sell_form_new'); ?>
        </h2>

        <?php if (!empty($errorMsg)): ?>
            <div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-xl text-sm font-semibold flex items-center gap-2">
                <svg class="w-4 h-4 text-red-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                <span><?php echo sanitize($errorMsg); ?></span>
            </div>
        <?php endif; ?>

        <form action="sell.php?action=save" method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="product_id" value="<?php echo $editProduct ? $editProduct['id'] : '0'; ?>">

            <div>
                <label for="title" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_title'); ?></label>
                <input type="text" name="title" id="title" required placeholder="<?php echo __('sell_ph_title'); ?>" value="<?php echo $editProduct ? sanitize($editProduct['title']) : ''; ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 transition-all">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label for="price" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_price'); ?></label>
                    <input type="number" step="0.01" min="0.01" name="price" id="price" required placeholder="99.99" value="<?php echo $editProduct ? sanitize($editProduct['price']) : ''; ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 transition-all">
                </div>
                <div>
                    <label for="stock" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_stock'); ?></label>
                    <input type="number" min="0" name="stock" id="stock" required placeholder="50" value="<?php echo $editProduct ? sanitize($editProduct['stock']) : ''; ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 transition-all">
                </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label for="category" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_category'); ?></label>
                    <select name="category" id="category" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white transition-all">
                        <?php 
                        $cats = ['Electronics', 'Gadgets', 'Home & Living', 'Fashion', 'Beauty & Health', 'Sports & Outdoors', 'Food & Beverages', 'Books & Stationery', 'Toys & Hobbies', 'Other'];
                        foreach ($cats as $c):
                            $sel = ($editProduct && $editProduct['category'] === $c) ? 'selected' : '';
                        ?>
                            <option value="<?php echo $c; ?>" <?php echo $sel; ?>><?php echo $c; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="images" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_image'); ?></label>
                    <input type="file" name="images" id="images" class="w-full p-2 text-xs">
                </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label for="sizes" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_sizes'); ?></label>
                    <input type="text" name="sizes" id="sizes" placeholder="<?php echo __('sell_ph_sizes'); ?>" value="<?php echo $editProduct ? sanitize($editProduct['sizes']) : ''; ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white transition-all">
                </div>
                <div>
                    <label for="colors" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_colors'); ?></label>
                    <input type="text" name="colors" id="colors" placeholder="<?php echo __('sell_ph_colors'); ?>" value="<?php echo $editProduct ? sanitize($editProduct['colors']) : ''; ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white transition-all">
                </div>
            </div>

            <div>
                <label for="description" class="block text-xs font-bold uppercase tracking-wider text-gray-500 mb-1.5"><?php echo __('sell_label_desc'); ?></label>
                <textarea name="description" id="description" rows="3" required placeholder="<?php echo __('sell_ph_desc'); ?>" class="w-full p-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:bg-white transition-all"><?php echo $editProduct ? sanitize($editProduct['description']) : ''; ?></textarea>
            </div>

            <button type="submit" class="w-full py-3 bg-gradient-to-r from-orange-500 to-rose-500 text-white font-bold rounded-xl shadow hover:shadow-lg transition-all focus:outline-none text-sm">
                <?php echo $editProduct ? __('sell_btn_update') : __('sell_btn_list'); ?>
            </button>
            <?php if ($editProduct): ?>
                <a href="sell.php" class="block text-center py-2 bg-gray-100 text-gray-600 rounded-xl font-bold text-xs hover:bg-gray-200 transition-colors"><?php echo __('sell_btn_cancel'); ?></a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Right panel: stats, products listed, incoming orders -->
    <div class="lg:col-span-7 space-y-6">
        
        <!-- Stats counters -->
        <div class="grid grid-cols-3 gap-4">
            <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('sell_earnings'); ?></span>
                <span class="text-xl sm:text-2xl font-black text-rose-600 block mt-1">$<?php echo number_format($earnings, 2); ?></span>
            </div>
            <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('sell_active_listings'); ?></span>
                <span class="text-xl sm:text-2xl font-black text-gray-900 block mt-1"><?php echo count($myProducts); ?></span>
            </div>
            <div class="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wider block"><?php echo __('sell_total_orders'); ?></span>
                <span class="text-xl sm:text-2xl font-black text-gray-900 block mt-1"><?php echo count($salesOrders); ?></span>
            </div>
        </div>

        <!-- Products List grid -->
        <div class="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-4">
            <h3 class="font-bold text-gray-900 text-lg border-b border-gray-100 pb-3"><?php echo __('sell_my_listings'); ?></h3>
            
            <?php if (empty($myProducts)): ?>
                <p class="text-xs text-gray-400 py-6 text-center"><?php echo __('sell_no_products'); ?></p>
            <?php else: ?>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <?php foreach ($myProducts as $prod): 
                        $price = floatval($prod['price']);
                        $img = getProductImgUrl($prod['id'], $prod['images']);
                        $st = $prod['status'] ?? 'approved';
                        if ($st === 'approved') {
                            $stBadge = '<span class="px-1.5 py-0.5 text-[9px] font-black uppercase text-emerald-700 bg-emerald-100 rounded">' . __('sell_status_approved') . '</span>';
                        } elseif ($st === 'pending') {
                            $stBadge = '<span class="px-1.5 py-0.5 text-[9px] font-black uppercase text-amber-700 bg-amber-100 rounded">' . __('sell_status_pending') . '</span>';
                        } else {
                            $stBadge = '<span class="px-1.5 py-0.5 text-[9px] font-black uppercase text-red-700 bg-red-100 rounded">' . __('sell_status_rejected') . '</span>';
                        }
                    ?>
                        <div class="flex gap-3 p-3 border border-gray-50 bg-gray-50/20 rounded-xl relative">
                            <img src="<?php echo $img; ?>" class="w-14 h-14 rounded-lg object-cover border" onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1483985988355-763728e1935b?w=100';">
                            <div class="flex-grow min-w-0 space-y-0.5">
                                <div class="flex items-center justify-between gap-1">
                                    <h4 class="font-bold text-gray-900 text-xs truncate"><?php echo sanitize($prod['title']); ?></h4>
                                    <?php echo $stBadge; ?>
                                </div>
                                <div class="flex items-center justify-between text-xs">
                                    <span class="font-black text-rose-600">$<?php echo number_format($price, 2); ?></span>
                                    <span class="text-[10px] text-gray-400"><?php echo __('stock_label'); ?> <?php echo $prod['stock']; ?></span>
                                </div>
                                <div class="flex gap-3 text-[10px] font-bold pt-1">
                                    <a href="sell.php?action=edit&id=<?php echo $prod['id']; ?>" class="text-orange-500 hover:underline"><?php echo __('sell_edit_btn'); ?></a>
                                    <a href="sell.php?action=delete&id=<?php echo $prod['id']; ?>" onclick="return confirm('<?php echo addslashes(__('sell_delete_confirm')); ?>')" class="text-red-500 hover:underline"><?php echo __('sell_delete_btn'); ?></a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Sales Order lists -->
        <div class="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm space-y-4">
            <h3 class="font-bold text-gray-900 text-lg border-b border-gray-100 pb-3"><?php echo __('sell_orders_title'); ?></h3>

            <?php if (empty($salesOrders)): ?>
                <p class="text-xs text-gray-400 py-6 text-center"><?php echo __('sell_no_orders'); ?></p>
            <?php else: ?>
                <div class="space-y-4 max-h-[300px] overflow-y-auto pr-2 divide-y divide-gray-100">
                    <?php foreach ($salesOrders as $sOrd): ?>
                        <div class="pt-4 first:pt-0 space-y-1.5 text-xs">
                            <div class="flex justify-between font-semibold text-gray-500">
                                <span><?php echo __('sell_order_id'); ?>: TV-<?php echo $sOrd['id']; ?></span>
                                <span><?php echo __('sell_order_buyer'); ?>: <strong class="text-gray-700"><?php echo sanitize($sOrd['buyer_name']); ?></strong></span>
                            </div>
                            <!-- Items ordered -->
                            <div class="bg-gray-50 p-2.5 rounded-lg space-y-1">
                                <?php foreach ($sOrd['my_items'] as $item): ?>
                                    <div class="flex justify-between font-bold text-gray-800">
                                        <span><?php echo sanitize($item['title']); ?> (Size: <?php echo $item['size']; ?>, Color: <?php echo $item['color']; ?>) x<?php echo $item['quantity']; ?></span>
                                        <span>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="flex justify-between text-[10px] text-gray-400">
                                <span>Fulfillment: <strong class="text-orange-500 uppercase"><?php echo $sOrd['status']; ?></strong></span>
                                <span>Shipping to: <?php echo sanitize($sOrd['shipping_address']); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

    </div>

</div>

<?php
renderFooter();
?>
