<?php
// Tab configuration
$tabs = [
    'all'        => ['label' => 'ทั้งหมด',        'icon' => 'bi-grid-3x3-gap'],
    'to_pay'     => ['label' => 'รอชำระเงิน',     'icon' => 'bi-wallet2'],
    'to_receive' => ['label' => 'รอรับสินค้า',    'icon' => 'bi-box-seam'],
    'delivered'  => ['label' => 'จัดส่งแล้ว',     'icon' => 'bi-patch-check-fill'],
    'cancelled'  => ['label' => 'ยกเลิก',          'icon' => 'bi-x-circle'],
];
$emptyMessages = [
    'all'        => ['icon' => 'bi-bag-x',            'text' => 'คุณยังไม่มีคำสั่งซื้อ'],
    'to_pay'     => ['icon' => 'bi-wallet2',          'text' => 'ไม่มีออเดอร์ที่รอชำระเงิน'],
    'to_receive' => ['icon' => 'bi-box-seam',         'text' => 'ไม่มีออเดอร์ที่รอรับสินค้า'],
    'delivered'  => ['icon' => 'bi-patch-check-fill', 'text' => 'ยังไม่มีสินค้าที่จัดส่งสำเร็จ'],
    'cancelled'  => ['icon' => 'bi-x-circle',         'text' => 'ไม่มีรายการที่ถูกยกเลิก'],
];
$emptyMsg = $emptyMessages[$activeTab] ?? $emptyMessages['all'];
?>

<style>
.order-tab-bar { display: flex; overflow-x: auto; gap: 0; border-bottom: 2px solid #e9ecef; margin-bottom: 0; scrollbar-width: none; }
.order-tab-bar::-webkit-scrollbar { display: none; }
.order-tab-btn { flex-shrink: 0; display: flex; align-items: center; gap: 6px; padding: 12px 20px; font-size: .9rem; font-weight: 600; color: #6c757d; text-decoration: none; border-bottom: 3px solid transparent; margin-bottom: -2px; white-space: nowrap; transition: color .15s, border-color .15s; }
.order-tab-btn:hover { color: #0d6efd; }
.order-tab-btn.active { color: #0d6efd; border-bottom-color: #0d6efd; }
.order-tab-count { font-size: .72rem; padding: 2px 7px; border-radius: 20px; background: #e9ecef; color: #495057; font-weight: 700; }
.order-tab-btn.active .order-tab-count { background: #0d6efd; color: #fff; }
</style>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3 class="fw-bold m-0"><i class="bi bi-bag-check text-primary me-2"></i>ติดตามคำสั่งซื้อของฉัน</h3>
    </div>

    <!-- Tab Bar -->
    <div class="card border-0 shadow-sm rounded-top-4 overflow-hidden mb-4">
        <div class="order-tab-bar px-2 pt-2 bg-white">
            <?php foreach ($tabs as $tabKey => $tabInfo): ?>
            <a href="<?= APP_URL ?>/orders?tab=<?= $tabKey ?>" class="order-tab-btn <?= $activeTab === $tabKey ? 'active' : '' ?>">
                <i class="bi <?= $tabInfo['icon'] ?> fs-5"></i>
                <?= $tabInfo['label'] ?>
                <?php if (($tabCounts[$tabKey] ?? 0) > 0): ?>
                    <span class="order-tab-count"><?= $tabCounts[$tabKey] ?></span>
                <?php endif; ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>

    <?php if (empty($orders)): ?>
        <div class="card border-0 shadow-sm p-5 text-center rounded-4">
            <i class="bi <?= $emptyMsg['icon'] ?> text-muted display-1 mb-3 d-block"></i>
            <h5 class="fw-bold"><?= $emptyMsg['text'] ?></h5>
            <p class="text-muted">เลือกซื้อสินค้าโปรดของคุณและทำการสั่งซื้อได้ง่ายๆ</p>
            <div class="mt-3">
                <a href="<?= APP_URL ?>/products" class="btn btn-primary px-4 py-2 rounded-pill fw-bold">ไปที่หน้ารวมสินค้า</a>
            </div>
        </div>
    <?php else: ?>
        <div class="d-flex flex-column gap-4">
            <?php foreach ($orders as $ord): ?>
                <?php
                if ($ord['status'] === 'paid') {
                    $statusBadge = 'bg-success-subtle text-success border border-success-subtle';
                    $statusText = 'ชำระเงินแล้ว';
                } elseif ($ord['status'] === 'shipping') {
                    $statusBadge = 'bg-info-subtle text-info-emphasis border border-info-subtle';
                    $statusText = 'กำลังจัดส่ง';
                } elseif ($ord['status'] === 'delivered' || $ord['status'] === 'completed') {
                    $statusBadge = 'bg-success text-white';
                    $statusText = 'จัดส่งสำเร็จ';
                } elseif ($ord['status'] === 'cancelled') {
                    $statusBadge = 'bg-danger-subtle text-danger border border-danger-subtle';
                    $statusText = 'ยกเลิกแล้ว';
                } else {
                    $statusBadge = 'bg-warning-subtle text-warning-emphasis border border-warning-subtle';
                    $statusText = ucfirst($ord['status']);
                }
                ?>
                <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                    <!-- Order Card Header -->
                    <div class="card-header bg-light bg-gradient px-4 py-3 border-0 d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <div class="d-flex align-items-center flex-wrap gap-2">
                            <span class="badge bg-white text-dark border px-2 py-1 rounded"><i class="bi bi-shop me-1 text-primary"></i><?= Security::e($ord['shop_name']) ?></span>
                            <span class="text-muted small">| เลขที่: <strong class="text-dark">#<?= Security::e($ord['order_number']) ?></strong></span>
                            <span class="text-muted small d-none d-md-inline">| สั่งเมื่อ: <?= date('d/m/Y H:i', strtotime($ord['created_at'])) ?></span>
                            
                            <!-- Payment Method Badge -->
                            <?php if (($ord['payment_method'] ?? 'prepaid') === 'cod'): ?>
                                <span class="badge bg-warning text-dark border border-warning px-2 py-1 rounded-pill small">
                                    <i class="bi bi-cash me-1"></i>เก็บเงินปลายทาง (COD)
                                </span>
                            <?php else: ?>
                                <span class="badge bg-info-subtle text-primary border border-primary-subtle px-2 py-1 rounded-pill small">
                                    <i class="bi bi-credit-card me-1"></i>ชำระเงินต้นทาง (Prepaid)
                                </span>
                            <?php endif; ?>
                        </div>
                        <div>
                            <span class="badge <?= $statusBadge ?> px-3 py-2 rounded-pill fw-semibold"><i class="bi bi-truck me-1"></i><?= $statusText ?></span>
                        </div>
                    </div>

                    <!-- Order Items Body -->
                    <div class="card-body p-4">
                        <div class="d-flex flex-column gap-3">
                            <?php foreach ($ord['items'] as $item): ?>
                                <?php
                                $imgSrc = !empty($item['primary_image']) ? APP_URL . '/public/' . ltrim(Security::e($item['primary_image']), '/') : APP_URL . '/public/images/no-image.png';
                                ?>
                                <div class="d-flex align-items-center justify-content-between flex-wrap gap-3 pb-3 border-bottom last-border-none">
                                    <div class="d-flex align-items-center gap-3" style="min-width: 280px; flex: 1;">
                                        <img src="<?= $imgSrc ?>" alt="<?= Security::e($item['title']) ?>" class="rounded-3 border object-fit-cover" style="width: 75px; height: 75px;">
                                        <div>
                                            <a href="<?= APP_URL ?>/product/<?= $item['slug'] ?>" class="text-decoration-none fw-bold text-dark h6 mb-1 d-block hover-primary">
                                                <?= Security::e($item['title']) ?>
                                            </a>
                                            <?php if (!empty($item['variant_info'])): ?>
                                                <span class="badge bg-light text-secondary border small mb-1"><?= Security::e($item['variant_info']) ?></span>
                                            <?php endif; ?>
                                            <div class="small text-muted">จำนวน: x<?= $item['quantity'] ?></div>
                                        </div>
                                    </div>
                                    <div class="text-end ms-auto">
                                        <div class="fw-bold text-primary fs-5">฿<?= number_format($item['subtotal'], 2) ?></div>
                                        <div class="small text-muted">฿<?= number_format($item['price'], 2) ?> / ชิ้น</div>
                                    </div>

                                    <!-- Item Level Review Button -->
                                    <div class="w-100 w-md-auto text-end mt-2 mt-md-0">
                                        <?php if (!empty($item['review'])): ?>
                                            <div class="d-flex align-items-center justify-content-end gap-2">
                                                <span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-3 py-1 small">
                                                    <i class="bi bi-star-fill text-warning me-1"></i><?= $item['review']['rating'] ?>/5 รีวิวแล้ว
                                                </span>
                                                <button type="button" 
                                                        class="btn btn-sm btn-outline-secondary rounded-pill px-3 btn-open-review"
                                                        data-order-id="<?= $ord['id'] ?>"
                                                        data-item-id="<?= $item['id'] ?>"
                                                        data-product-title="<?= Security::e($item['title']) ?>"
                                                        data-rating="<?= $item['review']['rating'] ?>"
                                                        data-comment="<?= Security::e($item['review']['comment'] ?? '') ?>">
                                                    <i class="bi bi-pencil me-1"></i>แก้ไข
                                                </button>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" 
                                                    class="btn btn-sm btn-warning text-dark fw-bold rounded-pill px-3 btn-open-review"
                                                    data-order-id="<?= $ord['id'] ?>"
                                                    data-item-id="<?= $item['id'] ?>"
                                                    data-product-title="<?= Security::e($item['title']) ?>"
                                                    data-rating="5"
                                                    data-comment="">
                                                <i class="bi bi-star-fill me-1"></i>เขียนรีวิว
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Order Card Footer -->
                    <div class="card-footer bg-white px-4 py-3 border-0 d-flex justify-content-between align-items-center flex-wrap gap-2 border-top">
                        <div class="d-flex align-items-center flex-wrap gap-3">
                            <div>
                                <span class="text-muted small">ราคารวมสุทธิ:</span>
                                <span class="fs-4 fw-bold text-primary ms-1">฿<?= number_format($ord['total_amount'], 2) ?></span>
                            </div>
                            <?php if (($ord['payment_method'] ?? '') === 'cod'): ?>
                                <span class="badge bg-warning-subtle text-dark border border-warning px-3 py-1 rounded-pill small">
                                    <i class="bi bi-cash-coin me-1"></i>
                                    <?= ($ord['payment_status'] ?? '') === 'paid' ? 'ชำระเงินปลายทางแล้ว' : 'รอชำระเงินสดปลายทาง: ฿' . number_format($ord['total_amount'], 2) ?>
                                </span>
                            <?php else: ?>
                                <span class="badge bg-success-subtle text-success border border-success-subtle px-3 py-1 rounded-pill small">
                                    <i class="bi bi-check-circle-fill me-1"></i>ชำระเงินต้นทางแล้ว
                                </span>
                            <?php endif; ?>
                        </div>
                        <div class="d-flex gap-2">
                            <a href="<?= APP_URL ?>/orders/<?= $ord['id'] ?>" class="btn btn-outline-primary rounded-pill px-4 btn-sm fw-bold">
                                <i class="bi bi-file-text me-1"></i>ดูรายละเอียดคำสั่งซื้อ
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Modal เขียน / แก้ไขรีวิว -->
<div class="modal fade" id="reviewModal" tabindex="-1" aria-labelledby="reviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
            <form action="<?= APP_URL ?>/orders/review" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
                <input type="hidden" name="order_id" id="modalOrderId" value="">
                <input type="hidden" name="order_item_id" id="modalItemId" value="">
                <input type="hidden" name="rating" id="modalRatingInput" value="5">

                <div class="modal-header bg-warning bg-gradient text-dark border-0 py-3">
                    <h5 class="modal-title fw-bold" id="reviewModalLabel"><i class="bi bi-star-fill me-2"></i>ให้คะแนนและรีวิวสินค้า</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body p-4">
                    <div class="mb-3 text-center">
                        <h6 class="fw-bold text-dark mb-1" id="modalProductTitle">ชื่อสินค้า</h6>
                        <p class="small text-muted mb-0">แชร์ประสบการณ์และการใช้งานของคุณเพื่อช่วยผู้ซื้อท่านอื่น</p>
                    </div>

                    <!-- Interactive Star Picker -->
                    <div class="mb-4 text-center p-3 bg-light rounded-3">
                        <label class="form-label d-block fw-semibold mb-2">คะแนนคุณภาพสินค้า</label>
                        <div class="star-rating-select d-inline-flex gap-2 fs-1 cursor-pointer" id="starContainer">
                            <i class="bi bi-star-fill text-warning star-btn" data-value="1"></i>
                            <i class="bi bi-star-fill text-warning star-btn" data-value="2"></i>
                            <i class="bi bi-star-fill text-warning star-btn" data-value="3"></i>
                            <i class="bi bi-star-fill text-warning star-btn" data-value="4"></i>
                            <i class="bi bi-star-fill text-warning star-btn" data-value="5"></i>
                        </div>
                        <div class="small fw-bold text-warning mt-2 fs-6" id="starLabel">5/5 - ดีมาก</div>
                    </div>

                    <!-- Comment input -->
                    <div class="mb-3">
                        <label for="reviewComment" class="form-label fw-semibold">ความคิดเห็น / ข้อเสนอแนะ</label>
                        <textarea class="form-control rounded-3" id="reviewComment" name="comment" rows="4" placeholder="เขียนรีวิวเกี่ยวกับสินค้า ความคุ้มค่า การแพ็คสินค้า การจัดส่ง..."></textarea>
                    </div>

                    <!-- Photos Upload -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">อัปโหลดรูปถ่ายสินค้าจริง (ไม่เกิน 5 รูป)</label>
                        <input type="file" class="form-control rounded-3" name="images[]" multiple accept="image/*">
                        <div class="form-text small text-muted">รองรับไฟล์ JPG, PNG, WEBP</div>
                    </div>
                </div>

                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal">ยกเลิก</button>
                    <button type="submit" class="btn btn-warning text-dark fw-bold rounded-pill px-4"><i class="bi bi-send-fill me-1"></i>บันทึกรีวิว</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.last-border-none:last-child {
    border-bottom: 0 !important;
    padding-bottom: 0 !important;
}
.star-btn {
    transition: transform 0.15s ease-in-out;
    cursor: pointer;
}
.star-btn:hover {
    transform: scale(1.25);
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const reviewModalEl = document.getElementById('reviewModal');
    const reviewModal = new bootstrap.Modal(reviewModalEl);
    const modalOrderId = document.getElementById('modalOrderId');
    const modalItemId = document.getElementById('modalItemId');
    const modalProductTitle = document.getElementById('modalProductTitle');
    const modalRatingInput = document.getElementById('modalRatingInput');
    const reviewComment = document.getElementById('reviewComment');
    const starBtns = document.querySelectorAll('.star-btn');
    const starLabel = document.getElementById('starLabel');

    const starTexts = {
        1: '1/5 - ปรับปรุง',
        2: '2/5 - พอใช้',
        3: '3/5 - ปานกลาง',
        4: '4/5 - ดี',
        5: '5/5 - ดีมาก'
    };

    function updateStars(val) {
        modalRatingInput.value = val;
        starLabel.textContent = starTexts[val] || (val + '/5');
        starBtns.forEach(btn => {
            const btnVal = parseInt(btn.getAttribute('data-value'));
            if (btnVal <= val) {
                btn.classList.remove('text-muted', 'opacity-25');
                btn.classList.add('text-warning');
            } else {
                btn.classList.remove('text-warning');
                btn.classList.add('text-muted', 'opacity-25');
            }
        });
    }

    starBtns.forEach(btn => {
        btn.addEventListener('click', function () {
            const val = parseInt(this.getAttribute('data-value'));
            updateStars(val);
        });
    });

    document.querySelectorAll('.btn-open-review').forEach(btn => {
        btn.addEventListener('click', function () {
            modalOrderId.value = this.getAttribute('data-order-id');
            modalItemId.value = this.getAttribute('data-item-id');
            modalProductTitle.textContent = this.getAttribute('data-product-title');
            reviewComment.value = this.getAttribute('data-comment') || '';
            const initialRating = parseInt(this.getAttribute('data-rating')) || 5;
            updateStars(initialRating);
            reviewModal.show();
        });
    });
});
</script>
