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


if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = [];
}


$query = mysqli_query($conn, "SELECT * FROM produk ORDER BY id DESC LIMIT 5");

$isUserLoggedIn = isset($_SESSION['user_id']) && $_SESSION['role'] === 'user';
$isAdminLoggedIn = isset($_SESSION['user_id']) && $_SESSION['role'] === 'admin';

if($isAdminLoggedIn){
    header("Location: admin/index_admin.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alfateeh Sepatuku</title>
<style>

*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:'Poppins',sans-serif;background:#f5f7fa;color:#333;}
nav{display:flex;justify-content:space-between;align-items:center;padding:15px 40px;background:#1e88e5;color:#fff;position:sticky;top:0;z-index:1000;}
nav a{color:#fff;text-decoration:none;margin-left:20px;font-weight:500;}
nav a:hover{color:#ffeb3b;}
nav .logo{font-size:2rem;font-weight:900;text-shadow:2px 2px 6px rgba(0,0,0,0.5);}
nav .dropdown{position:relative;display:inline-block;}
nav .dropdown-content{display:none;position:absolute;background:#fff;color:#333;min-width:180px;box-shadow:0 4px 12px rgba(0,0,0,0.2);border-radius:6px;z-index:1000;}
nav .dropdown-content a{color:#333;padding:10px 15px;display:block;text-decoration:none;}
nav .dropdown-content a:hover{background:#1e88e5;color:#fff;border-radius:4px;}
nav .dropdown:hover .dropdown-content{display:block;}

.slideshow-container{margin-top:15px;position:relative;width:100%;height:85vh;overflow:hidden;}
@media screen and (max-width:768px){ .slideshow-container { height:60vh; } }
.slide{position:absolute;width:100%;height:100%;opacity:0;transition:opacity 1s;}
.slide img{width:100%;height:100%;object-fit:cover;filter:brightness(70%);}
.slide.active{opacity:1;}
.slide-caption{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#fff;text-align:center;background:rgba(0,0,0,0.35);padding:20px;border-radius:15px;width: 80%;}
.slide-caption h1{font-size:3rem;text-shadow:0 3px 8px rgba(0,0,0,0.6);}
.slide-caption p{font-size:1.2rem;text-shadow:0 2px 5px rgba(0,0,0,0.6);}

.prev,.next{position:absolute;top:50%;transform:translateY(-50%);background:rgba(0,0,0,0.5);color:white;font-size:2rem;padding:10px;border-radius:50%;cursor:pointer;z-index: 10;}
.prev{left:20px;} .next{right:20px;}
.dots{text-align:center;position:absolute;bottom:15px;width:100%;z-index: 10;}
.dot{height:12px;width:12px;margin:0 5px;background-color:rgba(255,255,255,0.6);border-radius:50%;display:inline-block;cursor:pointer;}
.active-dot{background-color:#fff;}

.discount-banner {margin: 30px auto;width: 90%;background: linear-gradient(90deg,#00b4d8,#0096c7);color: #fff;border-radius: 12px;text-align:center;padding:25px 15px;box-shadow:0 4px 12px rgba(0,0,0,0.15);position:relative;overflow:hidden;transition: transform 0.3s;}
.discount-banner:hover { transform: scale(1.02); }
.discount-banner h2 { font-size: 2rem; margin-bottom: 10px; text-shadow:0 2px 5px rgba(0,0,0,0.3); color:#fff; border:none; }
.discount-banner p { font-size:1.1rem; margin-bottom: 15px; }


.container{width:90%;margin:40px auto;text-align:center;}
h2{color:#1e88e5;margin-bottom:25px; text-align: center;}
.product-grid{display:flex;flex-wrap:wrap;justify-content:center;gap:25px;}
.product-card{background:#fff;border-radius:12px;box-shadow:0 4px 10px rgba(0,0,0,0.1);width:230px;padding:15px;transition:.3s; display: flex; flex-direction: column;}
.product-card:hover{transform:translateY(-5px);box-shadow:0 8px 15px rgba(0,0,0,0.15);}
.product-card img{width:100%;height:180px;object-fit:cover;border-radius:8px;}
.product-card h3{margin-top:10px;font-size:1.1rem;color:#333; min-height: 45px;}
.product-card .price{color:#1e88e5;font-weight:600;margin:5px 0; font-size: 1.1rem;}

.size-selection { margin: 10px 0; }
.size-selection select { width: 100%; padding: 7px; border-radius: 6px; border: 1px solid #ddd; outline: none; background: #f9f9f9; cursor: pointer; }

.btn-group { display: flex; gap: 5px; margin-top: auto; }
.btn, .btn-cart{ flex: 1; display:inline-block; background:#00b4d8; color:#fff; text-decoration:none; border-radius:6px; padding:8px 5px; font-weight:600; cursor:pointer; transition:.3s; border:none; font-size: 0.85rem;}
.btn{ background: #1e88e5; text-align: center; }
.btn:hover{ background: #1565c0; }
.btn-cart:hover{background:#0096c7;}

.flash-red { color: #ff3b3b; animation: flash 1s infinite; }
@keyframes flash { 0%,50%,100%{color:#ff3b3b;} 25%,75%{color:#ffeb3b;} }
.btn-banner { display:inline-block; background:#ffeb3b; color:#000; padding:12px 25px; border-radius:8px; font-weight:700; text-decoration:none; transition:0.3s; }
footer{background:#1e88e5;color:#fff;text-align:center;padding:15px;margin-top:60px;font-size:.9rem;}
.out-of-stock { opacity: 0.6; filter: grayscale(1); }
</style>
</head>
<body>

<nav>
  <div class="logo">ALFATEEH SEPATUKU</div>
  <div>
    <a href="index.php">Beranda</a>
    <?php if($isUserLoggedIn): ?>
      <a href="product.php">Product</a>
    <?php endif; ?>
    <a href="tentang.php">Tentang</a>
    <a href="kontak.php">Kontak</a>

    <?php if($isUserLoggedIn): ?>
      <div class="dropdown">
        <a href="#">My Profile 👤</a>
        <div class="dropdown-content">
          <a href="profil.php">Profil Saya</a>
          <a href="edit_profil.php">Edit Profil</a>
          <a href="ubah_password.php">Ubah Password</a>
          <a href="pesanan_saya.php">Pesanan Saya</a>
          <a href="logout.php" style="color:#e63946;">Logout</a>
        </div>
      </div>
      <a href="keranjang.php">Keranjang 🛒 (<span id="cart-count"><?= array_sum(array_column($_SESSION['cart'], 'qty')) ?></span>)</a>
    <?php else: ?>
      <a href="register.php" class="btn-banner" style="padding: 5px 10px; font-size: 0.8rem;">Daftar</a>
      <a href="login_user.php" class="btn-banner" style="padding: 5px 10px; font-size: 0.8rem;">Login User</a>
      <a href="login_admin.php" class="btn-banner" style="padding: 5px 10px; font-size: 0.8rem;">Admin</a>
    <?php endif; ?>
  </div>
</nav>

<div class="slideshow-container">
  <div class="slide active">
    <img src="assets/img/banner1.jpg" alt="Classic Sneakers">
    <div class="slide-caption">
      <h1>Classic Sneakers</h1>
      <p>Gaya klasik yang tak lekang oleh waktu</p>
    </div>
  </div>
  <div class="slide">
    <img src="assets/img/banner2.jpg" alt="Street Runner">
    <div class="slide-caption">
      <h1>Street Runner</h1>
      <p>Ringan, cepat, dan stylish untuk harimu</p>
    </div>
  </div>
  <div class="slide">
    <img src="assets/img/banner3.jpg" alt="Trail Boots">
    <div class="slide-caption">
      <h1>Trail Boots</h1>
      <p>Kuat untuk petualangan di segala medan</p>
    </div>
  </div>
  <span class="prev" onclick="changeSlide(-1)">&#10094;</span>
  <span class="next" onclick="changeSlide(1)">&#10095;</span>
  <div class="dots">
    <span class="dot active-dot" onclick="currentSlide(1)"></span>
    <span class="dot" onclick="currentSlide(2)"></span>
    <span class="dot" onclick="currentSlide(3)"></span>
  </div>
</div>

<div class="discount-banner">
  <h2><span class="flash-red">🎉 Diskon 20%</span> untuk Pembelian Kedua Produk Sama!</h2>
  <p>Tambahkan produk kedua yang sama ke keranjang dan nikmati potongan harga spesial.</p>
  <?php if($isUserLoggedIn): ?>
    <a href="product.php" class="btn-banner">Belanja Sekarang</a>
  <?php else: ?>
    <a href="register.php" class="btn-banner">Daftar & Belanja</a>
  <?php endif; ?>
</div>

<div class="container">
  <h2>🆕 Produk Terbaru</h2>
  <div class="product-grid">
    <?php if(mysqli_num_rows($query) > 0): ?>
      <?php while($row = mysqli_fetch_assoc($query)): 
          $id_p = $row['id'];
          // Cek total stok produk
          $stok_res = mysqli_query($conn, "SELECT SUM(stok) as total FROM produk_detail WHERE id_produk = '$id_p'");
          $stok_data = mysqli_fetch_assoc($stok_res);
          $is_out = ($stok_data['total'] <= 0);
      ?>
        <div class="product-card <?= $is_out ? 'out-of-stock' : '' ?>">
          <img src="assets/img/<?= htmlspecialchars($row['gambar']) ?>" alt="<?= htmlspecialchars($row['nama']) ?>">
          <h3><?= htmlspecialchars($row['nama']) ?></h3>
          <p class="price">Rp <?= number_format($row['harga'],0,",",".") ?></p>

          <?php if($isUserLoggedIn): ?>
            <div class="size-selection">
                <select id="size-<?= $id_p ?>" <?= $is_out ? 'disabled' : '' ?>>
                    <option value="">-- Pilih Size --</option>
                    <?php 
                    $uk_query = mysqli_query($conn, "SELECT * FROM produk_detail WHERE id_produk = '$id_p' ORDER BY ukuran ASC");
                    while($uk = mysqli_fetch_assoc($uk_query)):
                        $disabled = ($uk['stok'] <= 0) ? 'disabled' : '';
                        $label = ($uk['stok'] <= 0) ? $uk['ukuran'] . " (Habis)" : $uk['ukuran'] . " (Sisa ".$uk['stok'].")";
                    ?>
                        <option value="<?= $uk['ukuran'] ?>" <?= $disabled ?>><?= $label ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <div class="btn-group">
                <?php if(!$is_out): ?>
                    <button onclick="addToCart(<?= $id_p ?>)" class="btn-cart">+ 🛒</button>
                    <button onclick="buyNow(<?= $id_p ?>)" class="btn">Beli</button>
                <?php else: ?>
                    <button disabled style="background:#888; width: 100%; border:none; color:#fff; border-radius:6px; padding:8px;">Sold Out</button>
                <?php endif; ?>
            </div>
          <?php else: ?>
            <a href="login_user.php" class="btn-banner" style="display:block; margin-top:10px; font-size: 0.9rem;">Login</a>
          <?php endif; ?>
        </div>
      <?php endwhile; ?>
    <?php else: ?>
      <p>Belum ada produk.</p>
    <?php endif; ?>
  </div>
</div>

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

<script>

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

    fetch(`keranjang.php?add=${id}&size=${size}`)
    .then(res => res.json())
    .then(data => {
        if(data.status === 'ok') {
            alert("Berhasil masuk keranjang!");
            const countEl = document.getElementById('cart-count');
            countEl.innerText = parseInt(countEl.innerText) + 1;
        } else {
            alert(data.msg);
        }
    });
}

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}`;
}


let slideIndex = 0;
const slides = document.querySelectorAll('.slide');
const dots = document.querySelectorAll('.dot');

function showSlide(n){
  slides.forEach((s,i)=>{
    s.classList.remove('active');
    dots[i].classList.remove('active-dot');
    if(i===n){ s.classList.add('active'); dots[i].classList.add('active-dot'); }
  });
}

function changeSlide(n){
  slideIndex = (slideIndex + n + slides.length) % slides.length;
  showSlide(slideIndex);
}

function currentSlide(n){
  slideIndex = n-1;
  showSlide(slideIndex);
}

setInterval(()=>changeSlide(1),4000);
</script>
</body>
</html>