<?php
session_start();
include('includes/config.php');


$tipe_query = mysqli_query($conn, "SELECT DISTINCT tipe FROM produk ORDER BY tipe ASC");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Semua Produk - Alfateeh Sepatuku</title>
    <style>
        body{font-family:'Poppins',sans-serif;background:#f5f7fa;margin:0;padding:0;color:#333;}
        header{background:#1e88e5;color:#fff;padding:15px 0;}
        header .container{display:flex;justify-content:space-between;align-items:center;width:90%;margin:auto;}
        header a{color:#fff;text-decoration:none;margin:0 10px;}
        .container{width:90%; margin:auto;}
        h1{text-align:center;color:#1e88e5;margin-top:30px;}
        h2{margin-top:50px;color:#1565c0;text-align:left;border-bottom:2px solid #1565c0;width:fit-content;padding-bottom:5px;}
        
        .produk-grid{display:flex;flex-wrap:wrap;gap:20px;justify-content:center;margin-top:20px;}
        .produk-item{background:#fff;border-radius:10px;box-shadow:0 4px 10px rgba(0,0,0,0.1);width:240px;padding:15px;text-align:center;transition:.3s;}
        .produk-item:hover{transform: translateY(-5px);}
        .produk-item img{width:100%;height:180px;object-fit:cover;border-radius:8px;}
        .produk-item h3{margin:10px 0 5px;font-size:1.1rem; height: 50px; overflow: hidden;}
        .produk-item .harga{color:#1e88e5;font-weight:bold;margin-bottom:10px;}
        
        .size-selection { margin-bottom: 15px; }
        .size-selection select { width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #ddd; outline: none; cursor: pointer; background: #fafafa; }
        
        .button-group { display: flex; gap: 5px; justify-content: center; }
        .button-link{display:inline-block;padding:8px 12px;background:#1e88e5;color:#fff;text-decoration:none;border-radius:6px;transition:.3s; font-size: 0.9rem; border:none; cursor:pointer;}
        .btn-cart { background:#00b4d8; color:#fff; border:none; padding:8px 12px; border-radius:6px; cursor:pointer; font-weight:600; }
        .btn-cart:hover{background:#0096c7;}
        .button-link:hover{background:#1565c0;}
        
        footer{text-align:center;background:#1e88e5;color:#fff;padding:15px;margin-top:60px;}
        
        
        .out-of-stock { opacity: 0.6; filter: grayscale(1); }
        .badge-habis { background: #ff4d4d; color: white; padding: 2px 8px; border-radius: 4px; font-size: 0.7rem; display: block; margin-bottom: 5px; }
    </style>
</head>
<body>

<header>
  <div class="container">
    <div class="logo"><a href="index.php"><strong>Alfateeh</strong>Sepatuku</a></div>
    <nav>
      <a href="index.php">Beranda</a>
      <a href="product.php">Produk</a>
      <a href="keranjang.php">Keranjang 🛒 <span id="cart-count">0</span></a>
    </nav>
  </div>
</header>

<main>
  <h1>Semua Produk Kami</h1>
  <div class="container">
    <?php
    if(mysqli_num_rows($tipe_query) > 0){
        while($tipe_row = mysqli_fetch_assoc($tipe_query)){
            $tipe = $tipe_row['tipe'];
            echo "<h2>".htmlspecialchars($tipe)."</h2>";
            $produk_query = mysqli_query($conn, "SELECT * FROM produk WHERE tipe='$tipe' ORDER BY id ASC");
            
            echo '<div class="produk-grid">';
            while($row = mysqli_fetch_assoc($produk_query)){
                $id_p = $row['id'];
                
                // Ambil semua data stok untuk produk ini
                $stok_res = mysqli_query($conn, "SELECT * FROM produk_detail WHERE id_produk = '$id_p' ORDER BY ukuran ASC");
                $detail_stok = [];
                $total_stok_produk = 0;
                while($s = mysqli_fetch_assoc($stok_res)){
                    $detail_stok[] = $s;
                    $total_stok_produk += $s['stok'];
                }
                ?>
                <div class="produk-item <?= ($total_stok_produk <= 0) ? 'out-of-stock' : '' ?>">
                    <?php if($total_stok_produk <= 0) echo '<span class="badge-habis">STOK HABIS</span>'; ?>
                    
                    <img src="assets/img/<?= htmlspecialchars($row['gambar']) ?>" alt="<?= htmlspecialchars($row['nama']) ?>">
                    <h3><?= htmlspecialchars($row['nama']) ?></h3>
                    <div class="harga">Rp <?= number_format($row['harga'],0,",",".") ?></div>
                    
                    <div class="size-selection">
                        <select id="size-<?= $id_p ?>" <?= ($total_stok_produk <= 0) ? 'disabled' : '' ?>>
                            <option value="">-- Pilih Ukuran --</option>
                            <?php 
                            foreach($detail_stok as $stok_item){
                                $s_qty = intval($stok_item['stok']);
                                if($s_qty <= 0){
                                    echo "<option value='' disabled>Size ".$stok_item['ukuran']." (Habis)</option>";
                                } else {
                                    echo "<option value='".$stok_item['ukuran']."'>Size ".$stok_item['ukuran']." (Sisa ".$s_qty.")</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>

                    <div class="button-group">
                        <?php if($total_stok_produk > 0): ?>
                            <button class="btn-cart" onclick="addToCart(<?= $id_p ?>)">+ 🛒</button> 
                            <button class="button-link" onclick="buyNow(<?= $id_p ?>)">Beli</button>
                        <?php else: ?>
                            <button class="button-link" style="background: #888; cursor: not-allowed;" disabled>Sold Out</button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php
            }
            echo '</div>';
        }
    }
    ?>
  </div>
</main>

<footer>&copy; <?= date('Y') ?> Alfateeh Sepatuku</footer>

<script>
function addToCart(id) {
    const sizeSelect = document.getElementById('size-' + id);
    const size = sizeSelect.value;
    
    if(size === "") {
        alert("Silakan pilih ukuran terlebih dahulu!");
        return;
    }

    fetch(`keranjang.php?add=${id}&size=${size}`)
    .then(response => response.json())
    .then(data => {
        if(data.status === 'ok') {
            const countEl = document.getElementById('cart-count');
            countEl.innerText = parseInt(countEl.innerText) + 1;
            alert("Produk berhasil ditambah ke keranjang!");
        } else {
            alert(data.msg); 
        }
    })
    .catch(err => console.error("Error:", err));
}

function buyNow(id) {
    const size = document.getElementById('size-' + id).value;
    if(size === "") {
        alert("Silakan pilih ukuran terlebih dahulu!");
        return;
    }
    window.location.href = `checkout.php?buy=${id}&size=${size}`;
}
</script>

</body>
</html>