<?php
/**
 * Product Detail Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($product_id <= 0) {
    header("Location: " . base_url('index.php'));
    exit();
}

// Fetch Product Data
$stmt = $db->prepare("
    SELECT p.*, c.name as category_name,
           (SELECT COALESCE(SUM(quantity), 0) FROM product_stock WHERE product_id = p.id) as total_stock
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.id = ? AND p.status = 'active'
    LIMIT 1
");
$stmt->execute([$product_id]);
$product = $stmt->fetch();

if (!$product) {
    echo "<div class='container my-5 text-center py-5'>
            <div class='card shadow-sm border-0 p-5 mx-auto' style='max-width: 500px; border-radius: 16px;'>
                <i class='bi bi-exclamation-triangle text-warning' style='font-size: 3.5rem;'></i>
                <h4 class='fw-bold mt-3'>ไม่พบสินค้าที่ต้องการ</h4>
                <p class='text-muted'>สินค้านี้อาจถูกลบหรือปิดการมองเห็นไปแล้ว</p>
                <div>
                    <a href='" . base_url('index.php') . "' class='btn btn-primary px-4 mt-2' style='border-radius: 10px;'>
                        <i class='bi bi-arrow-left me-1'></i> กลับหน้าร้านค้า
                    </a>
                </div>
            </div>
          </div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit();
}

// Fetch Images
$stmt_images = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_main DESC, id ASC");
$stmt_images->execute([$product_id]);
$images = $stmt_images->fetchAll();

// Fetch Colors
$stmt_colors = $db->prepare("SELECT * FROM product_colors WHERE product_id = ? ORDER BY id ASC");
$stmt_colors->execute([$product_id]);
$colors = $stmt_colors->fetchAll();

// Fetch Sizes
$stmt_sizes = $db->prepare("SELECT * FROM product_sizes WHERE product_id = ? ORDER BY id ASC");
$stmt_sizes->execute([$product_id]);
$sizes = $stmt_sizes->fetchAll();

// Pricing calculation
$display_price = !empty($product['promo_price']) ? $product['promo_price'] : $product['price'];
$is_promo = !empty($product['promo_price']);
$discount_percent = $is_promo ? round((($product['price'] - $product['promo_price']) / $product['price']) * 100) : 0;
$is_booking = ($product['purchase_type'] ?? 'normal') === 'booking';
?>

<style>
    .product-main-img-box {
        border-radius: 16px;
        overflow: hidden;
        background-color: var(--bs-tertiary-bg, #f8fafc);
        border: 1px solid var(--bs-border-color, rgba(0,0,0,0.08));
        height: 380px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .product-main-img {
        max-height: 100%;
        max-width: 100%;
        object-fit: contain;
        transition: transform 0.3s ease;
    }
    .product-main-img:hover {
        transform: scale(1.03);
    }
    .thumb-img-box {
        width: 70px;
        height: 70px;
        border-radius: 10px;
        border: 2px solid transparent;
        cursor: pointer;
        overflow: hidden;
        background-color: var(--bs-tertiary-bg, #f8fafc);
        transition: all 0.2s ease;
    }
    .thumb-img-box.active {
        border-color: #0d6efd;
        box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.25);
    }
    .thumb-img-box img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .option-btn-radio input[type="radio"] {
        display: none;
    }
    .option-btn-radio label {
        display: inline-block;
        padding: 8px 16px;
        border-radius: 8px;
        border: 1.5px solid var(--bs-border-color, #dee2e6);
        cursor: pointer;
        font-size: 0.9rem;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    .option-btn-radio input[type="radio"]:checked + label {
        border-color: #0d6efd;
        background-color: rgba(13, 110, 253, 0.08);
        color: #0d6efd;
    }
    .btn-quantity {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        font-weight: bold;
    }
    .qty-input {
        width: 60px;
        text-align: center;
        font-weight: bold;
        border-radius: 8px;
    }
</style>

<div class="container my-5">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?php echo base_url('index.php'); ?>" class="text-decoration-none">หน้าแรก</a></li>
            <li class="breadcrumb-item"><a href="<?php echo base_url('index.php?category=' . ($product['category_id'] ?? 0)); ?>" class="text-decoration-none"><?php echo sanitize($product['category_name'] ?? 'หมวดหมู่สินค้า'); ?></a></li>
            <li class="breadcrumb-item active" aria-current="page"><?php echo sanitize($product['name']); ?></li>
        </ol>
    </nav>

    <div class="row g-5">
        <!-- Product Images -->
        <div class="col-lg-6">
            <div class="product-main-img-box mb-3 shadow-sm">
                <?php
                $main_img_url = !empty($images[0]['image_path']) ? product_image_url($images[0]['image_path']) : base_url('assets/images/no-image.png');
                ?>
                <img id="mainProductImg" src="<?php echo $main_img_url; ?>" class="product-main-img" alt="<?php echo sanitize($product['name']); ?>" onerror="this.onerror=null; this.src='<?php echo base_url('assets/images/no-image.png'); ?>';">
            </div>

            <!-- Thumbnail Gallery -->
            <?php if (count($images) > 1): ?>
                <div class="d-flex gap-2 overflow-auto pb-2">
                    <?php foreach ($images as $idx => $img): ?>
                        <?php $thumb_url = product_image_url($img['image_path']); ?>
                        <div class="thumb-img-box <?php echo $idx === 0 ? 'active' : ''; ?>" onclick="changeMainImage('<?php echo $thumb_url; ?>', this)">
                            <img src="<?php echo $thumb_url; ?>" alt="Thumb" onerror="this.onerror=null; this.src='<?php echo base_url('assets/images/no-image.png'); ?>';">
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Product Information & Options -->
        <div class="col-lg-6">
            <div class="d-flex align-items-center gap-2 mb-2">
                <span class="badge bg-secondary px-2.5 py-1.5" style="font-size: 0.8rem;"><?php echo sanitize($product['category_name'] ?? 'สินค้าทั่วไป'); ?></span>
                <?php if ($is_booking): ?>
                    <span class="badge bg-primary px-2.5 py-1.5" style="font-size: 0.8rem;"><i class="bi bi-bookmark-check me-1"></i>เปิดรับจอง</span>
                <?php endif; ?>
                <span class="badge <?php echo $product['total_stock'] > 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'; ?> px-2.5 py-1.5" style="font-size: 0.8rem;">
                    <?php echo $product['total_stock'] > 0 ? 'คงเหลือในสต๊อก ' . number_format($product['total_stock']) . ' ชิ้น' : 'สินค้าหมด'; ?>
                </span>
            </div>

            <h2 class="fw-bold mb-2"><?php echo sanitize($product['name']); ?></h2>
            <div class="text-muted small mb-3">
                <span class="me-3">รหัสสินค้า (SKU): <strong class="text-dark"><?php echo sanitize($product['sku']); ?></strong></span>
                <?php if (!empty($product['barcode'])): ?>
                    <span>บาร์โค้ด: <strong class="text-dark"><?php echo sanitize($product['barcode']); ?></strong></span>
                <?php endif; ?>
            </div>

            <!-- Price Box -->
            <div class="p-3 rounded-4 mb-4" style="background-color: rgba(13, 110, 253, 0.05); border: 1px dashed rgba(13, 110, 253, 0.25);">
                <div class="d-flex align-items-baseline gap-3 flex-wrap">
                    <span class="display-6 fw-bold text-primary" style="font-family: 'Outfit', 'Sarabun', sans-serif;">
                        <?php echo format_price($display_price); ?>
                    </span>
                    <?php if ($is_promo): ?>
                        <span class="text-decoration-line-through text-muted fs-5"><?php echo format_price($product['price']); ?></span>
                        <span class="badge bg-danger rounded-pill px-2.5 py-1 fw-bold">ลด <?php echo $discount_percent; ?>%</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Description -->
            <?php if (!empty($product['description'])): ?>
                <div class="mb-4">
                    <h6 class="fw-bold text-muted small text-uppercase mb-2">รายละเอียดสินค้า</h6>
                    <p class="text-secondary" style="white-space: pre-line; line-height: 1.7;">
                        <?php echo nl2br(sanitize($product['description'])); ?>
                    </p>
                </div>
            <?php endif; ?>

            <form id="addToCartForm">
                <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                <input type="hidden" name="action" value="add">

                <!-- Colors Selection -->
                <?php if (count($colors) > 0): ?>
                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase mb-2">เลือกสี / รูปแบบ</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach ($colors as $cIdx => $color): ?>
                                <div class="option-btn-radio">
                                    <input type="radio" id="color_<?php echo $color['id']; ?>" name="color_id" value="<?php echo $color['id']; ?>" <?php echo $cIdx === 0 ? 'checked' : ''; ?>>
                                    <label for="color_<?php echo $color['id']; ?>">
                                        <?php if (!empty($color['color_code'])): ?>
                                            <span class="d-inline-block rounded-circle me-1" style="width: 12px; height: 12px; background-color: <?php echo sanitize($color['color_code']); ?>; border: 1px solid rgba(0,0,0,0.15); vertical-align: middle;"></span>
                                        <?php endif; ?>
                                        <?php echo sanitize($color['color_name']); ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Sizes Selection -->
                <?php if (count($sizes) > 0): ?>
                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase mb-2">เลือกขนาด / ไซส์</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach ($sizes as $sIdx => $size): ?>
                                <div class="option-btn-radio">
                                    <input type="radio" id="size_<?php echo $size['id']; ?>" name="size_id" value="<?php echo $size['id']; ?>" <?php echo $sIdx === 0 ? 'checked' : ''; ?>>
                                    <label for="size_<?php echo $size['id']; ?>">
                                        <?php echo sanitize($size['size_name']); ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Quantity & Actions -->
                <div class="mb-4">
                    <label class="form-label fw-bold small text-muted text-uppercase mb-2">จำนวน</label>
                    <div class="d-flex align-items-center gap-2">
                        <button type="button" class="btn btn-outline-secondary btn-quantity" onclick="updateQty(-1)"><i class="bi bi-dash"></i></button>
                        <input type="number" id="quantityInput" name="quantity" class="form-control qty-input" value="1" min="1" max="<?php echo max(1, $product['total_stock']); ?>">
                        <button type="button" class="btn btn-outline-secondary btn-quantity" onclick="updateQty(1)"><i class="bi bi-plus"></i></button>
                    </div>
                </div>

                <!-- Add to Cart / Buy Now Buttons -->
                <div class="d-flex gap-3">
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <button type="submit" class="btn btn-primary flex-grow-1 py-2.5 fw-bold d-flex align-items-center justify-content-center gap-2" style="border-radius: 12px;" id="btnAddToCart">
                            <i class="bi bi-cart-plus fs-5"></i>
                            <span><?php echo $is_booking ? 'จองสินค้าลงตะกร้า' : 'เพิ่มลงตะกร้าสินค้า'; ?></span>
                        </button>
                        <a href="<?php echo base_url('views/cart.php'); ?>" class="btn btn-outline-primary py-2.5 px-3 fw-bold d-flex align-items-center justify-content-center" style="border-radius: 12px;">
                            <i class="bi bi-cart3 fs-5"></i>
                        </a>
                    <?php else: ?>
                        <a href="<?php echo base_url('login.php'); ?>" class="btn btn-warning flex-grow-1 py-2.5 fw-bold d-flex align-items-center justify-content-center gap-2" style="border-radius: 12px;">
                            <i class="bi bi-box-arrow-in-right fs-5"></i>
                            <span>เข้าสู่ระบบเพื่อสั่งซื้อ / สั่งจอง</span>
                        </a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- SweetAlert2 for notifications -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function changeMainImage(url, elem) {
    const mainImg = document.getElementById('mainProductImg');
    const fallback = document.getElementById('mainProductImgFallback');
    
    if (mainImg) {
        mainImg.src = url;
        mainImg.classList.remove('d-none');
    }
    if (fallback) {
        fallback.classList.add('d-none');
    }
    
    document.querySelectorAll('.thumb-img-box').forEach(el => el.classList.remove('active'));
    if (elem) {
        elem.classList.add('active');
    }
}

function updateQty(delta) {
    const input = document.getElementById('quantityInput');
    let val = parseInt(input.value) || 1;
    val += delta;
    if (val < 1) val = 1;
    input.value = val;
}

$(document).ready(function() {
    $('#addToCartForm').on('submit', function(e) {
        e.preventDefault();
        const btn = $('#btnAddToCart');
        btn.prop('disabled', true);

        $.ajax({
            url: '<?php echo base_url("api/cart_handler.php"); ?>',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res) {
                btn.prop('disabled', false);
                if (res.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'สำเร็จ!',
                        text: res.message,
                        showCancelButton: true,
                        confirmButtonText: '<i class="bi bi-cart-check me-1"></i> ไปที่ตะกร้าสินค้า',
                        cancelButtonText: 'เลือกสินค้าต่อ',
                        confirmButtonColor: '#0d6efd',
                        cancelButtonColor: '#6c757d'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '<?php echo base_url("views/cart.php"); ?>';
                        } else {
                            location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'ผิดพลาด',
                        text: res.message || 'เกิดข้อผิดพลาดในการเพิ่มสินค้าลงตะกร้า',
                        confirmButtonColor: '#0d6efd'
                    });
                }
            },
            error: function(xhr) {
                btn.prop('disabled', false);
                let msg = 'ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                Swal.fire({
                    icon: 'error',
                    title: 'แจ้งเตือน',
                    text: msg,
                    confirmButtonColor: '#0d6efd'
                });
            }
        });
    });
});
</script>

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