<?php
// my_orders.php
require_once 'config.php';

// บังคับให้เข้าสู่ระบบก่อนเข้าใช้งานหน้านี้
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$alertMessage = "";

// คำแปลภาษาของหน้ารายการสั่งซื้อของฉัน
$orders_translations = [
    'th' => [
        'title' => '📦 รายการสั่งซื้อของฉัน',
        'desc' => 'ตรวจสอบสถานะ คำสั่งซื้อทั้งหมดของคุณจากร้านค้าในเครือ Noa Shop',
        'order_id' => 'หมายเลขสั่งซื้อ',
        'shop' => 'ร้านค้า',
        'product' => 'ชื่อสินค้า / รายละเอียด',
        'qty' => 'จำนวน',
        'total' => 'ยอดชำระสุทธิ',
        'status' => 'สถานะจัดส่ง',
        'date' => 'วันที่ทำรายการ',
        'action' => 'การจัดการ',
        'btn_cancel' => 'ยกเลิกคำสั่งซื้อ',
        'cancel_confirm' => 'คุณแน่ใจหรือไม่ที่จะยกเลิกและลบคำสั่งซื้อนี้?',
        'empty_orders' => 'คุณยังไม่มีประวัติการสั่งซื้อเสื้อผ้าในขณะนี้',
        'go_shopping' => 'ไปเลือกซื้อเสื้อผ้าแฟชั่นหน้าร้าน',
        'back_to_shop' => '← กลับหน้าร้านหลัก',
        'status_pending' => 'รอดำเนินการ (Pending)',
        'status_shipped' => 'จัดส่งแล้ว (Shipped)',
        'status_delivered' => 'ได้รับสินค้าแล้ว (Delivered)',
        'alert_cancel_success' => 'ยกเลิกคำสั่งซื้อและลบรายการสินค้าเรียบร้อยแล้ว!'
    ],
    'en' => [
        'title' => '📦 My Orders',
        'desc' => 'Track shipping statuses and view history for all your merchant purchases.',
        'order_id' => 'Order ID',
        'shop' => 'Shop Name',
        'product' => 'Product Details',
        'qty' => 'Qty',
        'total' => 'Total Paid',
        'status' => 'Status',
        'date' => 'Order Date',
        'action' => 'Actions',
        'btn_cancel' => 'Cancel Order',
        'cancel_confirm' => 'Are you sure you want to cancel and remove this order?',
        'empty_orders' => 'You do not have any order history yet.',
        'go_shopping' => 'Go shop trendy apparel now',
        'back_to_shop' => '← Back to store',
        'status_pending' => 'Pending Shipment',
        'status_shipped' => 'Shipped',
        'status_delivered' => 'Delivered',
        'alert_cancel_success' => 'Order cancelled and removed successfully!'
    ]
];
$ot = $orders_translations[$lang];

// จัดการการยกเลิกคำสั่งซื้อ (ลบออกถาวรจากหน้าจอ - Hard Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_order'])) {
    $orderId = (int)$_POST['order_id'];
    
    try {
        $stmtCheck = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ? AND status = 'Pending'");
        $stmtCheck->execute([$orderId, $userId]);
        $order = $stmtCheck->fetch();

        if ($order) {
            // ลบคำสั่งซื้อออกจากฐานข้อมูลเลย (หายไปเลยตามต้องการ)
            $stmtDelete = $pdo->prepare("DELETE FROM orders WHERE id = ?");
            $stmtDelete->execute([$orderId]);

            // หาตัวสินค้าเพื่อดึงสต็อกกลับคืนระบบ
            $fullProdName = $order['product_name'];
            $baseName = trim(explode('(', $fullProdName)[0]); // ดึงชื่อหลักก่อนวงเล็บตัวเลือกขนาด/สี

            $stmtFind = $pdo->prepare("SELECT id FROM products WHERE name_th = ? OR name_en = ? OR name = ?");
            $stmtFind->execute([$baseName, $baseName, $baseName]);
            $prodId = $stmtFind->fetchColumn();

            if ($prodId) {
                $stmtStock = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                $stmtStock->execute([$order['quantity'], $prodId]);
            }
            
            // ใช้ Post-Redirect-Get pattern เพื่อป้องกันส่งค่าซ้ำซ้อน
            header('Location: my_orders.php?cancelled=1');
            exit;
        }
    } catch (PDOException $e) {
        $alertMessage = "เกิดข้อผิดพลาด: " . $e->getMessage();
    }
}

if (isset($_GET['cancelled']) && $_GET['cancelled'] == 1) {
    $alertMessage = $ot['alert_cancel_success'];
}

// ดึงรายการคำสั่งซื้อของผู้ใช้คนนี้ และเชื่อมข้อมูลรูปภาพสินค้าจริง
try {
    $stmtOrders = $pdo->prepare("
        SELECT orders.*, shops.name AS shop_name, products.image AS product_image 
        FROM orders 
        LEFT JOIN shops ON orders.shop_id = shops.id 
        LEFT JOIN products ON orders.product_id = products.id
        WHERE orders.user_id = ? 
        ORDER BY orders.id DESC
    ");
    $stmtOrders->execute([$userId]);
    $myOrders = $stmtOrders->fetchAll();
} catch (PDOException $e) {
    $myOrders = [];
}

// จัดกลุ่มออเดอร์ตามสถานะแต่ละอัน
$groupedOrders = [
    'Pending' => [],
    'Shipped' => [],
    'Delivered' => []
];
foreach ($myOrders as $order) {
    if (isset($groupedOrders[$order['status']])) {
        $groupedOrders[$order['status']][] = $order;
    }
}

$hasAnyOrder = count($myOrders) > 0;
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= ($lang == 'th') ? 'รายการสั่งซื้อของฉัน' : 'My Orders' ?> - Noa Shop</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&family=Sarabun:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Outfit', 'Sarabun', sans-serif; }
        .gradient-brand { background: linear-gradient(135deg, #f59e0b 0%, #ee4d2d 100%); }
        .text-gradient {
            background: linear-gradient(135deg, #f59e0b 0%, #ee4d2d 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
    </style>
</head>
<body class="<?= $tc['bg'] ?> min-h-screen antialiased flex flex-col justify-between transition-colors duration-300">

    <!-- NAVIGATION BAR -->
    <nav class="sticky top-0 z-50 backdrop-blur-md <?= $tc['navbar'] ?> py-4 px-6">
        <div class="max-w-7xl mx-auto flex justify-between items-center">
            <a href="index.php" class="text-2xl font-black text-gradient hover:scale-105 transform transition duration-200">
                Noa Shop
            </a>

            <div class="flex items-center space-x-4 text-sm font-semibold">
                <!-- สลับภาษา -->
                <a href="index.php?action=toggle_lang" class="px-2.5 py-1 border border-slate-400/30 rounded-md text-xs hover:bg-amber-500 hover:text-white transition duration-200">
                    🌐 <?= strtoupper($lang) ?>
                </a>

                <!-- สลับธีม -->
                <a href="index.php?action=toggle_theme" class="p-1.5 border border-slate-400/30 rounded-md text-xs hover:bg-amber-500 hover:text-white transition duration-200">
                    <?= ($theme == 'light') ? '🌙 Dark Mode' : '☀️ Light Mode' ?>
                </a>

                <a href="index.php" class="text-xs hover:underline transition">
                    <?= $ot['back_to_shop'] ?>
                </a>
            </div>
        </div>
    </nav>

    <!-- MAIN GRID CONTAINER -->
    <main class="max-w-4xl mx-auto px-6 py-12 w-full flex-grow">
        
        <!-- Welcome header -->
        <header class="mb-8 text-center animate__animated animate__fadeIn">
            <h1 class="text-3xl font-black text-gradient uppercase tracking-tight"><?= $ot['title'] ?></h1>
            <p class="text-xs opacity-60 mt-2 max-w-md mx-auto"><?= $ot['desc'] ?></p>
        </header>

        <!-- Alert Notification -->
        <?php if ($alertMessage): ?>
            <div class="mb-8 p-4 rounded-2xl bg-emerald-500 text-white font-bold text-center shadow animate__animated animate__bounceIn text-xs">
                <?= htmlspecialchars($alertMessage) ?>
            </div>
        <?php endif; ?>

        <?php if (!$hasAnyOrder): ?>
            <!-- Empty state -->
            <div class="rounded-3xl p-12 text-center <?= $tc['card'] ?> max-w-lg mx-auto shadow animate__animated animate__fadeInUp">
                <span class="text-5xl block mb-4">🛍️</span>
                <h3 class="text-base font-bold mb-2"><?= $ot['empty_orders'] ?></h3>
                <a href="index.php" class="inline-block mt-4 gradient-brand hover:opacity-90 text-white font-bold text-xs px-6 py-3 rounded-xl shadow-md transition transform active:scale-95">
                    <?= $ot['go_shopping'] ?>
                </a>
            </div>
        <?php else: ?>
            
            <!-- วนลูปแสดงตามหัวข้อของสถานะแต่ละอัน (Grouped by status headers) -->
            <div class="space-y-12">
                
                <?php 
                $statusConfig = [
                    'Pending' => [
                        'label' => $ot['status_pending'],
                        'header_style' => 'text-amber-500 border-amber-500/20 bg-amber-500/5',
                        'badge_style' => 'bg-amber-50 text-amber-700 border border-amber-100 dark:bg-amber-950/20 dark:text-amber-400 dark:border-amber-900',
                        'icon' => '⏳'
                    ],
                    'Shipped' => [
                        'label' => $ot['status_shipped'],
                        'header_style' => 'text-blue-500 border-blue-500/20 bg-blue-500/5',
                        'badge_style' => 'bg-blue-50 text-blue-700 border border-blue-100 dark:bg-blue-950/20 dark:text-blue-400 dark:border-blue-900',
                        'icon' => '🚚'
                    ],
                    'Delivered' => [
                        'label' => $ot['status_delivered'],
                        'header_style' => 'text-emerald-500 border-emerald-500/20 bg-emerald-500/5',
                        'badge_style' => 'bg-emerald-50 text-emerald-700 border border-emerald-100 dark:bg-emerald-950/20 dark:text-emerald-400 dark:border-emerald-900',
                        'icon' => '🎉'
                    ]
                ];

                foreach ($groupedOrders as $statusKey => $ordersList): 
                    // แสดงผลหัวข้อของสถานะเฉพาะเมื่อมีสินค้าในสถานะนั้น
                    if (empty($ordersList)) continue;
                    
                    $cfg = $statusConfig[$statusKey];
                ?>
                    <div class="space-y-4 animate__animated animate__fadeInUp">
                        <!-- หัวข้อสถานะแต่ละอัน -->
                        <div class="flex items-center gap-2.5 px-4.5 py-3 rounded-2xl border font-bold text-xs uppercase tracking-wider <?= $cfg['header_style'] ?>">
                            <span><?= $cfg['icon'] ?></span>
                            <span><?= $cfg['label'] ?></span>
                            <span class="bg-current/10 px-2 py-0.5 rounded-full text-[10px] font-black opacity-80">
                                <?= count($ordersList) ?>
                            </span>
                        </div>

                        <!-- รายการสินค้าภายใต้สถานะนี้ -->
                        <div class="grid grid-cols-1 gap-4">
                            <?php foreach ($ordersList as $order): ?>
                                <div class="rounded-3xl p-5 <?= $tc['card'] ?> flex flex-col sm:flex-row items-start sm:items-center justify-between gap-5 hover:scale-[1.005] transform transition duration-300">
                                    
                                    <!-- ฝั่งข้อมูลสินค้าและรูปภาพ -->
                                    <div class="flex items-center gap-4.5 w-full">
                                        <!-- รูปภาพของสินค้าจริง -->
                                        <div class="w-20 h-20 rounded-2xl overflow-hidden bg-slate-200/50 border border-slate-300/10 shadow-inner flex-shrink-0 relative group-hover:scale-105 transition duration-300">
                                            <img src="<?= htmlspecialchars($order['product_image'] ?: 'https://images.unsplash.com/photo-1523381210434-271e8be1f52b?w=600') ?>" 
                                                 alt="Product Image" 
                                                 class="w-full h-full object-cover">
                                        </div>

                                        <!-- รายละเอียดออเดอร์ -->
                                        <div class="space-y-1.5 min-w-0 flex-grow">
                                            <div class="flex items-center gap-2.5 flex-wrap">
                                                <span class="bg-slate-500/10 text-[9px] font-mono font-bold px-2 py-0.5 rounded text-slate-500">
                                                    #ORD-<?= $order['id'] ?>
                                                </span>
                                                <span class="text-[10px] font-bold text-amber-500">
                                                    🏪 <?= htmlspecialchars($order['shop_name'] ?: 'Noa Shop General') ?>
                                                </span>
                                                <span class="text-[9px] opacity-45 font-mono">
                                                    <?= htmlspecialchars($order['created_at']) ?>
                                                </span>
                                            </div>
                                            
                                            <h3 class="text-xs font-black text-slate-800 dark:text-slate-100 tracking-tight leading-snug truncate pr-4">
                                                <?= htmlspecialchars($order['product_name']) ?>
                                            </h3>
                                            
                                            <div class="flex items-center gap-3.5 text-[10px] opacity-60 flex-wrap">
                                                 <span><?= $ot['qty'] ?>: <strong class="text-amber-500 font-black"><?= $order['quantity'] ?></strong> ชิ้น</span>
                                                 <span>|</span>
                                                 <span><?= $ot['total'] ?>: <strong class="text-amber-500 font-black">฿<?= number_format($order['total_price']) ?></strong></span>
                                                 <span>|</span>
                                                 <span class="text-blue-600 dark:text-blue-400 font-semibold">💳 <?= htmlspecialchars($order['payment_method'] ?? 'PromptPay') ?></span>
                                             </div>
                                        </div>
                                    </div>

                                    <!-- ฝั่งการยกเลิกออเดอร์และสถานะ -->
                                    <div class="flex sm:flex-col items-center sm:items-end justify-between sm:justify-center gap-3 flex-shrink-0 w-full sm:w-auto border-t sm:border-t-0 border-slate-500/10 pt-3 sm:pt-0">
                                        <span class="inline-block px-3 py-1 rounded-full text-[10px] font-bold shadow-sm <?= $cfg['badge_style'] ?>">
                                            <?= $ot['status_' . strtolower($statusKey)] ?>
                                        </span>

                                        <?php if ($statusKey === 'Pending'): ?>
                                            <form method="POST" action="my_orders.php" onsubmit="return confirm('<?= $ot['cancel_confirm'] ?>')">
                                                <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                                <button type="submit" name="cancel_order"
                                                        class="bg-red-500 hover:bg-red-650 text-white text-[10px] font-bold px-3.5 py-1.5 rounded-xl transition shadow-sm active:scale-95 cursor-pointer">
                                                    🗑️ <?= $ot['btn_cancel'] ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>

                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>

            </div>

        <?php endif; ?>

    </main>

    <!-- FOOTER -->
    <footer class="py-8 text-center text-xs <?= $tc['footer'] ?> transition-colors duration-300">
        <p class="font-bold text-amber-500 mb-1">Noa Shop Eco-System</p>
        <p class="opacity-50">© 2026 Noa Shop. Premium Streetwear & Minimalist Pre-Orders</p>
    </footer>

</body>
</html>
