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

$message = '';
$message_type = '';

// ------------------------------------------------------------
// จัดการการเพิ่มสินค้าลงตะกร้า (Add to Cart Action)
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_to_cart') {
    $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
    $quantity   = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT) ?? 1;

    if ($product_id && $quantity > 0) {
        // ตรวจสอบสินค้าในฐานข้อมูล
        $stmt = $pdo->prepare("SELECT id, name, stock FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();

        if ($product) {
            $current_in_cart = $_SESSION['cart'][$product_id] ?? 0;
            $new_total_qty  = $current_in_cart + $quantity;

            if ($new_total_qty <= $product['stock']) {
                if (!isset($_SESSION['cart'])) {
                    $_SESSION['cart'] = [];
                }
                $_SESSION['cart'][$product_id] = $new_total_qty;

                $message = "เพิ่ม <strong>" . htmlspecialchars($product['name']) . "</strong> ลงในตะกร้าสินค้าเรียบร้อยแล้ว!";
                $message_type = "success";
            } else {
                $message = "ขออภัย จำนวนสินค้าในสต็อกมีเพียง {$product['stock']} ชิ้นเท่านั้น";
                $message_type = "danger";
            }
        } else {
            $message = "ไม่พบสินค้าที่ต้องการ";
            $message_type = "danger";
        }
    }
}

// ------------------------------------------------------------
// ดึงรายการสินค้าทั้งหมดจากฐานข้อมูล PDO
// ------------------------------------------------------------
$stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC");
$products = $stmt->fetchAll();

// ดึงตัวเลือกสีของแต่ละสินค้าแบบประสิทธิภาพสูง
$variants_raw = $pdo->query("SELECT * FROM product_variants ORDER BY id ASC")->fetchAll();
$grouped_variants = [];
foreach ($variants_raw as $v) {
    $grouped_variants[$v['product_id']][] = $v;
}
?>

<!-- Hero Banner -->
<div class="hero-banner text-center text-md-start">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h1 class="display-5 fw-bold mb-3">ค้นพบอุปกรณ์ IT & Gadgets ทันสมัย</h1>
            <p class="lead mb-4 opacity-90">ยกระดับประสบการณ์ชีวิตดิจิทัลด้วยสินค้าคุณภาพสูง การันตีของแท้ พร้อมจัดส่งทั่วประเทศ</p>
            <a href="#products-section" class="btn btn-light rounded-pill text-primary fw-semibold px-4 py-2">
                <i class="fa-solid fa-store me-2"></i>เลือกซื้อสินค้าทั้งหมด
            </a>
        </div>
        <div class="col-md-4 text-center d-none d-md-block">
            <i class="fa-solid fa-laptop-code display-1 opacity-75"></i>
        </div>
    </div>
</div>

<!-- Welcome Message Notification -->
<?php if (isset($_SESSION['welcome_msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show rounded-3 shadow-sm d-flex align-items-center mb-4" role="alert">
        <i class="fa-solid fa-circle-check text-success fs-4 me-3"></i>
        <div><?= htmlspecialchars($_SESSION['welcome_msg']) ?></div>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['welcome_msg']); ?>
<?php endif; ?>

<!-- Alert Notification -->
<?php if (!empty($message)): ?>
    <div class="alert alert-<?= $message_type ?> alert-dismissible fade show rounded-3 shadow-sm d-flex align-items-center mb-4" role="alert">
        <i class="fa-solid <?= $message_type === 'success' ? 'fa-circle-check text-success' : 'fa-circle-exclamation text-danger' ?> fs-4 me-3"></i>
        <div><?= $message ?></div>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Products Section -->
<div id="products-section" class="mb-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1"><i class="fa-solid fa-boxes-stacked me-2 text-primary"></i>รายการสินค้าทั้งหมด</h3>
            <p class="text-muted small mb-0">คัดสรรสินค้าไอทีเกรดพรีเมียมเพื่อคุณ</p>
        </div>
        <a href="cart.php" class="btn btn-outline-primary rounded-pill px-3">
            <i class="fa-solid fa-basket-shopping me-1"></i> ดูตะกร้าสินค้า
        </a>
    </div>

    <?php if (empty($products)): ?>
        <div class="card border-0 shadow-sm rounded-4 text-center py-5">
            <div class="card-body">
                <i class="fa-solid fa-box-open display-1 text-muted mb-3"></i>
                <h5>ยังไม่มีสินค้าในระบบ</h5>
                <p class="text-muted">กรุณานำเข้าข้อมูลสินค้าในฐานข้อมูล schema.sql</p>
            </div>
        </div>
    <?php else: ?>
        <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
            <?php foreach ($products as $product): ?>
                <div class="col">
                    <div class="card product-card">
                        <!-- Image & Stock Badge -->
                        <?php 
                        $p_vars = $grouped_variants[$product['id']] ?? []; 
                        $default_front = get_product_image_url($product['image']);
                        $default_back = !empty($product['image_back']) ? get_product_image_url($product['image_back']) : '';
                        ?>
                        <div class="product-img-wrapper" id="img_wrapper_<?= $product['id'] ?>"
                             onmouseenter="hoverProductImage(<?= $product['id'] ?>, true)"
                             onmouseleave="hoverProductImage(<?= $product['id'] ?>, false)">
                            <img src="<?= htmlspecialchars($default_front) ?>" 
                                 class="product-img" 
                                 id="prod_img_<?= $product['id'] ?>"
                                 data-front="<?= htmlspecialchars($default_front) ?>"
                                 data-back="<?= htmlspecialchars($default_back) ?>"
                                 alt="<?= htmlspecialchars($product['name']) ?>">
                            
                            <?php if (is_admin()): ?>
                                <a href="product_edit.php?id=<?= $product['id'] ?>" class="btn btn-sm btn-warning rounded-pill shadow position-absolute m-2 top-0 start-0 z-3 px-3 fw-bold">
                                    <i class="fa-solid fa-pen-to-square me-1"></i> แก้ไขสินค้า
                                </a>
                            <?php endif; ?>

                            <?php if ($product['stock'] > 0): ?>
                                <span class="badge bg-success badge-stock">
                                    <i class="fa-solid fa-check me-1"></i> มีสินค้า (<?= $product['stock'] ?>)
                                </span>
                            <?php else: ?>
                                <span class="badge bg-danger badge-stock">
                                    <i class="fa-solid fa-xmark me-1"></i> สินค้าหมด
                                </span>
                            <?php endif; ?>
                        </div>

                        <!-- Card Body -->
                        <div class="card-body d-flex flex-column p-4">
                            <h5 class="product-title">
                                <a href="product_detail.php?id=<?= $product['id'] ?>" class="text-decoration-none text-dark hover-primary">
                                    <?= htmlspecialchars($product['name']) ?>
                                </a>
                            </h5>
                            <p class="card-text text-muted small flex-grow-1 mb-2">
                                <?= htmlspecialchars(mb_strimwidth($product['description'], 0, 95, "...")) ?>
                            </p>
                            
                            <?php if (!empty($p_vars)): ?>
                                <div class="mb-3">
                                    <small class="text-muted fw-semibold d-block mb-1" style="font-size: 0.75rem;">
                                        <i class="fa-solid fa-palette text-danger me-1"></i>สีที่มีจำหน่าย:
                                    </small>
                                    <div class="d-flex flex-wrap gap-1">
                                        <button type="button" class="btn btn-xs btn-secondary text-white rounded-pill py-0 px-2 text-xs small-variant-btn active"
                                                style="font-size: 0.75rem;"
                                                onclick="changeProductColor(<?= $product['id'] ?>, '<?= htmlspecialchars($default_front) ?>', '<?= htmlspecialchars($default_back) ?>', this)">
                                            เริ่มต้น
                                        </button>
                                        <?php foreach ($p_vars as $v): ?>
                                            <?php 
                                            $v_front = get_product_image_url($v['image_front']);
                                            $v_back = !empty($v['image_back']) ? get_product_image_url($v['image_back']) : '';
                                            ?>
                                            <button type="button" class="btn btn-xs btn-outline-secondary rounded-pill py-0 px-2 text-xs small-variant-btn"
                                                    style="font-size: 0.75rem;"
                                                    onclick="changeProductColor(<?= $product['id'] ?>, '<?= htmlspecialchars($v_front) ?>', '<?= htmlspecialchars($v_back) ?>', this)">
                                                <?= htmlspecialchars($v['color_name']) ?>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <div class="d-flex justify-content-between align-items-center mt-auto pt-3 border-top">
                                <div>
                                    <span class="text-muted small d-block">ราคา</span>
                                    <span class="product-price"><?= format_price($product['price']) ?></span>
                                </div>

                                <?php if ($product['stock'] > 0): ?>
                                    <a href="product_detail.php?id=<?= $product['id'] ?>" class="btn btn-primary-custom btn-sm rounded-pill px-3 fw-semibold">
                                        <i class="fa-solid fa-eye me-1"></i> ดูรายละเอียด / ซื้อ
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary btn-sm rounded-pill px-3" disabled>
                                        <i class="fa-solid fa-ban me-1"></i> สินค้าหมด
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script>
function changeProductColor(productId, frontSrc, backSrc, btnElem) {
    const img = document.getElementById('prod_img_' + productId);
    if (img) {
        img.src = frontSrc;
        img.setAttribute('data-front', frontSrc);
        img.setAttribute('data-back', backSrc);
    }
    
    // สลับคลาส active ของปุ่มสีต่างๆ
    const wrapper = btnElem.parentElement;
    wrapper.querySelectorAll('.small-variant-btn').forEach(btn => {
        btn.classList.remove('active', 'btn-secondary', 'text-white');
        btn.classList.add('btn-outline-secondary');
    });
    btnElem.classList.remove('btn-outline-secondary');
    btnElem.classList.add('active', 'btn-secondary', 'text-white');
}

function hoverProductImage(productId, isHover) {
    const img = document.getElementById('prod_img_' + productId);
    if (img) {
        const backSrc = img.getAttribute('data-back');
        const frontSrc = img.getAttribute('data-front');
        if (backSrc && backSrc.trim() !== '') {
            img.src = isHover ? backSrc : frontSrc;
        }
    }
}
</script>

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