<?php
// หลังบ้าน - จัดการออเดอร์และพิมพ์ใบส่งพัสดุ/ใบจัดของ (admin_orders.php)
require_once 'auth.php';
requireSellerLogin();
require_once 'config.php';


// 1. อัปเดตสถานะออเดอร์หากมีการส่งฟอร์มเข้ามา
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $orderId = intval($_POST['order_id'] ?? 0);
    $newStatus = $_POST['status'] ?? '';
    
    if ($orderId && in_array($newStatus, ['pending', 'processing', 'shipped', 'cancelled'])) {
        try {
            $stmtUpdate = $conn->prepare("UPDATE orders SET status = :status WHERE id = :id");
            $stmtUpdate->execute([':status' => $newStatus, ':id' => $orderId]);
            $_SESSION['msg'] = "อัปเดตสถานะออเดอร์ #ORD-$orderId เป็นสำเร็จแล้ว!";
        } catch (PDOException $e) {
            $_SESSION['err'] = "ไม่สามารถอัปเดตสถานะได้: " . $e->getMessage();
        }
    }
    header("Location: admin_orders.php?order_id=$orderId");
    exit;
}

$user = getCurrentUser();
$sellerId = $user['id'] ?? 0;
$isAdmin = isAdminLoggedIn();

try {
    if ($orderId > 0) {
        // --- 2.1 มุมมองสำหรับรายละเอียดของออเดอร์เดี่ยวเพื่อพิมพ์ใบแพ็กสินค้า ---
        if ($isAdmin) {
            $stmtOrder = $conn->prepare("SELECT * FROM orders WHERE id = :id");
            $stmtOrder->execute([':id' => $orderId]);
        } else {
            $stmtOrder = $conn->prepare("
                SELECT DISTINCT o.* 
                FROM orders o
                JOIN order_items oi ON o.id = oi.order_id
                JOIN product_variants pv ON oi.product_variant_id = pv.id
                JOIN products p ON pv.product_id = p.id
                WHERE o.id = :id AND p.seller_id = :seller_id
            ");
            $stmtOrder->execute([':id' => $orderId, ':seller_id' => $sellerId]);
        }
        $order = $stmtOrder->fetch();

        if (!$order) {
            die("ไม่พบรหัสออเดอร์ที่เลือกในระบบ หรือไม่มีสิทธิ์เข้าถึงออเดอร์นี้");
        }

        // ดึงรายการย่อยของออเดอร์นี้ (ถ้าเป็นผู้ขาย ดึงเฉพาะรายการสินค้าของร้านผู้ขาย)
        if ($isAdmin) {
            $stmtItems = $conn->prepare("
                SELECT oi.*, pv.sku
                FROM order_items oi
                LEFT JOIN product_variants pv ON oi.product_variant_id = pv.id
                WHERE oi.order_id = :order_id
            ");
            $stmtItems->execute([':order_id' => $orderId]);
        } else {
            $stmtItems = $conn->prepare("
                SELECT oi.*, pv.sku
                FROM order_items oi
                LEFT JOIN product_variants pv ON oi.product_variant_id = pv.id
                LEFT JOIN products p ON pv.product_id = p.id
                WHERE oi.order_id = :order_id AND p.seller_id = :seller_id
            ");
            $stmtItems->execute([':order_id' => $orderId, ':seller_id' => $sellerId]);
        }
        $orderItems = $stmtItems->fetchAll();

    } else {
        // --- 2.2 มุมมองรายการออเดอร์ในระบบ (ถ้าเป็นผู้ขาย ดึงเฉพาะออเดอร์ที่มีสินค้าของร้านตนเอง) ---
        if ($isAdmin) {
            $orders = $conn->query("SELECT * FROM orders ORDER BY id DESC")->fetchAll();
        } else {
            $stmtOrders = $conn->prepare("
                SELECT DISTINCT o.* 
                FROM orders o
                JOIN order_items oi ON o.id = oi.order_id
                JOIN product_variants pv ON oi.product_variant_id = pv.id
                JOIN products p ON pv.product_id = p.id
                WHERE p.seller_id = :seller_id
                ORDER BY o.id DESC
            ");
            $stmtOrders->execute([':seller_id' => $sellerId]);
            $orders = $stmtOrders->fetchAll();
        }
    }
} catch (PDOException $e) {
    die("เกิดข้อผิดพลาดในการดึงข้อมูลออเดอร์: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>จัดการคำสั่งซื้อและพิมพ์ใบแพ็ก - AMARA STUDIO Portal</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <!-- Header Navigation (จะถูกซ่อนอัตโนมัติเมื่อพิมพ์หน้ากระดาษ) -->
    <header class="no-print">
        <div class="nav-container">
            <a href="index.php" class="logo">AMARA<span>STUDIO</span></a>
            <span style="background: var(--dark); color: white; padding: 4px 10px; border-radius: 4px; font-size: 11px; font-weight: 700; letter-spacing: 1px;">PORTAL ADMIN</span>
            <ul class="nav-menu">
                <li style="display:flex; align-items:center; gap:8px; color: var(--text-muted); font-size:14px;">
                    <span>👤 <?= htmlspecialchars(getAdminName()) ?></span>
                </li>
                <li><a href="manual.php" class="nav-link" target="_blank">📖 คู่มือการใช้งาน</a></li>
                <li><a href="index.php" class="nav-link">หน้าร้านค้า</a></li>
                <li>
                    <a href="logout.php" class="nav-link" id="logout-btn"
                       style="color: var(--danger); font-weight: 600;"
                       onclick="return confirmLogout(event)">
                        🚪 ออกจากระบบ
                    </a>
                </li>
            </ul>
        </div>
    </header>

    <div class="container">
        <!-- Layout สองฝั่งซ่อนคอลัมน์ซ้ายอัตโนมัติเมื่อสั่งพิมพ์ -->
        <div class="admin-layout">
            
            <!-- แผง Sidebar นำทางหลังบ้าน (ซ่อนตอนพิมพ์) -->
            <aside class="admin-menu-sidebar no-print">
                <ul class="admin-menu-list">
                    <li class="admin-menu-item"><a href="admin.php">📊 แดชบอร์ดภาพรวม</a></li>
                    <li class="admin-menu-item"><a href="admin_product.php">➕ เพิ่มสินค้าใหม่ (Matrix Generator)</a></li>
                    <li class="admin-menu-item active"><a href="admin_orders.php">📦 จัดการออเดอร์ & ใบแพ็กของ</a></li>
                </ul>
            </aside>

            <!-- พื้นที่จัดการออเดอร์ -->
            <main>
                
                <?php if ($orderId > 0 && isset($order)): ?>
                    
                    <!-- ============================================== -->
                    <!-- มุมมองแสดงรายละเอียดคำสั่งซื้อ & พิมพ์ใบแพ็กของ -->
                    <!-- ============================================== -->
                    <div class="no-print" style="margin-bottom: 20px;">
                        <a href="admin_orders.php" style="color: var(--text-muted); text-decoration: none; font-weight: 600;">← ย้อนกลับไปคำสั่งซื้อทั้งหมด</a>
                    </div>

                    <?php if (isset($_SESSION['msg'])): ?>
                        <div class="no-print" style="background-color: #dcfce7; border:1px solid #bbf7d0; color: #16a34a; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                            <?= htmlspecialchars($_SESSION['msg']); unset($_SESSION['msg']); ?>
                        </div>
                    <?php endif; ?>

                    <div class="admin-card">
                        
                        <!-- เมนูดำเนินการสำหรับหน้าเว็บปกติ (ไม่แสดงตอนพิมพ์) -->
                        <div class="no-print" style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 20px; margin-bottom: 20px;">
                            <div>
                                <h2 style="font-size: 20px; font-weight: 700;">จัดการคำสั่งซื้อ #ORD-<?= $order['id'] ?></h2>
                                <span style="font-size: 13px; color: var(--text-muted);">วันที่สั่งซื้อ: <?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></span>
                            </div>
                            
                            <div style="display: flex; gap: 15px; align-items: center;">
                                <!-- ฟอร์มอัปเดตสถานะการทำงาน -->
                                <form action="admin_orders.php" method="POST" style="display: flex; align-items: center; gap: 10px;">
                                    <input type="hidden" name="action" value="update_status">
                                    <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                    <select name="status" style="padding: 10px; border-radius: 8px; border: 1px solid var(--border); font-weight: 600;">
                                        <option value="pending" <?= $order['status'] === 'pending' ? 'selected' : '' ?>>รอเตรียมส่ง</option>
                                        <option value="processing" <?= $order['status'] === 'processing' ? 'selected' : '' ?>>กำลังแพ็กของ</option>
                                        <option value="shipped" <?= $order['status'] === 'shipped' ? 'selected' : '' ?>>จัดส่งแล้ว</option>
                                        <option value="cancelled" <?= $order['status'] === 'cancelled' ? 'selected' : '' ?>>ยกเลิกออเดอร์</option>
                                    </select>
                                    <button type="submit" class="btn btn-dark" style="padding: 10px 15px;">อัปเดต</button>
                                </form>

                                <button type="button" class="btn btn-primary" onclick="window.print()">
                                    🖨️ พิมพ์ใบแพ็กพัสดุ (Packing Slip)
                                </button>
                            </div>
                        </div>

                        <!-- ============================================== -->
                        <!-- เริ่มพิมพ์โครงใบจัดและแพ็กสินค้า (Packing Slip) -->
                        <!-- ============================================== -->
                        <div class="packing-slip-header">
                            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                                <div>
                                    <h1 style="font-size: 28px; font-weight: 800; font-family: var(--font-eng); margin: 0; letter-spacing: 0.5px;">AMARA STUDIO</h1>
                                    <p style="font-size: 13px; color: var(--text-muted); margin-top: 4px;">ใบจัดรายการเตรียมพัสดุ (Packing Slip)</p>
                                </div>
                                <div style="text-align: right;">
                                    <h2 style="margin: 0; font-size: 20px;">เลขสั่งซื้อ: <strong>#ORD-<?= $order['id'] ?></strong></h2>
                                    <span style="font-size: 13px; color: var(--text-muted);">วันที่พิมพ์: <?= date('d/m/Y H:i') ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- ข้อมูลที่อยู่จัดส่งพัสดุ (เน้นกล่องที่อยู่อ่านง่ายขนาดใหญ่) -->
                        <div style="background-color: var(--light); border: 2px solid var(--border); border-radius: 8px; padding: 20px; margin-top: 25px; margin-bottom: 30px;">
                            <h3 style="font-size: 15px; font-weight: 700; margin-bottom: 8px; color: var(--dark); text-transform: uppercase;">ชื่อและที่อยู่จัดส่งสินค้า (Recipient Address):</h3>
                            <p style="font-size: 18px; font-weight: 700; color: #000; line-height: 1.5; margin-bottom: 5px;">ผู้รับ: <?= htmlspecialchars($order['customer_name']) ?></p>
                            <p style="font-size: 16px; color: #1a202c; line-height: 1.6; white-space: pre-wrap; font-weight: 500;"><?= htmlspecialchars($order['shipping_address']) ?></p>
                        </div>

                        <h3 style="font-size: 16px; font-weight: 700; margin-bottom: 15px; border-bottom: 2px solid var(--dark); padding-bottom: 5px; color: var(--dark);">
                            รายการเสื้อผ้าที่ต้องจัดเตรียม (Pick List Items)
                        </h3>

                        <!-- รายการสินค้าเสื้อผ้า (เน้นไซซ์สีตัวหนาใหญ่อ่านง่าย) -->
                        <div>
                            <?php foreach ($orderItems as $item): ?>
                                <?php 
                                $details = json_decode($item['variant_details'], true);
                                $colorName = $details['Color'] ?? '-';
                                $sizeName = $details['Size'] ?? '-';
                                ?>
                                <div class="packing-slip-item" style="border-bottom: 2px dashed var(--border); padding: 20px 0; display: flex; justify-content: space-between; align-items: center;">
                                    <div style="max-width: 60%;">
                                        <h4 style="font-size: 17px; font-weight: 700; margin: 0; color: #000;"><?= htmlspecialchars($item['product_name']) ?></h4>
                                        <span style="font-size: 13px; color: var(--text-muted); display: block; margin-top: 4px;">รหัส SKU: <strong><?= htmlspecialchars($item['sku'] ?? 'N/A') ?></strong></span>
                                        
                                        <!-- จุดเน้นย้ำพิเศษ: ขนาดตัวอักษรใหญ่ ตัวหนามาก กรอบหนา มีสีพื้นหลังสะดุดสายตาพนักงานแพ็กของ -->
                                        <div class="print-bold-details" style="border: 2.5px solid #000; background-color: #f1f5f9; padding: 6px 12px; border-radius: 6px; display: inline-flex; align-items: center; gap: 10px; margin-top: 10px;">
                                            <span style="font-size: 14px; font-weight: 600; color: #334155;">สี: <strong style="font-size: 20px; font-weight: 900; color: #000; text-decoration: underline;"><?= htmlspecialchars($colorName) ?></strong></span>
                                            <span style="font-size: 18px; color: #cbd5e1;">|</span>
                                            <span style="font-size: 14px; font-weight: 600; color: #334155;">ไซซ์: <strong style="font-size: 24px; font-weight: 900; color: #000; background-color: #000; color: #fff; padding: 2px 8px; border-radius: 4px;"><?= htmlspecialchars($sizeName) ?></strong></span>
                                        </div>
                                    </div>
                                    
                                    <div style="text-align: right;">
                                        <div style="font-size: 15px; color: var(--text-muted); margin-bottom: 5px;">จำนวนที่ต้องการ</div>
                                        <div style="font-size: 26px; font-weight: 900; color: #000; text-decoration: underline; text-underline-offset: 4px;">
                                            x <?= $item['quantity'] ?> ชิ้น
                                        </div>
                                        <div style="font-size: 14px; font-weight: 600; color: var(--text-muted); margin-top: 5px;">ราคาต่อชิ้น: ฿<?= number_format($item['price']) ?></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- สรุปราคารวมท้ายใบงาน -->
                        <div style="margin-top: 30px; text-align: right;">
                            <p style="font-size: 14px; color: var(--text-muted); margin-bottom: 5px;">ยอดชำระเงินสุทธิ (รวมค่าส่งฟรี)</p>
                            <h2 style="font-size: 24px; font-weight: 800; color: #000;">ยอดเงินรวม: ฿<?= number_format($order['total_amount']) ?></h2>
                        </div>

                    </div>

                <?php else: ?>
                    
                    <!-- ============================================== -->
                    <!-- มุมมองรายการออเดอร์ทั้งหมดในระบบหลังบ้าน -->
                    <!-- ============================================== -->
                    <h1 style="margin-bottom: 25px; font-size: 24px; font-weight: 700;">จัดการคำสั่งซื้อของลูกค้า</h1>

                    <div class="admin-card">
                        <table class="admin-table">
                            <thead>
                                <tr>
                                    <th>รหัสออเดอร์</th>
                                    <th>ชื่อลูกค้า</th>
                                    <th>ที่อยู่จัดส่งย่อ</th>
                                    <th>ยอดสุทธิ</th>
                                    <th>สถานะดำเนินงาน</th>
                                    <th>วันที่ส่งซื้อ</th>
                                    <th>การจัดการ</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($orders)): ?>
                                    <tr>
                                        <td colspan="7" style="text-align: center; color: var(--text-muted); padding: 40px 10px;">ไม่มีออเดอร์จากลูกค้าเข้ามาในระบบในขณะนี้</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($orders as $ord): ?>
                                        <tr>
                                            <td><strong>#ORD-<?= $ord['id'] ?></strong></td>
                                            <td><strong><?= htmlspecialchars($ord['customer_name']) ?></strong></td>
                                            <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                                <?= htmlspecialchars($ord['shipping_address']) ?>
                                            </td>
                                            <td>฿<?= number_format($ord['total_amount']) ?></td>
                                            <td>
                                                <span class="badge <?= $ord['status'] ?>">
                                                    <?= $ord['status'] === 'pending' ? 'รอเตรียมส่ง' : 
                                                       ($ord['status'] === 'processing' ? 'กำลังแพ็กของ' : 
                                                       ($ord['status'] === 'shipped' ? 'จัดส่งแล้ว' : 'ยกเลิกออเดอร์')) ?>
                                                </span>
                                            </td>
                                            <td><?= date('d/m/Y H:i', strtotime($ord['created_at'])) ?></td>
                                            <td>
                                                <a href="admin_orders.php?order_id=<?= $ord['id'] ?>" class="btn btn-dark" style="padding: 6px 12px; font-size: 13px;">
                                                    🔎 จัดการ & พิมพ์ใบแพ็ก
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                <?php endif; ?>

            </main>

        </div>
    </div>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function confirmLogout(e) {
            e.preventDefault();
            Swal.fire({
                title: 'ออกจากระบบ?',
                text: 'ต้องการออกจากระบบผู้ดูแลใช่หรือไม่?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#e53e3e',
                cancelButtonColor: '#718096',
                confirmButtonText: 'ออกจากระบบ',
                cancelButtonText: 'ยกเลิก'
            }).then((result) => {
                if (result.isConfirmed) window.location.href = 'logout.php';
            });
        }
    </script>
</body>
</html>
