<?php
require_once __DIR__ . '/../config/db.php';

// Secure Admin Defenses: Only authorized roles allowed
$user = getLoggedInUser();
if (!$user || !in_array($user['role'], ['Admin', 'Sub Admin', 'Manager', 'Officer'])) {
    http_response_code(403);
    echo "<!DOCTYPE html>
    <html lang='en'>
    <body style='background:#0f172a;color:#f1f5f9;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;'>
        <div style='text-align:center;border:1px solid #334155;padding:30px;border-radius:12px;background:#020617;max-width:400px;'>
            <h2 style='color:#ef4444;'>🚫 Access Restricted</h2>
            <p style='font-size:13px;color:#94a3b8;line-height:1.6;'>This administrative node is highly guarded. Your current session does not possess root Admin or Sub-Admin clearance credentials.</p>
            <a href='/auth/login.php' style='background:#4f46e5;color:white;padding:10px 20px;border-radius:6px;text-decoration:none;font-size:12px;font-weight:bold;display:inline-block;margin-top:15px;'>Go to Login</a>
        </div>
    </body>
    </html>";
    exit();
}

$db = Database::getConnection();
$error = null;
$success = null;

// 2. Process Shipment, Payment, and Production status updates from the View Modal
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action_proceed_production'])) {
        $orderId = $_POST['order_id'] ?? '';
        $orderType = $_POST['order_type'] ?? '';

        if (!empty($orderId) && in_array($orderType, ['sourcing', 'capacity'])) {
            $table = ($orderType === 'sourcing') ? 'sourcing_orders' : 'capacity_posts';
            try {
                $upd = $db->prepare("UPDATE $table SET production_status = 'In Production' WHERE id = ?");
                $upd->execute([$orderId]);

                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'message' => 'Production stage updated to In Production!']);
                    exit();
                }
                $success = "Production stage dispatched! Status updated to 'In Production'.";
            } catch (Exception $e) {
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
                    exit();
                }
                $error = "Failed to update production status: " . $e->getMessage();
            }
        }
    } elseif (isset($_POST['action_update_status'])) {
        $orderId = $_POST['order_id'] ?? '';
        $orderType = $_POST['order_type'] ?? '';
        $field = $_POST['field'] ?? '';

        if (!empty($orderId) && in_array($orderType, ['sourcing', 'capacity']) && in_array($field, ['shipment', 'payment'])) {
            $table = ($orderType === 'sourcing') ? 'sourcing_orders' : 'capacity_posts';
            $statusField = ($field === 'shipment') ? 'shipment_status' : 'payment_status';

            try {
                // Update selected status column to 'Completed'
                $upd = $db->prepare("UPDATE $table SET $statusField = 'Completed' WHERE id = ?");
                $upd->execute([$orderId]);

                // Check if BOTH are now 'Completed'
                $check = $db->prepare("SELECT shipment_status, payment_status, completed_at FROM $table WHERE id = ?");
                $check->execute([$orderId]);
                $res = $check->fetch();

                if ($res && $res['shipment_status'] === 'Completed' && $res['payment_status'] === 'Completed') {
                    if (empty($res['completed_at'])) {
                        $updCompleted = $db->prepare("UPDATE $table SET completed_at = NOW() WHERE id = ?");
                        $updCompleted->execute([$orderId]);
                    }
                }

                $success = "Order state updated successfully!";
            } catch (Exception $e) {
                $error = "Failed to update status flag: " . $e->getMessage();
            }
        }
    }
}

// 3. Fetch Sourcing Orders & auto-heal missing Order Numbers
$approvedSourcingOrders = [];
try {
    $qSourcing = "
        SELECT 
            so.id, 
            so.style_name, 
            so.category, 
            so.garment_item,
            so.target_quantity, 
            so.fob_budget,
            so.smv,
            so.images_json,
            so.created_at,
            so.order_number,
            so.shipment_status,
            so.payment_status,
            COALESCE(so.production_status, 'Pending') AS production_status,
            so.completed_at,
            so.spec_description,
            buyer.name AS buyer_name,
            buyer.email AS buyer_email,
            buyer.phone AS buyer_phone,
            buyer_f.factory_name AS buyer_factory_name,
            ob.proposed_fob AS accepted_price,
            ob.created_at AS bid_accepted_at,
            supplier.name AS supplier_name,
            supplier.email AS supplier_email,
            supplier.phone AS supplier_phone,
            f.factory_name
        FROM sourcing_orders so
        LEFT JOIN users buyer ON so.user_id = buyer.id
        LEFT JOIN factories buyer_f ON buyer_f.user_id = buyer.id
        LEFT JOIN order_bids ob ON so.id = ob.order_id AND ob.status = 'Approved'
        LEFT JOIN users supplier ON ob.supplier_id = supplier.id
        LEFT JOIN factories f ON f.user_id = supplier.id
        WHERE so.is_closed = 1
        ORDER BY so.created_at DESC
    ";
    $stmtSourcing = $db->query($qSourcing);
    $approvedSourcingOrders = $stmtSourcing->fetchAll();

    // Auto-heal empty order numbers for any sourcing orders closed prior
    foreach ($approvedSourcingOrders as &$row) {
        if (empty($row['order_number'])) {
            $numStmt = $db->query("SELECT order_number FROM sourcing_orders WHERE order_number LIKE 'ORD-%' UNION SELECT order_number FROM capacity_posts WHERE order_number LIKE 'ORD-%'");
            $nums = $numStmt->fetchAll(PDO::FETCH_COLUMN);
            $maxNum = 1000;
            foreach ($nums as $n) {
                if (preg_match('/^ORD-(\d+)$/', $n, $matches)) {
                    $val = (int)$matches[1];
                    if ($val > $maxNum) $maxNum = $val;
                }
            }
            $nextNum = $maxNum + 1;
            $newOrdNum = "ORD-" . $nextNum;
            $upd = $db->prepare("UPDATE sourcing_orders SET order_number = ? WHERE id = ?");
            $upd->execute([$newOrdNum, $row['id']]);
            $row['order_number'] = $newOrdNum;
        }
    }
    unset($row);
} catch (Exception $e) {
    $error = "Error loading sourcing order analytics: " . $e->getMessage();
}

// 4. Fetch Capacity Need Orders & auto-heal missing Order Numbers
$approvedNeedOrders = [];
try {
    $qCapacity = "
        SELECT 
            cp.id, 
            cp.category, 
            cp.garment_item,
            cp.quantity_capacity, 
            cp.sewing_start_date,
            cp.created_at,
            cp.order_number,
            cp.shipment_status,
            cp.payment_status,
            COALESCE(cp.production_status, 'Pending') AS production_status,
            cp.completed_at,
            f.factory_name,
            owner.name AS owner_name,
            owner.email AS owner_email,
            owner.phone AS owner_phone,
            cq.quantity AS offered_quantity,
            cq.target_budget,
            cq.style_name,
            cq.smv,
            cq.sample_photos_json,
            cq.spec_description,
            buyer.name AS buyer_name,
            buyer.email AS buyer_email,
            buyer.phone AS buyer_phone,
            buyer_f.factory_name AS buyer_factory_name
        FROM capacity_posts cp
        LEFT JOIN factories f ON cp.factory_id = f.id
        LEFT JOIN users owner ON cp.user_id = owner.id
        LEFT JOIN capacity_quotes cq ON cq.id = (
            SELECT id FROM capacity_quotes 
            WHERE capacity_post_id = cp.id 
            ORDER BY (status = 'Approved') DESC, id DESC 
            LIMIT 1
        )
        LEFT JOIN users buyer ON cq.buyer_id = buyer.id
        LEFT JOIN factories buyer_f ON buyer_f.user_id = buyer.id
        WHERE cp.is_closed = 1
        ORDER BY cp.created_at DESC
    ";
    $stmtCapacity = $db->query($qCapacity);
    $approvedNeedOrders = $stmtCapacity->fetchAll();

    // Auto-heal empty order numbers for any capacity posts closed prior
    foreach ($approvedNeedOrders as &$post) {
        if (empty($post['order_number'])) {
            $numStmt = $db->query("SELECT order_number FROM sourcing_orders WHERE order_number LIKE 'ORD-%' UNION SELECT order_number FROM capacity_posts WHERE order_number LIKE 'ORD-%'");
            $nums = $numStmt->fetchAll(PDO::FETCH_COLUMN);
            $maxNum = 1000;
            foreach ($nums as $n) {
                if (preg_match('/^ORD-(\d+)$/', $n, $matches)) {
                    $val = (int)$matches[1];
                    if ($val > $maxNum) $maxNum = $val;
                }
            }
            $nextNum = $maxNum + 1;
            $newOrdNum = "ORD-" . $nextNum;
            $upd = $db->prepare("UPDATE capacity_posts SET order_number = ? WHERE id = ?");
            $upd->execute([$newOrdNum, $post['id']]);
            $post['order_number'] = $newOrdNum;
        }
    }
    unset($post);
} catch (Exception $e) {
    $error = "Error loading capacity order analytics: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Analysis - Admin Dashboard</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .font-mono-custom { font-family: 'JetBrains Mono', monospace; }
    </style>
</head>
<body class="bg-slate-50 text-slate-800 min-h-screen flex flex-col justify-between">

    <!-- Top Navigation Header -->
    <header class="bg-slate-900 text-white shadow-md border-b border-slate-800">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div class="flex items-center space-x-3">
                <span class="p-2 bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 rounded-lg">
                    <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="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"></path>
                    </svg>
                </span>
                <div>
                    <h1 class="text-sm font-bold tracking-tight font-sans">Order Analysis &amp; Auditing</h1>
                    <p class="text-[10px] text-slate-400 font-mono-custom">Authorized Node: <?php echo htmlspecialchars($user['name']); ?> (<?php echo htmlspecialchars($user['designation']); ?>)</p>
                </div>
            </div>

            <nav class="flex items-center space-x-1 bg-slate-950 p-1 rounded-lg border border-slate-800 overflow-x-auto">
                <a href="/admin/dashboard.php" class="px-3 py-1.5 rounded-md text-xs font-semibold text-slate-400 hover:text-white transition">Dashboard</a>
                <a href="/admin/users.php" class="px-3 py-1.5 rounded-md text-xs font-semibold text-slate-400 hover:text-white transition">User</a>
                <a href="/admin/employees.php" class="px-3 py-1.5 rounded-md text-xs font-semibold text-slate-400 hover:text-white transition">Employee</a>
                <a href="/admin/factories.php" class="px-3 py-1.5 rounded-md text-xs font-semibold text-slate-400 hover:text-white transition">My Factories</a>
                <a href="/admin/analysis.php" class="px-3 py-1.5 rounded-md text-xs font-semibold bg-indigo-600 text-white shadow-sm transition">Order Analysis</a>
                <a href="/admin/profile.php" class="px-3 py-1.5 rounded-md text-xs font-semibold text-slate-400 hover:text-white transition">Profile Settings</a>
                <a href="/auth/login.php" class="px-2.5 py-1.5 rounded-md text-xs font-bold text-rose-400 hover:text-rose-300 transition">Logout</a>
            </nav>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 flex-grow w-full space-y-8">
        <!-- Banner -->
        <div class="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-950 rounded-2xl p-6 text-white shadow-md border border-slate-700/50 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div class="space-y-1.5">
                <span class="inline-flex bg-indigo-500/10 text-indigo-400 text-[10px] font-mono-custom px-2.5 py-0.5 rounded-full border border-indigo-500/20">Market Statistics</span>
                <h2 class="text-lg font-bold">Transaction Intelligence Board</h2>
                <p class="text-xs text-slate-300 max-w-xl leading-relaxed">
                    Full visibility over completed sourcing agreements and empty factory capacity bookings. Monitor closed contracts, match values, and secure trade metrics.
                </p>
            </div>
            <div class="flex gap-3">
                <div class="bg-slate-900 border border-slate-800 px-4 py-2 rounded-xl text-center min-w-[120px]">
                    <p class="text-[9px] text-slate-500 uppercase font-bold font-mono-custom">Closed Sourcing</p>
                    <p class="text-lg font-bold text-indigo-400 font-sans"><?php echo count($approvedSourcingOrders); ?></p>
                </div>
                <div class="bg-slate-900 border border-slate-800 px-4 py-2 rounded-xl text-center min-w-[120px]">
                    <p class="text-[9px] text-slate-500 uppercase font-bold font-mono-custom">Capacity Bookings</p>
                    <p class="text-lg font-bold text-emerald-400 font-sans"><?php echo count($approvedNeedOrders); ?></p>
                </div>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="bg-rose-50 border border-rose-200 text-rose-800 p-4 rounded-xl text-xs font-bold">
                ⚠️ <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-4 rounded-xl text-xs font-bold">
                ✨ <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <!-- Search Filters Section -->
        <div class="bg-white border border-slate-200 rounded-xl p-4 shadow-xs flex flex-col sm:flex-row gap-4 items-center justify-between">
            <div class="w-full sm:max-w-md relative">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <svg class="h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                </div>
                <input 
                    type="text" 
                    id="orderSearchInput" 
                    placeholder="Search by Order Number, Style Name, Category, or Factory..." 
                    class="block w-full pl-9 pr-3 py-2 border border-slate-200 rounded-lg text-xs focus:outline-none focus:border-indigo-500 font-sans shadow-inner"
                    onkeyup="filterOrders()"
                >
            </div>
            <div class="text-[10px] text-slate-400 font-mono-custom font-medium">
                * Real-time live client-side filters active
            </div>
        </div>

        <!-- Section 1: Closed Sourcing Orders -->
        <div class="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden space-y-4">
            <div class="p-6 border-b border-slate-150 flex justify-between items-center bg-slate-50/50">
                <div>
                    <h3 class="text-xs uppercase font-bold tracking-wider text-slate-500 font-mono-custom">Category A</h3>
                    <h2 class="text-sm font-bold text-slate-900 font-sans">Sourcing Contracts</h2>
                    <p class="text-[11px] text-slate-500 mt-0.5">Sourcing orders posted by buyers where a supplier's bid has been officially accepted.</p>
                </div>
                <span class="text-[10px] font-bold bg-indigo-50 text-indigo-700 px-2.5 py-0.5 rounded border border-indigo-150">Filled Orders</span>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse text-xs" id="sourcingOrdersTable">
                    <thead>
                        <tr class="bg-slate-50 border-b border-slate-200 text-slate-600 font-mono-custom uppercase text-[9px] tracking-wider font-bold">
                            <th class="py-3 px-6">Order Number</th>
                            <th class="py-3 px-6">Buyer (Issuer)</th>
                            <th class="py-3 px-6">Winning Supplier</th>
                            <th class="py-3 px-6">Order Information (Qty/FOB/Total)</th>
                            <th class="py-3 px-6">Commission</th>
                            <th class="py-3 px-6 text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-150">
                        <?php if (empty($approvedSourcingOrders)): ?>
                            <tr class="no-results-row">
                                <td colspan="6" class="py-16 text-center space-y-2 bg-slate-50/20 text-slate-400 italic">
                                    No approved sourcing logs found.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($approvedSourcingOrders as $row): 
                                // Color code logic
                                $rowClass = '';
                                if ($row['shipment_status'] === 'Completed' && $row['payment_status'] === 'Completed') {
                                    $rowClass = 'bg-rose-200 hover:bg-rose-300/80';
                                } elseif ($row['shipment_status'] === 'Completed') {
                                    $rowClass = 'bg-rose-50/70 hover:bg-rose-100/70';
                                } else {
                                    $rowClass = 'hover:bg-slate-50/30';
                                }
                            ?>
                                <tr class="<?php echo $rowClass; ?> transition duration-75">
                                    <td class="py-3.5 px-6 font-bold text-slate-900 font-mono-custom">
                                        <?php echo htmlspecialchars($row['order_number']); ?>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <div>
                                            <p class="font-bold text-slate-900"><?php echo htmlspecialchars($row['buyer_factory_name'] ?: 'Global Sourcing Ltd'); ?></p>
                                            <p class="text-[10px] text-indigo-600 font-semibold font-mono-custom"><?php echo htmlspecialchars($row['buyer_name'] ?: 'N/A'); ?></p>
                                            <p class="text-[10px] text-slate-500 font-mono-custom"><?php echo htmlspecialchars($row['buyer_phone'] ?: 'N/A'); ?></p>
                                        </div>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <?php if ($row['supplier_name']): ?>
                                            <div>
                                                <p class="font-bold text-slate-900"><?php echo htmlspecialchars($row['factory_name'] ?: 'Apex Apparel'); ?></p>
                                                <p class="text-[10px] text-indigo-600 font-semibold font-mono-custom"><?php echo htmlspecialchars($row['supplier_name']); ?></p>
                                                <p class="text-[10px] text-slate-500 font-mono-custom"><?php echo htmlspecialchars($row['supplier_phone'] ?: 'N/A'); ?></p>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-slate-400 italic">No Winner Registered</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <div class="space-y-0.5 font-mono-custom">
                                            <p class="font-bold text-slate-900"><?php echo number_format($row['target_quantity']); ?> Pcs</p>
                                            <?php $finalFob = $row['accepted_price'] ?: $row['fob_budget']; ?>
                                            <p class="text-[10px] text-slate-500">Unit FOB: ৳<? echo number_format($finalFob, 2); ?></p>
                                            <p class="text-emerald-600 font-bold">Total: ৳<?php echo number_format($row['target_quantity'] * $finalFob, 2); ?></p>
                                        </div>
                                    </td>
                                    <td class="py-3.5 px-6 font-bold font-mono-custom text-slate-700">
                                        ৳<?php echo number_format($row['target_quantity'] * 5.00, 2); ?>
                                    </td>
                                    <td class="py-3.5 px-6 text-center">
                                        <button 
                                            onclick='openSourcingModal(<?php echo htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8'); ?>)'
                                            class="bg-slate-900 hover:bg-slate-800 text-white font-bold py-1.5 px-3 rounded-lg text-[11px] transition cursor-pointer shadow-sm"
                                        >
                                            View
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Section 2: Closed Capacity/Need Orders -->
        <div class="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden space-y-4">
            <div class="p-6 border-b border-slate-150 flex justify-between items-center bg-slate-50/50">
                <div>
                    <h3 class="text-xs uppercase font-bold tracking-wider text-slate-500 font-mono-custom">Category B</h3>
                    <h2 class="text-sm font-bold text-slate-900 font-sans">Capacity Bookings</h2>
                    <p class="text-[11px] text-slate-500 mt-0.5">Empty production lines posted by suppliers where a brand has successfully secured space.</p>
                </div>
                <span class="text-[10px] font-bold bg-emerald-50 text-emerald-700 px-2.5 py-0.5 rounded border border-emerald-150">Filled Capacity</span>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse text-xs" id="capacityOrdersTable">
                    <thead>
                        <tr class="bg-slate-50 border-b border-slate-200 text-slate-600 font-mono-custom uppercase text-[9px] tracking-wider font-bold">
                            <th class="py-3 px-6">Order Number</th>
                            <th class="py-3 px-6">Securing Buyer</th>
                            <th class="py-3 px-6">Factory/Space Owner</th>
                            <th class="py-3 px-6">Order Information (Qty/FOB/Total)</th>
                            <th class="py-3 px-6">Commission</th>
                            <th class="py-3 px-6 text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-150">
                        <?php if (empty($approvedNeedOrders)): ?>
                            <tr class="no-results-row">
                                <td colspan="6" class="py-16 text-center space-y-2 bg-slate-50/20 text-slate-400 italic">
                                    No approved capacity logs found.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($approvedNeedOrders as $post): 
                                // Color code logic
                                $postClass = '';
                                if ($post['shipment_status'] === 'Completed' && $post['payment_status'] === 'Completed') {
                                    $postClass = 'bg-rose-200 hover:bg-rose-300/80';
                                } elseif ($post['shipment_status'] === 'Completed') {
                                    $postClass = 'bg-rose-50/70 hover:bg-rose-100/70';
                                } else {
                                    $postClass = 'hover:bg-slate-50/30';
                                }
                            ?>
                                <tr class="<?php echo $postClass; ?> transition duration-75">
                                    <td class="py-3.5 px-6 font-bold text-slate-900 font-mono-custom">
                                        <?php echo htmlspecialchars($post['order_number']); ?>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <div>
                                            <p class="font-bold text-slate-900"><?php echo htmlspecialchars($post['buyer_factory_name'] ?: 'Global Sourcing Ltd'); ?></p>
                                            <p class="text-[10px] text-indigo-600 font-semibold font-mono-custom"><?php echo htmlspecialchars($post['buyer_name'] ?: 'N/A'); ?></p>
                                            <p class="text-[10px] text-slate-500 font-mono-custom"><?php echo htmlspecialchars($post['buyer_phone'] ?: 'N/A'); ?></p>
                                        </div>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <div>
                                            <p class="font-bold text-slate-900"><?php echo htmlspecialchars($post['factory_name'] ?: 'Apex Apparel'); ?></p>
                                            <p class="text-[10px] text-indigo-600 font-semibold font-mono-custom"><?php echo htmlspecialchars($post['owner_name'] ?: 'N/A'); ?></p>
                                            <p class="text-[10px] text-slate-500 font-mono-custom"><?php echo htmlspecialchars($post['owner_phone'] ?: 'N/A'); ?></p>
                                        </div>
                                    </td>
                                    <td class="py-3.5 px-6">
                                        <div class="space-y-0.5 font-mono-custom">
                                            <?php $bookedQty = $post['offered_quantity'] ?: $post['quantity_capacity']; ?>
                                            <p class="font-bold text-slate-900"><?php echo number_format($bookedQty); ?> Pcs</p>
                                            <p class="text-[10px] text-slate-500">Unit FOB: ৳<?php echo number_format($post['target_budget'] ?: 0, 2); ?></p>
                                            <p class="text-emerald-600 font-bold">Total: ৳<?php echo number_format($bookedQty * ($post['target_budget'] ?: 0), 2); ?></p>
                                        </div>
                                    </td>
                                    <td class="py-3.5 px-6 font-bold font-mono-custom text-slate-700">
                                        ৳<?php echo number_format($bookedQty * 5.00, 2); ?>
                                    </td>
                                    <td class="py-3.5 px-6 text-center">
                                        <button 
                                            onclick='openCapacityModal(<?php echo htmlspecialchars(json_encode($post), ENT_QUOTES, 'UTF-8'); ?>)'
                                            class="bg-slate-900 hover:bg-slate-800 text-white font-bold py-1.5 px-3 rounded-lg text-[11px] transition cursor-pointer shadow-sm"
                                        >
                                            View
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <!-- Unified Detailed Audit View Modal -->
    <div id="auditModal" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/65 backdrop-blur-xs flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl max-w-2xl w-full border border-slate-200 shadow-2xl relative flex flex-col max-h-[90vh]">
            
            <!-- Modal Header -->
            <div class="flex justify-between items-center px-6 py-4 border-b border-slate-100">
                <div class="space-y-1">
                    <span class="bg-indigo-50 text-indigo-700 text-[10px] font-mono-custom font-bold px-2.5 py-0.5 rounded border border-indigo-150">
                        ADMIN COMPLIANCE PORTAL
                    </span>
                    <h3 class="text-base font-bold text-slate-900 font-sans" id="modalTitle">
                        Transaction Audit &amp; State Settings
                    </h3>
                </div>
                <button
                    onclick="closeModal()"
                    class="text-slate-400 hover:text-slate-600 transition p-1.5 rounded-full hover:bg-slate-100 cursor-pointer"
                >
                    <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="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>

            <!-- Modal Content -->
            <div class="p-6 space-y-6 overflow-y-auto flex-1 text-slate-700">
                
                <!-- ID Banner Card -->
                <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
                    <div>
                        <p class="text-[10px] text-slate-400 font-mono-custom uppercase font-semibold">Security Order Reference</p>
                        <p class="text-base font-bold text-indigo-600 font-mono-custom" id="modalOrderNumber">ORD-XXXX</p>
                        <p class="text-xs text-slate-500 font-sans mt-0.5" id="modalSubtext">Style / Category name here</p>
                    </div>
                    <div class="text-right space-y-1">
                        <span class="inline-block bg-slate-900 text-white font-mono-custom text-[10px] font-semibold px-2.5 py-1 rounded" id="modalCategoryBadge">
                            Woven Apparels
                        </span>
                        <div>
                            <span id="modalProductionBadge" class="bg-slate-100 text-slate-700 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom">
                                Pending
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Transaction Details Grid -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="bg-slate-50/60 p-4 rounded-xl border border-slate-150/80 space-y-2">
                        <h4 class="text-xs font-bold text-slate-900 font-sans uppercase tracking-wider flex items-center gap-1.5">
                            👤 Buyer Information
                        </h4>
                        <div class="text-xs space-y-1 font-sans">
                            <p><span class="font-semibold text-slate-500">Contact:</span> <span id="modalBuyerName" class="text-slate-800 font-semibold"></span></p>
                            <p><span class="font-semibold text-slate-500">Email:</span> <span id="modalBuyerEmail" class="font-mono-custom"></span></p>
                            <p><span class="font-semibold text-slate-500">Phone:</span> <span id="modalBuyerPhone" class="font-mono-custom"></span></p>
                        </div>
                    </div>

                    <div class="bg-slate-50/60 p-4 rounded-xl border border-slate-150/80 space-y-2">
                        <h4 class="text-xs font-bold text-slate-900 font-sans uppercase tracking-wider flex items-center gap-1.5">
                            🏭 Supplier / Factory
                        </h4>
                        <div class="text-xs space-y-1 font-sans">
                            <p><span class="font-semibold text-slate-500">Factory:</span> <span id="modalSupplierFactory" class="text-slate-800 font-semibold"></span></p>
                            <p><span class="font-semibold text-slate-500">Operator:</span> <span id="modalSupplierName"></span></p>
                            <p><span class="font-semibold text-slate-500">Phone:</span> <span id="modalSupplierPhone" class="font-mono-custom"></span></p>
                        </div>
                    </div>
                </div>

                <!-- Financial Metrics & Dates -->
                <div class="grid grid-cols-2 sm:grid-cols-3 gap-3 bg-slate-50/30 border border-slate-100 rounded-xl p-4">
                    <div class="bg-white p-2.5 rounded-lg border border-slate-200 text-center">
                        <p class="text-[9px] font-mono-custom text-slate-400 uppercase font-bold">Booked Qty</p>
                        <p class="text-xs font-bold text-slate-800 font-mono-custom" id="modalQty">
                            0 Pcs
                        </p>
                    </div>
                    <div class="bg-white p-2.5 rounded-lg border border-slate-200 text-center">
                        <p class="text-[9px] font-mono-custom text-slate-400 uppercase font-bold">Unit FOB Price</p>
                        <p class="text-xs font-bold text-emerald-600 font-mono-custom" id="modalFob">
                            ৳0.00
                        </p>
                    </div>
                    <div class="bg-white p-2.5 rounded-lg border border-slate-200 text-center col-span-2 sm:col-span-1">
                        <p class="text-[9px] font-mono-custom text-slate-400 uppercase font-bold">Finalized Date</p>
                        <p class="text-xs font-bold text-slate-800 font-mono-custom" id="modalAppDate">
                            YYYY-MM-DD
                        </p>
                    </div>
                </div>

                <!-- Capacity Deal & Technical Specifications Summary Panel -->
                <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-3">
                    <h4 class="text-xs font-bold text-slate-900 font-sans uppercase tracking-wider flex items-center gap-1.5">
                        📋 Capacity Deal &amp; Technical Specifications
                    </h4>
                    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3 text-xs bg-white p-3 rounded-lg border border-slate-150">
                        <div>
                            <span class="text-[10px] text-slate-400 uppercase font-bold block">Capable Garment Type</span>
                            <span id="modalGarmentType" class="font-bold text-slate-900 text-xs">N/A</span>
                        </div>
                        <div>
                            <span class="text-[10px] text-slate-400 uppercase font-bold block">Offered Quantity</span>
                            <span id="modalSpecQty" class="font-bold text-slate-900 text-xs font-mono-custom">0 Pcs</span>
                        </div>
                        <div>
                            <span class="text-[10px] text-slate-400 uppercase font-bold block">Target FOB Price</span>
                            <span id="modalSpecFob" class="font-bold text-emerald-700 text-xs font-mono-custom">৳0.00</span>
                        </div>
                        <div>
                            <span class="text-[10px] text-slate-400 uppercase font-bold block">Style Name</span>
                            <span id="modalStyleName" class="font-bold text-slate-900 text-xs">N/A</span>
                        </div>
                        <div>
                            <span class="text-[10px] text-slate-400 uppercase font-bold block">SMV</span>
                            <span id="modalSMV" class="font-bold text-indigo-700 text-xs font-mono-custom">N/A</span>
                        </div>
                    </div>

                    <!-- 4 Sample Photos Gallery -->
                    <div class="space-y-1">
                        <span class="text-[10px] text-slate-400 uppercase font-bold block">Sample Photos Gallery (Max 4)</span>
                        <div id="modalPhotosGallery" class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-2">
                            <p class="text-[11px] text-slate-400 italic col-span-4">No sample photos provided.</p>
                        </div>
                    </div>

                    <!-- Detailed Fabric & Spec Description -->
                    <div class="space-y-1">
                        <span class="text-[10px] text-slate-400 uppercase font-bold block">Detailed Fabric &amp; Spec Description</span>
                        <p id="modalDescription" class="text-xs text-slate-700 bg-white p-3 rounded-lg border border-slate-150 leading-relaxed whitespace-pre-line"></p>
                    </div>
                </div>

                <!-- Shipment and Payment Management Panel -->
                <div class="bg-slate-50/50 rounded-xl border border-slate-200 p-4 space-y-3">
                    <h4 class="text-xs font-bold text-slate-900 font-sans uppercase tracking-wider flex items-center gap-1">
                        ⚙️ Management Control Workflow
                    </h4>
                    <p class="text-[10px] text-slate-400 mt-0.5 font-sans leading-relaxed">
                        Authorize delivery state controls. Clicking a checkbox flags database milestones immediately.
                    </p>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
                        <!-- Shipment Action Column -->
                        <div class="bg-white border border-slate-150 rounded-lg p-3 flex flex-col justify-between items-center gap-2">
                            <span class="text-[10px] uppercase font-bold font-mono-custom text-slate-400">Shipment Status</span>
                            <div id="shipmentStatusContainer">
                                <!-- Dynamic Status badge or active button form -->
                            </div>
                        </div>

                        <!-- Payment Action Column -->
                        <div class="bg-white border border-slate-150 rounded-lg p-3 flex flex-col justify-between items-center gap-2">
                            <span class="text-[10px] uppercase font-bold font-mono-custom text-slate-400">Payment Status</span>
                            <div id="paymentStatusContainer">
                                <!-- Dynamic Status badge or active button form -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 rounded-b-2xl flex justify-between items-center">
                <button
                    onclick="openAgreementModal()"
                    class="bg-indigo-600 hover:bg-indigo-700 text-white font-semibold px-4 py-2 rounded-lg text-xs transition cursor-pointer shadow-sm flex items-center space-x-1.5"
                >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                    <span>Agreement</span>
                </button>
                <div class="flex items-center space-x-2">
                    <button
                        id="btnProceedProduction"
                        onclick="proceedToProduction()"
                        class="bg-amber-600 hover:bg-amber-700 text-white font-bold px-4 py-2 rounded-lg text-xs transition cursor-pointer shadow-sm flex items-center space-x-1.5"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                        <span id="proceedBtnLabel">Proceed</span>
                    </button>
                    <button
                        onclick="closeModal()"
                        class="bg-slate-950 hover:bg-slate-800 text-white font-semibold px-4 py-2 rounded-lg text-xs transition cursor-pointer shadow-sm"
                    >
                        Close Audit View
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Contract Agreement Document Overlay Modal -->
    <div id="agreementModal" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/80 backdrop-blur-xs flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl max-w-3xl w-full border border-slate-200 shadow-2xl relative flex flex-col max-h-[90vh]">
            <div class="flex justify-between items-center px-6 py-4 border-b border-slate-200 bg-slate-50 rounded-t-2xl no-print">
                <div class="flex items-center space-x-2">
                    <span class="bg-emerald-100 text-emerald-800 font-bold px-2.5 py-0.5 rounded text-xs font-mono-custom">OFFICIAL CONTRACT AGREEMENT</span>
                    <span class="text-xs font-mono-custom text-slate-500 font-bold" id="agreeModalOrderNum">ORD-XXXX</span>
                </div>
                <div class="flex items-center space-x-2">
                    <button onclick="window.print()" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-1.5 rounded-lg text-xs shadow-sm flex items-center space-x-1.5 cursor-pointer">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
                        <span>Print Agreement</span>
                    </button>
                    <button onclick="closeAgreementModal()" class="text-slate-400 hover:text-slate-700 p-1.5 text-lg cursor-pointer">✕</button>
                </div>
            </div>

            <!-- Printable Document Wrapper -->
            <div id="printable-agreement-content" class="p-8 space-y-6 overflow-y-auto font-sans text-slate-900 bg-white">
                <!-- Document Title Header -->
                <div class="border-b-2 border-slate-900 pb-4 text-center space-y-1">
                    <h2 class="text-xl font-black uppercase tracking-wider text-slate-900">B2B Garments Sourcing Hub</h2>
                    <p class="text-xs uppercase font-bold text-slate-600 tracking-widest">Official Sourcing &amp; Capacity Production Contract Agreement</p>
                    <p class="text-[10px] text-slate-500 font-mono-custom">Reference No: <span id="agreeDocRef" class="font-bold text-indigo-700">ORD-1001</span> &bull; Issue Date: <span id="agreeDocDate"><?php echo date('Y-m-d'); ?></span></p>
                </div>

                <!-- Parties Info Grid -->
                <div class="grid grid-cols-2 gap-6 bg-slate-50 p-4 rounded-xl border border-slate-200 text-xs">
                    <div>
                        <p class="font-bold uppercase text-[10px] text-slate-500 tracking-wider mb-1">Party A (Buyer / Sourcing Issuer)</p>
                        <p class="font-bold text-slate-900 text-sm" id="agreeBuyerName">N/A</p>
                        <p class="text-slate-600" id="agreeBuyerFactory">Buyer Organization</p>
                        <p class="font-mono-custom text-slate-500 text-[11px]" id="agreeBuyerEmail">buyer@example.com</p>
                    </div>
                    <div>
                        <p class="font-bold uppercase text-[10px] text-slate-500 tracking-wider mb-1">Party B (Factory / Manufacturer Supplier)</p>
                        <p class="font-bold text-slate-900 text-sm" id="agreeSupplierFactory">Apex Apparel Ltd.</p>
                        <p class="text-slate-600" id="agreeSupplierName">Operator Name</p>
                        <p class="font-mono-custom text-slate-500 text-[11px]" id="agreeSupplierEmail">supplier@example.com</p>
                    </div>
                </div>

                <!-- Financial Ledger & Order Specs Table -->
                <div class="space-y-2">
                    <h4 class="text-xs font-bold uppercase tracking-wider text-slate-800">1. Production Specifications &amp; Agreed Financials</h4>
                    <table class="w-full border-collapse border border-slate-300 text-xs">
                        <tr class="bg-slate-100">
                            <th class="border border-slate-300 p-2 text-left">Category</th>
                            <th class="border border-slate-300 p-2 text-left">Style Name</th>
                            <th class="border border-slate-300 p-2 text-center">SMV</th>
                            <th class="border border-slate-300 p-2 text-right">Booked Qty</th>
                            <th class="border border-slate-300 p-2 text-right">Unit FOB</th>
                            <th class="border border-slate-300 p-2 text-right">Total Contract Value</th>
                        </tr>
                        <tr>
                            <td class="border border-slate-300 p-2" id="agreeCategory">Woven Apparels</td>
                            <td class="border border-slate-300 p-2 font-bold" id="agreeStyleName">N/A</td>
                            <td class="border border-slate-300 p-2 text-center font-mono-custom" id="agreeSMV">N/A</td>
                            <td class="border border-slate-300 p-2 text-right font-mono-custom font-bold" id="agreeQty">0 Pcs</td>
                            <td class="border border-slate-300 p-2 text-right font-mono-custom text-emerald-700 font-bold" id="agreeFob">৳0.00</td>
                            <td class="border border-slate-300 p-2 text-right font-mono-custom text-slate-900 font-black" id="agreeTotalVal">৳0.00</td>
                        </tr>
                    </table>
                </div>

                <!-- Detailed Specs and Sample Photos -->
                <div class="space-y-2 text-xs">
                    <h4 class="text-xs font-bold uppercase tracking-wider text-slate-800">2. Technical Specifications &amp; Fabric Description</h4>
                    <div class="bg-slate-50 border border-slate-200 p-3 rounded-lg text-slate-700 leading-relaxed whitespace-pre-line" id="agreeSpecDesc">
                        No detailed specifications attached.
                    </div>
                    <div id="agreePhotosGallery" class="grid grid-cols-2 md:grid-cols-4 gap-4 pt-2"></div>
                </div>

                <!-- Terms and Conditions -->
                <div class="space-y-2 text-[11px] text-slate-600 leading-relaxed border-t border-slate-200 pt-4">
                    <h4 class="text-xs font-bold uppercase tracking-wider text-slate-800">3. Standard Legal Terms &amp; Conditions</h4>
                    <ol class="list-decimal list-inside space-y-1">
                        <li>Party B agrees to execute garment manufacturing strictly adhering to SMV, fabric composition, and techpack details specified above.</li>
                        <li>Unit prices are locked in Bangladesh Taka (৳ BDT). No price adjustments permitted after contract execution.</li>
                        <li>Both parties agree to submit production milestones to B2B Garments Sourcing Hub platform compliance audits.</li>
                        <li>Disputes shall be governed under the laws of Bangladesh Garment Manufacturers and Exporters Association (BGMEA) arbitration rules.</li>
                    </ol>
                </div>

                <!-- Signatures -->
                <div class="grid grid-cols-3 gap-6 pt-12 text-center text-xs">
                    <div class="border-t border-slate-400 pt-2 space-y-1">
                        <p class="font-bold text-slate-800" id="sigBuyer">Authorized Buyer</p>
                        <p class="text-[10px] text-slate-400 font-mono-custom">Party A Digital Signature</p>
                    </div>
                    <div class="border-t border-slate-400 pt-2 space-y-1">
                        <p class="font-bold text-slate-800" id="sigSupplier">Authorized Factory</p>
                        <p class="text-[10px] text-slate-400 font-mono-custom">Party B Digital Signature</p>
                    </div>
                    <div class="border-t border-slate-400 pt-2 space-y-1">
                        <p class="font-bold text-indigo-700">Platform Admin Seal</p>
                        <p class="text-[10px] text-slate-400 font-mono-custom">B2B Marketplace Audit Verification</p>
                    </div>
                </div>
            </div>

            <div class="px-6 py-4 border-t border-slate-200 bg-slate-50 rounded-b-2xl flex justify-between items-center no-print">
                <button onclick="window.print()" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-2 rounded-lg text-xs shadow-sm flex items-center space-x-1.5 cursor-pointer">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
                    <span>Print Agreement</span>
                </button>
                <button onclick="closeAgreementModal()" class="bg-slate-900 hover:bg-slate-800 text-white font-semibold px-4 py-2 rounded-lg text-xs cursor-pointer">
                    Close Agreement
                </button>
            </div>
        </div>
    </div>

    <style>
    @media print {
        body * {
            visibility: hidden !important;
        }
        #printable-agreement-content, #printable-agreement-content * {
            visibility: visible !important;
        }
        #printable-agreement-content {
            position: absolute !important;
            left: 0 !important;
            top: 0 !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 24px !important;
            background: #ffffff !important;
            color: #000000 !important;
            box-shadow: none !important;
            border: none !important;
        }
        .no-print {
            display: none !important;
        }
    }
    </style>
        </div>
    </div>

    <footer class="bg-slate-900 border-t border-slate-800 text-slate-500 py-6 text-xs text-center font-mono-custom mt-12">
        <p>&copy; 2026 B2B Garments Sourcing Hub. Safe Administrative Sub-Terminal.</p>
    </footer>

    <!-- Client side interactive logic and Modal handler -->
    <script>
        function filterOrders() {
            const input = document.getElementById('orderSearchInput');
            const filter = input.value.toLowerCase();
            
            // Filter Sourcing Orders Table
            const sourcingRows = document.querySelectorAll('#sourcingOrdersTable tbody tr');
            let sourcingMatches = 0;
            sourcingRows.forEach(row => {
                if (row.classList.contains('no-results-row')) return;
                const text = row.innerText.toLowerCase();
                if (text.includes(filter)) {
                    row.style.display = '';
                    sourcingMatches++;
                } else {
                    row.style.display = 'none';
                }
            });
            
            // Filter Capacity Orders Table
            const capacityRows = document.querySelectorAll('#capacityOrdersTable tbody tr');
            let capacityMatches = 0;
            capacityRows.forEach(row => {
                if (row.classList.contains('no-results-row')) return;
                const text = row.innerText.toLowerCase();
                if (text.includes(filter)) {
                    row.style.display = '';
                    capacityMatches++;
                } else {
                    row.style.display = 'none';
                }
            });
        }

        const auditModal = document.getElementById('auditModal');
        let currentAuditItem = null;
        let currentAuditType = null;

        function openSourcingModal(order) {
            currentAuditItem = order;
            currentAuditType = 'sourcing';

            document.getElementById('modalTitle').innerText = "Transaction Audit: Sourcing Agreement";
            document.getElementById('modalOrderNumber').innerText = order.order_number;
            document.getElementById('modalSubtext').innerText = "Style: " + (order.style_name || 'N/A');
            document.getElementById('modalCategoryBadge').innerText = order.category || 'Woven Apparels';

            // Production status badge
            const prodBadge = document.getElementById('modalProductionBadge');
            const prodStatus = order.production_status || 'Pending';
            if (prodStatus === 'In Production') {
                prodBadge.className = 'bg-amber-100 text-amber-800 border border-amber-300 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom';
                prodBadge.innerText = 'In Production';
            } else {
                prodBadge.className = 'bg-slate-100 text-slate-700 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom';
                prodBadge.innerText = prodStatus;
            }

            // Contacts
            document.getElementById('modalBuyerName').innerText = order.buyer_name || 'N/A';
            document.getElementById('modalBuyerEmail').innerText = order.buyer_email || 'N/A';
            document.getElementById('modalBuyerPhone').innerText = order.buyer_phone || 'Private';
            
            document.getElementById('modalSupplierFactory').innerText = order.factory_name || 'Apex Apparel Ltd.';
            document.getElementById('modalSupplierName').innerText = order.supplier_name || 'N/A';
            document.getElementById('modalSupplierPhone').innerText = order.supplier_phone || 'Private';
            
            // Financials
            document.getElementById('modalQty').innerText = Number(order.target_quantity || 0).toLocaleString() + " Pcs";
            const bidVal = order.accepted_price ? Number(order.accepted_price) : Number(order.fob_budget || 0);
            document.getElementById('modalFob').innerText = "৳" + bidVal.toFixed(2);
            document.getElementById('modalAppDate').innerText = order.created_at ? order.created_at.substring(0, 10) : 'N/A';

            // Specs & Merchandising
            document.getElementById('modalGarmentType').innerText = order.garment_item || order.category || 'N/A';
            document.getElementById('modalSpecQty').innerText = Number(order.target_quantity || 0).toLocaleString() + " Pcs";
            document.getElementById('modalSpecFob').innerText = "৳" + bidVal.toFixed(2);
            document.getElementById('modalStyleName').innerText = order.style_name || 'N/A';
            document.getElementById('modalSMV').innerText = order.smv ? order.smv + " Mins" : "N/A";
            document.getElementById('modalDescription').innerText = order.spec_description || 'No detailed specifications attached.';

            // Photos
            renderGallery('modalPhotosGallery', order.images_json);

            // Controls setup
            setupWorkflowControls(order.id, 'sourcing', order.shipment_status, order.payment_status);

            // Show
            auditModal.classList.remove('hidden');
            auditModal.classList.add('flex');
        }

        function openCapacityModal(post) {
            currentAuditItem = post;
            currentAuditType = 'capacity';

            document.getElementById('modalTitle').innerText = "Transaction Audit: Capacity Booking";
            document.getElementById('modalOrderNumber').innerText = post.order_number;
            document.getElementById('modalSubtext').innerText = "Style: " + (post.style_name || post.category || 'N/A');
            document.getElementById('modalCategoryBadge').innerText = "Capacity Space";

            // Production status badge
            const prodBadge = document.getElementById('modalProductionBadge');
            const prodStatus = post.production_status || 'Pending';
            if (prodStatus === 'In Production') {
                prodBadge.className = 'bg-amber-100 text-amber-800 border border-amber-300 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom';
                prodBadge.innerText = 'In Production';
            } else {
                prodBadge.className = 'bg-slate-100 text-slate-700 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom';
                prodBadge.innerText = prodStatus;
            }

            // Contacts
            document.getElementById('modalBuyerName').innerText = post.buyer_name || 'N/A';
            document.getElementById('modalBuyerEmail').innerText = post.buyer_email || 'N/A';
            document.getElementById('modalBuyerPhone').innerText = post.buyer_phone || 'Private';
            
            document.getElementById('modalSupplierFactory').innerText = post.factory_name || 'Apex Apparel Ltd.';
            document.getElementById('modalSupplierName').innerText = post.owner_name || 'N/A';
            document.getElementById('modalSupplierPhone').innerText = post.owner_phone || 'Private';
            
            // Financials
            const bookedQty = post.offered_quantity ? post.offered_quantity : post.quantity_capacity;
            document.getElementById('modalQty').innerText = Number(bookedQty || 0).toLocaleString() + " Pcs";
            const budgetVal = Number(post.target_budget || 0);
            document.getElementById('modalFob').innerText = "৳" + budgetVal.toFixed(2);
            document.getElementById('modalAppDate').innerText = post.created_at ? post.created_at.substring(0, 10) : 'N/A';

            // Specs & Merchandising
            document.getElementById('modalGarmentType').innerText = post.garment_item || post.category || 'N/A';
            document.getElementById('modalSpecQty').innerText = Number(bookedQty || 0).toLocaleString() + " Pcs";
            document.getElementById('modalSpecFob').innerText = "৳" + budgetVal.toFixed(2);
            document.getElementById('modalStyleName').innerText = post.style_name || 'N/A';
            document.getElementById('modalSMV').innerText = post.smv ? post.smv + " Mins" : "N/A";
            document.getElementById('modalDescription').innerText = post.spec_description || 'No detailed specifications attached.';

            // Photos
            renderGallery('modalPhotosGallery', post.sample_photos_json);

            // Controls setup
            setupWorkflowControls(post.id, 'capacity', post.shipment_status, post.payment_status);

            // Show
            auditModal.classList.remove('hidden');
            auditModal.classList.add('flex');
        }

        function renderGallery(containerId, photosJson) {
            const gallery = document.getElementById(containerId);
            gallery.innerHTML = '';
            let images = [];
            if (photosJson) {
                try {
                    if (typeof photosJson === 'string') {
                        const trimmed = photosJson.trim();
                        if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
                            const parsed = JSON.parse(trimmed);
                            images = Array.isArray(parsed) ? parsed : [parsed];
                        } else if (trimmed.includes(',')) {
                            images = trimmed.split(',').map(s => s.trim());
                        } else if (trimmed.length > 0) {
                            images = [trimmed];
                        }
                    } else if (Array.isArray(photosJson)) {
                        images = photosJson;
                    }
                } catch (e) {
                    if (typeof photosJson === 'string' && photosJson.trim().length > 0) {
                        images = [photosJson.trim()];
                    }
                }
            }
            if (Array.isArray(images) && images.length > 0) {
                images.slice(0, 4).forEach((imgUrl, i) => {
                    if (!imgUrl) return;
                    const imgEl = document.createElement('img');
                    imgEl.src = imgUrl;
                    imgEl.alt = `Sample Photo ${i + 1}`;
                    imgEl.className = 'w-full h-32 object-contain rounded-lg border border-slate-200 bg-slate-50 overflow-hidden';
                    gallery.appendChild(imgEl);
                });
            } else {
                gallery.innerHTML = '<p class="text-[11px] text-slate-400 italic col-span-4">No sample photos provided.</p>';
            }
        }

        function proceedToProduction() {
            if (!currentAuditItem || !currentAuditType) return;
            
            const btn = document.getElementById('btnProceedProduction');
            const label = document.getElementById('proceedBtnLabel');
            btn.disabled = true;
            label.innerText = 'Updating...';

            const formData = new FormData();
            formData.append('action_proceed_production', '1');
            formData.append('order_id', currentAuditItem.id);
            formData.append('order_type', currentAuditType);

            fetch('/admin/analysis.php', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    currentAuditItem.production_status = 'In Production';
                    const prodBadge = document.getElementById('modalProductionBadge');
                    prodBadge.className = 'bg-amber-100 text-amber-800 border border-amber-300 font-bold px-2 py-0.5 rounded text-[10px] uppercase font-mono-custom';
                    prodBadge.innerText = 'In Production';
                    label.innerText = 'In Production';
                    btn.className = 'bg-amber-700 text-white font-bold px-4 py-2 rounded-lg text-xs opacity-75 cursor-not-allowed flex items-center space-x-1.5';
                } else {
                    alert(data.message || 'Error updating production status.');
                    btn.disabled = false;
                    label.innerText = 'Proceed';
                }
            })
            .catch(err => {
                console.error(err);
                btn.disabled = false;
                label.innerText = 'Proceed';
            });
        }

        function openAgreementModal() {
            if (!currentAuditItem) return;

            const item = currentAuditItem;
            const isSourcing = (currentAuditType === 'sourcing');

            document.getElementById('agreeModalOrderNum').innerText = item.order_number;
            document.getElementById('agreeDocRef').innerText = item.order_number;
            
            document.getElementById('agreeBuyerName').innerText = item.buyer_name || 'N/A';
            document.getElementById('agreeBuyerFactory').innerText = item.buyer_factory_name || 'Buyer Enterprise';
            document.getElementById('agreeBuyerEmail').innerText = item.buyer_email || 'N/A';

            document.getElementById('agreeSupplierFactory').innerText = item.factory_name || 'Apex Apparel Ltd.';
            document.getElementById('agreeSupplierName').innerText = (isSourcing ? item.supplier_name : item.owner_name) || 'N/A';
            document.getElementById('agreeSupplierEmail').innerText = (isSourcing ? item.supplier_email : item.owner_email) || 'N/A';

            document.getElementById('agreeCategory').innerText = item.category || 'Woven Apparels';
            document.getElementById('agreeStyleName').innerText = item.style_name || 'N/A';
            document.getElementById('agreeSMV').innerText = item.smv ? item.smv + " Mins" : "N/A";

            const qty = isSourcing ? Number(item.target_quantity || 0) : Number(item.offered_quantity || item.quantity_capacity || 0);
            const fob = isSourcing ? (item.accepted_price ? Number(item.accepted_price) : Number(item.fob_budget || 0)) : Number(item.target_budget || 0);
            const total = qty * fob;

            document.getElementById('agreeQty').innerText = qty.toLocaleString() + " Pcs";
            document.getElementById('agreeFob').innerText = "৳" + fob.toFixed(2);
            document.getElementById('agreeTotalVal').innerText = "৳" + total.toFixed(2);

            document.getElementById('agreeSpecDesc').innerText = item.spec_description || 'No detailed specifications attached.';

            const photosJson = isSourcing ? item.images_json : item.sample_photos_json;
            renderGallery('agreePhotosGallery', photosJson);

            document.getElementById('sigBuyer').innerText = item.buyer_name ? `${item.buyer_name} (Buyer)` : 'Authorized Buyer';
            document.getElementById('sigSupplier').innerText = (isSourcing ? item.supplier_name : item.owner_name) ? `${isSourcing ? item.supplier_name : item.owner_name} (Factory)` : 'Authorized Factory';

            document.getElementById('agreementModal').classList.remove('hidden');
            document.getElementById('agreementModal').classList.add('flex');
        }

        function closeAgreementModal() {
            document.getElementById('agreementModal').classList.remove('flex');
            document.getElementById('agreementModal').classList.add('hidden');
        }

        function setupWorkflowControls(orderId, orderType, shipmentStatus, paymentStatus) {
            const shipContainer = document.getElementById('shipmentStatusContainer');
            const payContainer = document.getElementById('paymentStatusContainer');
            
            // Shipment Control
            if (shipmentStatus === 'Completed') {
                shipContainer.innerHTML = `
                    <div class="flex items-center space-x-1 bg-emerald-50 text-emerald-700 font-bold px-3 py-1 rounded border border-emerald-200 text-xs">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
                        </svg>
                        <span>Completed</span>
                    </div>
                `;
            } else {
                shipContainer.innerHTML = `
                    <form action="/admin/analysis.php" method="POST" class="m-0">
                        <input type="hidden" name="action_update_status" value="1">
                        <input type="hidden" name="order_id" value="${orderId}">
                        <input type="hidden" name="order_type" value="${orderType}">
                        <input type="hidden" name="field" value="shipment">
                        <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-3 py-1.5 rounded-lg text-xs transition cursor-pointer shadow-xs">
                            Mark Completed
                        </button>
                    </form>
                `;
            }

            // Payment Control
            if (paymentStatus === 'Completed') {
                payContainer.innerHTML = `
                    <div class="flex items-center space-x-1 bg-emerald-50 text-emerald-700 font-bold px-3 py-1 rounded border border-emerald-200 text-xs">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"></path>
                        </svg>
                        <span>Completed</span>
                    </div>
                `;
            } else {
                payContainer.innerHTML = `
                    <form action="/admin/analysis.php" method="POST" class="m-0">
                        <input type="hidden" name="action_update_status" value="1">
                        <input type="hidden" name="order_id" value="${orderId}">
                        <input type="hidden" name="order_type" value="${orderType}">
                        <input type="hidden" name="field" value="payment">
                        <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-3 py-1.5 rounded-lg text-xs transition cursor-pointer shadow-xs">
                            Mark Completed
                        </button>
                    </form>
                `;
            }
        }

        function closeModal() {
            auditModal.classList.remove('flex');
            auditModal.classList.add('hidden');
        }

        // Close on escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeModal();
            }
        });
    </script>
</body>
</html>
