<?php
require_once __DIR__ . '/header.php';

$product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$product_id) {
    header('Location: index.php');
    exit;
}

// 1. ดึงรายละเอียดสินค้า
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();

if (!$product) {
    echo "<div class='alert alert-danger my-5 text-center'>ไม่พบสินค้าที่ต้องการ</div>";
    require_once __DIR__ . '/footer.php';
    exit;
}

// 2. ดึงเฉดสีเพิ่มเติม (variants)
$stmt_var = $pdo->prepare("SELECT * FROM product_variants WHERE product_id = ? ORDER BY id ASC");
$stmt_var->execute([$product_id]);
$variants = $stmt_var->fetchAll();

// 3. ดึงไซส์
$sizes_list = [];
if (!empty($product['sizes'])) {
    $decoded = json_decode($product['sizes'], true);
    if (is_array($decoded)) {
        $sizes_list = $decoded;
    }
}

$default_front = get_product_image_url($product['image']);
$default_back = !empty($product['image_back']) ? get_product_image_url($product['image_back']) : '';
?>

<!-- นำทางด่วน (Breadcrumb) -->
<nav aria-label="breadcrumb" class="mb-4">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none text-muted">หน้าร้านค้า</a></li>
        <li class="breadcrumb-item active text-dark fw-medium" aria-current="page"><?= htmlspecialchars($product['name']) ?></li>
    </ol>
</nav>

<div class="row g-5 mb-5">
    
    <!-- ── คอลัมน์ซ้าย: แกลเลอรีรูปภาพสินค้า ── -->
    <div class="col-md-6">
        <!-- กรอบรูปภาพใหญ่ (รองรับการสลับหน้าหลังเมื่อโฮเวอร์) -->
        <div class="product-detail-img-box rounded-4 overflow-hidden border shadow-sm position-relative mb-3 bg-light d-flex align-items-center justify-content-center"
             style="height: 480px; cursor: zoom-in;"
             onmouseenter="hoverDetailImage(true)"
             onmouseleave="hoverDetailImage(false)">
            
            <img id="detail_main_img" 
                 src="<?= htmlspecialchars($default_front) ?>" 
                 data-front="<?= htmlspecialchars($default_front) ?>"
                 data-back="<?= htmlspecialchars($default_back) ?>"
                 style="max-height: 460px; max-width: 100%; object-fit: contain; transition: transform 0.3s ease;"
                 alt="<?= htmlspecialchars($product['name']) ?>">
                 
            <?php if (!empty($default_back)): ?>
                <span class="badge bg-dark opacity-75 position-absolute bottom-0 end-0 m-3 small rounded-pill">
                    <i class="fa-solid fa-arrows-rotate me-1"></i> โฮเวอร์เพื่อดูรูปหลัง
                </span>
            <?php endif; ?>
        </div>

        <!-- รายการรูปภาพขนาดเล็ก (Thumbnails) -->
        <?php if (!empty($variants) || !empty($default_back)): ?>
            <div class="d-flex gap-2 overflow-auto py-2" id="detail_thumbnails_container">
                <!-- รูปเริ่มต้น -->
                <div class="detail-thumb border rounded-3 p-1 active" style="width: 70px; height: 70px; cursor: pointer; display: flex; align-items: center; justify-content: center; background:#fff;"
                     onclick="setDetailMainImage('<?= htmlspecialchars($default_front) ?>', '<?= htmlspecialchars($default_back) ?>', 'เริ่มต้น', this)">
                    <img src="<?= htmlspecialchars($default_front) ?>" style="max-height: 60px; max-width: 100%; object-fit: contain;">
                </div>
                <!-- รูปเฉดสีต่างๆ -->
                <?php foreach ($variants as $var): ?>
                    <?php 
                    $v_front = get_product_image_url($var['image_front']);
                    $v_back = !empty($var['image_back']) ? get_product_image_url($var['image_back']) : '';
                    ?>
                    <div class="detail-thumb border rounded-3 p-1" style="width: 70px; height: 70px; cursor: pointer; display: flex; align-items: center; justify-content: center; background:#fff;"
                         onclick="setDetailMainImage('<?= htmlspecialchars($v_front) ?>', '<?= htmlspecialchars($v_back) ?>', '<?= htmlspecialchars($var['color_name']) ?>', this)">
                        <img src="<?= htmlspecialchars($v_front) ?>" style="max-height: 60px; max-width: 100%; object-fit: contain;">
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- ── คอลัมน์ขวา: รายละเอียดและการสั่งซื้อ ── -->
    <div class="col-md-6">
        <div class="d-flex flex-column h-100">
            <!-- หัวข้อสินค้า -->
            <h1 class="fw-bold text-dark mb-2"><?= htmlspecialchars($product['name']) ?></h1>
            
            <!-- สถานะสต็อกสินค้า -->
            <div class="mb-3">
                <?php if ($product['stock'] > 0): ?>
                    <span class="badge bg-success rounded-pill px-3 py-2 fw-semibold">
                        <i class="fa-solid fa-circle-check me-1"></i> มีสินค้าพร้อมส่ง (คงเหลือ <?= $product['stock'] ?> ชิ้น)
                    </span>
                <?php else: ?>
                    <span class="badge bg-danger rounded-pill px-3 py-2 fw-semibold">
                        <i class="fa-solid fa-circle-xmark me-1"></i> สินค้าหมดชั่วคราว
                    </span>
                <?php endif; ?>
            </div>

            <!-- ราคาสินค้า -->
            <div class="bg-light p-3 rounded-4 mb-4 border-start border-primary border-4">
                <span class="text-muted small d-block">ราคาพิเศษ</span>
                <span class="display-6 fw-bold text-primary"><?= format_price($product['price']) ?></span>
            </div>

            <!-- คำอธิบายสินค้า -->
            <div class="mb-4">
                <h6 class="fw-bold text-dark"><i class="fa-solid fa-circle-info text-primary me-2"></i>รายละเอียดสินค้า:</h6>
                <div class="text-muted" style="white-space: pre-line; line-height: 1.6; font-size: 0.95rem;">
                    <?= htmlspecialchars($product['description'] ?: 'ไม่มีข้อมูลรายละเอียดสินค้าเพิ่มเติม') ?>
                </div>
            </div>

            <!-- ฟอร์มการซื้อสินค้า -->
            <form method="POST" action="cart.php" class="mt-auto border-top pt-4">
                <input type="hidden" name="action" value="add_to_cart">
                <input type="hidden" name="product_id" value="<?= $product['id'] ?>">

                <!-- 1. เลือกเฉดสี (ถ้ามี) -->
                <?php if (!empty($variants)): ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold text-dark mb-2">
                            <i class="fa-solid fa-palette text-danger me-1"></i>เลือกเฉดสีที่ต้องการ:
                        </label>
                        <div class="d-flex flex-wrap gap-2" id="detail_color_container">
                            <button type="button" class="btn btn-outline-secondary rounded-pill px-3 py-1 text-sm active"
                                    id="btn_color_start"
                                    onclick="selectDetailColor('เริ่มต้น', '<?= htmlspecialchars($default_front) ?>', '<?= htmlspecialchars($default_back) ?>', this)">
                                สีเริ่มต้น
                            </button>
                            <?php foreach ($variants as $var): ?>
                                <?php 
                                $v_front = get_product_image_url($var['image_front']);
                                $v_back = !empty($var['image_back']) ? get_product_image_url($var['image_back']) : '';
                                ?>
                                <button type="button" class="btn btn-outline-secondary rounded-pill px-3 py-1 text-sm"
                                        onclick="selectDetailColor('<?= htmlspecialchars($var['color_name']) ?>', '<?= htmlspecialchars($v_front) ?>', '<?= htmlspecialchars($v_back) ?>', this)">
                                    <?= htmlspecialchars($var['color_name']) ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" name="color" id="selected_detail_color" value="เริ่มต้น">
                    </div>
                <?php else: ?>
                    <input type="hidden" name="color" value="">
                <?php endif; ?>

                <!-- 2. เลือกไซส์ (ถ้ามี) -->
                <?php if (!empty($sizes_list)): ?>
                    <div class="mb-4">
                        <label class="form-label fw-semibold text-dark mb-2">
                            <i class="fa-solid fa-ruler me-1 text-info"></i>เลือกขนาด / ไซส์:
                        </label>
                        <div class="d-flex flex-wrap gap-2" id="detail_size_container">
                            <?php foreach ($sizes_list as $index => $sz): ?>
                                <button type="button" class="btn btn-outline-secondary rounded-pill px-3 py-1 text-sm <?= $index === 0 ? 'active' : '' ?>"
                                        onclick="selectDetailSize('<?= htmlspecialchars($sz) ?>', this)">
                                    <?= htmlspecialchars($sz) ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                        <input type="hidden" name="size" id="selected_detail_size" value="<?= htmlspecialchars($sizes_list[0]) ?>">
                    </div>
                <?php else: ?>
                    <input type="hidden" name="size" value="">
                <?php endif; ?>

                <!-- 3. เลือกจำนวน + ปุ่มกดซื้อ -->
                <?php if ($product['stock'] > 0): ?>
                    <div class="row g-3 align-items-center">
                        <div class="col-sm-4">
                            <label class="form-label fw-semibold text-dark mb-1">จำนวนสินค้า</label>
                            <div class="input-group">
                                <button class="btn btn-outline-secondary" type="button" onclick="adjustQty(-1)"><i class="fa-solid fa-minus"></i></button>
                                <input type="number" id="detail_qty" name="quantity" class="form-control text-center fw-bold" value="1" min="1" max="<?= $product['stock'] ?>" readonly>
                                <button class="btn btn-outline-secondary" type="button" onclick="adjustQty(1)"><i class="fa-solid fa-plus"></i></button>
                            </div>
                        </div>
                        <div class="col-sm-8 pt-4">
                            <button type="submit" class="btn btn-primary-custom w-100 py-3 rounded-pill fw-bold fs-5 shadow">
                                <i class="fa-solid fa-cart-plus me-2"></i>ใส่ตะกร้าสินค้า
                            </button>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="alert alert-secondary text-center mt-3 py-3 rounded-4">
                        <i class="fa-solid fa-ban me-2 fs-5"></i> สินค้าหมดชั่วคราว ไม่สามารถสั่งซื้อได้
                    </div>
                <?php endif; ?>

            </form>
        </div>
    </div>

</div>

<script>
// ── ระบบแกลเลอรีและการสลับรูป ────────────────────────────────
function setDetailMainImage(frontSrc, backSrc, colorName, thumbElem) {
    const img = document.getElementById('detail_main_img');
    if (img) {
        img.src = frontSrc;
        img.setAttribute('data-front', frontSrc);
        img.setAttribute('data-back', backSrc);
    }
    
    // ตั้งค่าความเด่นของ Thumbnail
    document.querySelectorAll('.detail-thumb').forEach(t => t.classList.remove('active', 'border-primary'));
    if (thumbElem) {
        thumbElem.classList.add('active', 'border-primary');
    }
    
    // อัปเดตการเลือกสีในฟอร์มให้ตรงกัน
    if (colorName) {
        const colorButtons = document.querySelectorAll('#detail_color_container button');
        colorButtons.forEach(btn => {
            if (btn.textContent.trim() === colorName || (colorName === 'เริ่มต้น' && btn.id === 'btn_color_start')) {
                selectDetailColor(colorName, frontSrc, backSrc, btn);
            }
        });
    }
}

function hoverDetailImage(isHover) {
    const img = document.getElementById('detail_main_img');
    if (img) {
        const backSrc = img.getAttribute('data-back');
        const frontSrc = img.getAttribute('data-front');
        if (backSrc && backSrc.trim() !== '') {
            img.src = isHover ? backSrc : frontSrc;
        }
    }
}

// ── ระบบการเลือกสีและไซส์ในฟอร์ม ─────────────────────────────
function selectDetailColor(colorName, frontSrc, backSrc, btnElem) {
    document.getElementById('selected_detail_color').value = colorName;
    
    // ไฮไลต์ปุ่มสี
    const buttons = document.querySelectorAll('#detail_color_container button');
    buttons.forEach(btn => {
        btn.classList.remove('active', 'btn-danger', 'text-white');
        btn.classList.add('btn-outline-secondary');
    });
    btnElem.classList.remove('btn-outline-secondary');
    btnElem.classList.add('active', 'btn-danger', 'text-white');
    
    // สลับรูปแกลเลอรีใหญ่
    const img = document.getElementById('detail_main_img');
    if (img) {
        img.src = frontSrc;
        img.setAttribute('data-front', frontSrc);
        img.setAttribute('data-back', backSrc);
    }
}

function selectDetailSize(sizeName, btnElem) {
    document.getElementById('selected_detail_size').value = sizeName;
    
    // ไฮไลต์ปุ่มไซส์
    const buttons = document.querySelectorAll('#detail_size_container button');
    buttons.forEach(btn => {
        btn.classList.remove('active', 'btn-info', 'text-white');
        btn.classList.add('btn-outline-secondary');
    });
    btnElem.classList.remove('btn-outline-secondary');
    btnElem.classList.add('active', 'btn-info', 'text-white');
}

// ── ระบบบวกลบจำนวนสินค้า ──────────────────────────────────
function adjustQty(amount) {
    const qtyInput = document.getElementById('detail_qty');
    let currentVal = parseInt(qtyInput.value) || 1;
    const maxVal     = parseInt(qtyInput.getAttribute('max')) || 999;
    
    currentVal += amount;
    if (currentVal < 1) currentVal = 1;
    if (currentVal > maxVal) currentVal = maxVal;
    
    qtyInput.value = currentVal;
}
</script>

<style>
.detail-thumb.active {
    border-color: var(--bs-primary) !important;
    border-width: 2px !important;
    box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
}
</style>

<?php require_once __DIR__ . '/footer.php'; ?>
