<?php
session_start();
require 'config.php';
require './pelanggan/navbar.php';

$id = $_GET['id'] ?? null;

if (!isset($id) || !filter_var($id, FILTER_VALIDATE_INT)) {
  echo "Produk tidak ditemukan atau ID tidak valid.";
  exit;
}

// Ambil data produk
$stmt = $conn->prepare("
    SELECT p.*, kp.nama AS nama_kategori 
    FROM produk p 
    JOIN kategori_produk kp ON p.kategori_id = kp.id 
    WHERE p.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$produk = $result->fetch_assoc();

if (!$produk) {
  echo "Produk tidak ditemukan.";
  exit;
}

// Ambil semua ukuran produk dan stok-nya
$stmt_ukuran = $conn->prepare("SELECT id, ukuran, stok FROM ukuran_produk WHERE produk_id = ?");
$stmt_ukuran->bind_param("i", $id);
$stmt_ukuran->execute();
$result_ukuran = $stmt_ukuran->get_result();

$ukuran_list = [];
while ($row = $result_ukuran->fetch_assoc()) {
  $ukuran_list[] = $row;
}

$diskon = null;
if (!empty($produk['diskon_id'])) {
  $diskon_result = mysqli_query($conn, "SELECT * FROM diskon WHERE id = {$produk['diskon_id']} AND aktif = 'ya'");
  $diskon = mysqli_fetch_assoc($diskon_result);
}
?>

<!-- HTML Mulai -->
<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($produk['nama']) ?> - Detail Produk</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    body {
      background-color: #fff;
      color: #000;
      font-family: 'Segoe UI', sans-serif;
    }

    .product-image {
      width: 100%;
      border-radius: 12px;
      object-fit: contain;
      height: 500px;
      background-color: #f2f2f2;
    }

    @media (max-width: 100px){
      .product-image{
        min-width: 400px;
        object-fit: cover;
      }
    }

    .card-ukuran {
      cursor: pointer;
      border: 2px solid transparent;
      transition: all 0.2s ease-in-out;
      min-width: 80px;
      flex: 1;
    }

    .card-ukuran:hover,
    .card-ukuran.active {
      border-color: #000;
      background-color: #000;
      color: #fff;
    }

    .card-ukuran.disabled {
      background-color: #f8f9fa;
      color: #6c757d;
      border-color: #dee2e6;
      cursor: not-allowed;
      opacity: 0.6;
    }

    .card-ukuran.disabled:hover {
      background-color: #f8f9fa;
      color: #6c757d;
      border-color: #dee2e6;
    }

    .ukuran-container {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    /* Rating Bintang */
    .star-rating {
      direction: rtl;
      display: inline-flex;
      font-size: 2rem;
      gap: 0.2rem;
    }

    .star-rating input[type="radio"] {
      display: none;
    }

    .star-rating label {
      color: #ddd;
      cursor: pointer;
      transition: color 0.2s;
    }

    .star-rating input[type="radio"]:checked~label,
    .star-rating label:hover,
    .star-rating label:hover~label {
      color: #ffc107;
    }

    /* Ulasan Card */
    .review-card {
      border: 1px solid #eee;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      margin-bottom: 20px;
      background: #fafbfc;
      padding: 20px 24px;
      position: relative;
    }

    .review-user {
      font-weight: 600;
      color: #222;
      font-size: 1.1rem;
    }

    .review-date {
      font-size: 0.9rem;
      color: #888;
    }

    .review-rating {
      color: #ffc107;
      font-size: 1.2rem;
      margin-bottom: 6px;
    }

    .review-text {
      font-size: 1.05rem;
      color: #333;
      margin-top: 8px;
      margin-bottom: 0;
    }

    .review-quote {
      font-style: italic;
      color: #666;
      margin-left: 10px;
    }

        /* Mobile Responsive Styles */
    @media (max-width: 768px) {
      .container {
        padding-left: 15px !important;
        padding-right: 15px !important;
      }
      .product-image {
        height: 300px;
        margin-bottom: 20px;
      }
      .product-details {
        padding: 0 10px;
      }
      .product-title {
        font-size: 1.5rem;
        margin-bottom: 15px;
        line-height: 1.3;
      }
      .product-category {
        font-size: 0.9rem;
        margin-bottom: 15px;
      }
      .product-description {
        font-size: 0.95rem;
        line-height: 1.5;
        margin-bottom: 20px;
      }
      .product-price {
        font-size: 1.3rem !important;
        margin-bottom: 25px;
      }
      .discount-badge {
        font-size: 0.8rem;
        padding: 4px 8px;
        margin-bottom: 10px;
      }
      .original-price {
        font-size: 1rem;
      }
      .discounted-price {
        font-size: 1.3rem !important;
      }
      /* Mobile ukuran selection */
      .ukuran-container {
        gap: 8px;
        margin-bottom: 20px;
      }
      .card-ukuran {
        min-width: 70px;
        padding: 12px 8px !important;
        font-size: 0.9rem;
      }
      .card-ukuran .fw-bold {
        font-size: 0.95rem;
      }
      .card-ukuran small {
        font-size: 0.75rem;
      }
      /* Mobile form elements */
      .form-label {
        font-size: 1rem;
        font-weight: 600;
        margin-bottom: 10px;
      }
      .form-control {
        padding: 12px;
        font-size: 1rem;
        border-radius: 8px;
      }
      .btn-dark {
        width: 100%;
        padding: 15px;
        font-size: 1.1rem;
        font-weight: 600;
        border-radius: 8px;
        margin-top: 10px;
      }
      #stokInfo {
        font-size: 0.9rem;
        margin-top: 5px;
      }
      /* Mobile reviews section */
      .review-section {
        margin-top: 20px;
        padding: 0 5px;
        margin-bottom: 40px; /* Tambahan margin bottom untuk review section */
      }
      .review-section h4 {
        font-size: 1.4rem;
        margin-bottom: 20px;
        text-align: center;
      }
      .review-card {
        padding: 15px 18px;
        margin-bottom: 15px;
        border-radius: 10px;
      }
      .review-user {
        font-size: 1rem;
      }
      .review-date {
        font-size: 0.8rem;
      }
      .review-rating {
        font-size: 1.1rem;
        margin-bottom: 8px;
      }
      .review-text {
        font-size: 0.95rem;
        line-height: 1.4;
      }
      .review-quote {
        margin-left: 5px;
      }
      /* Mobile alert styles */
      .alert {
        margin-bottom: 20px;
        font-size: 0.9rem;
        padding: 12px;
        border-radius: 8px;
      }
      /* Mobile responsive flexbox adjustments */
      .d-flex.align-items-center {
        flex-wrap: wrap;
        gap: 10px;
      }
      .review-user {
        flex: 1 1 auto;
      }
      .review-date {
        flex: 1 1 100%;
        margin-top: 5px;
      }
    }
    @media (max-width: 480px) {
      .container {
        padding-left: 10px !important;
        padding-right: 10px !important;
      }
      .product-image {
        height: 250px;
        border-radius: 8px;
      }
      .product-title {
        font-size: 1.3rem;
      }
 
      .product-price {
        font-size: 1.2rem !important;
      }
      .discounted-price {
        font-size: 1.2rem !important;
      }
      .ukuran-container {
        gap: 6px;
      }
      .card-ukuran {
        min-width: 65px;
        padding: 10px 6px !important;
        font-size: 0.85rem;
      }
      .card-ukuran .fw-bold {
        font-size: 0.9rem;
      }
      .card-ukuran small {
        font-size: 0.7rem;
      }
      .btn-dark {
        padding: 12px;
        font-size: 1rem;
      }
      .review-card {
        padding: 12px 15px;
      }
      .review-section {
        margin-bottom: 50px; /* Lebih banyak margin bottom untuk layar kecil */
      }
      .review-section h4 {
        font-size: 1.2rem;
      }
      /* Main content padding untuk memberikan ruang */
      .main-content {
        padding-bottom: 160px; /* Increased padding untuk mencegah terpotong */
      }
    }
    /* Sticky bottom button for mobile */
    @media (max-width: 768px) {
      .mobile-sticky-footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 15px;
        box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
        border-top: 1px solid #eee;
        min-height: 80px; /* Pastikan tinggi minimum */
      }
      .main-content {
        padding-bottom: 140px; /* Padding bottom untuk main content */
      }
      .mobile-sticky-footer .btn {
        width: 100%;
        padding: 15px;
        font-size: 1.1rem;
        font-weight: 600;
      }
      .desktop-submit {
        display: none;
      }
    }
    @media (min-width: 769px) {
      .mobile-sticky-footer {
        display: none;
      }
      .desktop-submit {
        display: block;
      }
      .main-content {
        padding-bottom: 30px; /* Normal padding untuk desktop */
      }
    }
    /* Tambahan CSS untuk memastikan ulasan tidak terpotong */
    .review-section {
      position: relative;
      z-index: 1; /* Pastikan review section di atas sticky footer */
    }
    .review-container {
      padding-bottom: 20px; /* Tambahan padding untuk review container */
    }
    @media (max-width: 820px) {
      .main-content {
        padding-bottom: 140px !important;
      }
      .review-section {
        margin-bottom: 60px !important;
      }
      .review-container {
        padding-bottom: 30px !important;
      }
      .review-card {
        width: 100% !important;
        box-sizing: border-box;
        word-break: break-word;
        overflow-wrap: break-word;
      }
    }
  </style>

  <script>
    const ukuranData = <?= json_encode($ukuran_list) ?>;

    function pilihUkuran(id) {
      // Cek apakah ukuran ini tersedia (stok > 0)
      const ukuranTerpilih = ukuranData.find(u => u.id == id);
      if (!ukuranTerpilih || ukuranTerpilih.stok <= 0) {
        alert('Maaf, ukuran ini sedang tidak tersedia (stok habis)');
        return;
      }

      document.getElementById('ukuran').value = id;
      document.getElementById('ukuran-mobile').value = id;
      updateJumlahMax();
      document.querySelectorAll('.card-ukuran').forEach(el => el.classList.remove('active'));
      document.getElementById('ukuran-card-' + id).classList.add('active');
    }

    function updateJumlahMax() {
      const selectedUkuranId = document.getElementById('ukuran').value;
      const jumlahInput = document.getElementById('jumlah');
      const jumlahInputMobile = document.getElementById('jumlah-mobile');
      const submitBtn = document.querySelector('button[type="submit"]');
      const submitBtnMobile = document.querySelector('.mobile-sticky-footer button[type="submit"]');
      const ukuranTerpilih = ukuranData.find(u => u.id == selectedUkuranId);

      if (ukuranTerpilih && ukuranTerpilih.stok > 0) {
        jumlahInput.max = ukuranTerpilih.stok;
        jumlahInput.value = Math.min(jumlahInput.value || 1, ukuranTerpilih.stok);
        jumlahInput.disabled = false;
        jumlahInput.min = 1;
        if (jumlahInputMobile) {
          jumlahInputMobile.max = ukuranTerpilih.stok;
          jumlahInputMobile.value = jumlahInput.value;
          jumlahInputMobile.disabled = false;
          jumlahInputMobile.min = 1;
        }
        if (submitBtn) submitBtn.disabled = false;
        if (submitBtnMobile) submitBtnMobile.disabled = false;
        document.getElementById('stokInfo').innerText = `Stok tersedia: ${ukuranTerpilih.stok}`;
        document.getElementById('stokInfo').className = 'form-text text-success';
      } else if (ukuranTerpilih && ukuranTerpilih.stok === 0) {
        jumlahInput.max = 0;
        jumlahInput.value = 0;
        jumlahInput.disabled = true;
        if (jumlahInputMobile) {
          jumlahInputMobile.max = 0;
          jumlahInputMobile.value = 0;
          jumlahInputMobile.disabled = true;
        }
        if (submitBtn) submitBtn.disabled = true;
        if (submitBtnMobile) submitBtnMobile.disabled = true;
        document.getElementById('stokInfo').innerText = `Stok habis - tidak tersedia`;
        document.getElementById('stokInfo').className = 'form-text text-danger';
      } else {
        jumlahInput.max = 0;
        jumlahInput.value = 0;
        jumlahInput.disabled = true;
        if (jumlahInputMobile) {
          jumlahInputMobile.max = 0;
          jumlahInputMobile.value = 0;
          jumlahInputMobile.disabled = true;
        }
        if (submitBtn) submitBtn.disabled = true;
        if (submitBtnMobile) submitBtnMobile.disabled = true;
        document.getElementById('stokInfo').innerText = `Pilih ukuran terlebih dahulu`;
        document.getElementById('stokInfo').className = 'form-text text-muted';
      }
    }

    // Validasi saat input jumlah berubah
    function validateJumlah() {
      const jumlahInput = document.getElementById('jumlah');
      const jumlahInputMobile = document.getElementById('jumlah-mobile');
      const selectedUkuranId = document.getElementById('ukuran').value;
      const ukuranTerpilih = ukuranData.find(u => u.id == selectedUkuranId);

      if (ukuranTerpilih) {
        if (parseInt(jumlahInput.value) > ukuranTerpilih.stok) {
          jumlahInput.value = ukuranTerpilih.stok;
        }
        if (parseInt(jumlahInput.value) < 1) {
          jumlahInput.value = 1;
        }
        // Sync mobile input
        if (jumlahInputMobile) {
          jumlahInputMobile.value = jumlahInput.value;
        }
      }
    }
    function validateJumlahMobile() {
      const jumlahInput = document.getElementById('jumlah');
      const jumlahInputMobile = document.getElementById('jumlah-mobile');
      const selectedUkuranId = document.getElementById('ukuran').value;
      const ukuranTerpilih = ukuranData.find(u => u.id == selectedUkuranId);
      if (ukuranTerpilih) {
        if (parseInt(jumlahInputMobile.value) > ukuranTerpilih.stok) {
          jumlahInputMobile.value = ukuranTerpilih.stok;
        }
        if (parseInt(jumlahInputMobile.value) < 1) {
          jumlahInputMobile.value = 1;
        }
        
        // Sync desktop input
        jumlahInput.value = jumlahInputMobile.value;
      }
    }

    document.addEventListener('DOMContentLoaded', function() {
      updateJumlahMax();

      // Add event listener untuk input jumlah
      const jumlahInput = document.getElementById('jumlah');
      const jumlahInputMobile = document.getElementById('jumlah-mobile');
      if (jumlahInput) {
        jumlahInput.addEventListener('input', validateJumlah);
        jumlahInput.addEventListener('change', validateJumlah);
      }
      if (jumlahInputMobile) {
        jumlahInputMobile.addEventListener('input', validateJumlahMobile);
        jumlahInputMobile.addEventListener('change', validateJumlahMobile);
      }

      // Disable submit button initially
      const submitBtn = document.querySelector('button[type="submit"]');
      const submitBtnMobile = document.querySelector('.mobile-sticky-footer button[type="submit"]');
      if (submitBtn) submitBtn.disabled = true;
      if (submitBtnMobile) submitBtnMobile.disabled = true;
    });
  </script>
</head>

<body>
  <div class="container py-3 main-content">
    <?php if (isset($_SESSION['error'])): ?>
      <div class="alert alert-danger"><?= $_SESSION['error'] ?></div>
      <?php unset($_SESSION['error']); ?>
    <?php endif; ?>
    <div class="row">
      <div class="col-md-6">
        <img src="upload/<?= htmlspecialchars($produk['gambar']) ?>" alt="<?= htmlspecialchars($produk['nama']) ?>" class="product-image">
      </div>
      <div class="col-md-6 product-details">
        <h2 class="product-title"><?= htmlspecialchars($produk['nama']) ?></h2>
        <p class="text-muted product-category"><strong>Kategori:</strong> <?= htmlspecialchars($produk['nama_kategori']) ?></p>
        <p class="product-description"><?= nl2br(htmlspecialchars($produk['deskripsi'])) ?></p>
        <div class="product-price mt-4">
          <?php if ($diskon):
            $harga_diskon = $produk['harga'] - ($produk['harga'] * $diskon['persen'] / 100);
          ?>
            <span class="badge bg-danger mb-2 discount-badge">Diskon <?= $diskon['persen'] ?>% OFF</span><br>
            <span class="text-muted text-decoration-line-through original-price">Rp<?= number_format($produk['harga'], 0, ',', '.') ?></span>
            <span class="h4 fw-bold text-primary ms-2 discounted-price">Rp<?= number_format($harga_diskon, 0, ',', '.') ?></span>
          <?php else: ?>
            <span class="h4">Rp<?= number_format($produk['harga'], 0, ',', '.') ?></span>
          <?php endif; ?>
        </div>

        <form action="pelanggan/tambah_keranjang.php" method="POST" class="mt-4">
          <input type="hidden" name="produk_id" value="<?= $produk['id'] ?>">
          <input type="hidden" id="ukuran" name="ukuran_id" required>

          <div class="mb-3">
            <label class="form-label">Pilih Ukuran</label>
            <div class="ukuran-container">
              <?php foreach ($ukuran_list as $u): ?>
                <div
                  id="ukuran-card-<?= $u['id'] ?>"
                  class="p-3 border rounded text-center card-ukuran <?= $u['stok'] <= 0 ? 'disabled' : '' ?>"
                  onclick="<?= $u['stok'] > 0 ? 'pilihUkuran(' . $u['id'] . ')' : '' ?>"
                  <?= $u['stok'] <= 0 ? 'title="Stok habis - tidak tersedia"' : '' ?>>
                  <div class="fw-bold"><?= htmlspecialchars($u['ukuran']) ?></div>
                  <small class="<?= $u['stok'] <= 0 ? 'text-danger' : 'text-muted' ?>">
                    <?= $u['stok'] <= 0 ? 'Stok Habis' : 'Stok: ' . $u['stok'] ?>
                  </small>
                </div>
              <?php endforeach; ?>
            </div>
          </div>

          <div class="mb-3 mt-3">
            <label for="jumlah" class="form-label">Jumlah</label>
            <input type="number" class="form-control" id="jumlah" name="jumlah" min="1" value="1" required>
            <div id="stokInfo" class="form-text text-muted">Pilih ukuran untuk melihat stok</div>
          </div>

          <?php if (isset($_SESSION['user_id'])): ?>
            <button type="submit" class="btn btn-dark desktop-submit">Tambah ke Keranjang</button>
          <?php else: ?>
            <div class="alert alert-info">Silakan <a href="login.php">login</a> terlebih dahulu untuk membeli produk.</div>
          <?php endif; ?>
        </form>
      </div>
    </div>

    <!-- ULASAN PRODUK MULAI -->
    <div class="row mt-2">
      <div class="col-md-8 offset-md-2 review-section">
        <div class="review-container">
        <h4>Ulasan Produk</h4>
        <?php
        // Tampilkan review yang sudah di-approve
        $stmt_ulasan = $conn->prepare("SELECT up.*, p.nama as nama_pengguna FROM ulasan_produk up JOIN pengguna p ON up.id_pelanggan = p.id WHERE up.id_produk = ? AND up.status = 'approved' ORDER BY up.tanggal_ulasan DESC");
        if ($stmt_ulasan) {
          $stmt_ulasan->bind_param("i", $id);
          $stmt_ulasan->execute();
          $result_ulasan = $stmt_ulasan->get_result();
        } else {
          echo "Error preparing statement: " . $conn->error;
          $result_ulasan = null;
        }
        if ($result_ulasan && $result_ulasan->num_rows > 0):
          while ($ulasan = $result_ulasan->fetch_assoc()):
        ?>
            <div class="review-card">
              <div class="d-flex align-items-center mb-2">
                <span class="review-user"><i class="bi bi-person-circle"></i> <?= htmlspecialchars($ulasan['nama_pengguna']) ?></span>
                <span class="review-date ms-3"><i class="bi bi-clock"></i> <?= date('d M Y H:i', strtotime($ulasan['tanggal_ulasan'])) ?></span>
              </div>
              <div class="review-rating">
                <?php for ($i = 1; $i <= 5; $i++): ?>
                  <?php if ($i <= $ulasan['rating']): ?>
                    <i class="bi bi-star-fill"></i>
                  <?php else: ?>
                    <i class="bi bi-star"></i>
                  <?php endif; ?>
                <?php endfor; ?>
              </div>
              <p class="review-text"><span class="review-quote">"<?= nl2br(htmlspecialchars($ulasan['isi_ulasan'])) ?>"</span></p>
            </div>
          <?php endwhile;
        else: ?>
          <div class="alert alert-info">Belum ada ulasan untuk produk ini.</div>
        <?php endif; ?>
      </div>
    </div>
    <!-- ULASAN PRODUK SELESAI -->
  </div>

    <!-- Mobile Sticky Footer untuk tombol tambah keranjang -->
  <?php if (isset($_SESSION['user_id'])): ?>
    <div class="mobile-sticky-footer">
      <form action="pelanggan/tambah_keranjang.php" method="POST">
        <input type="hidden" name="produk_id" value="<?= $produk['id'] ?>">
        <input type="hidden" id="ukuran-mobile" name="ukuran_id" required>
        <input type="hidden" id="jumlah-mobile" name="jumlah" value="1" required>
        <button type="submit" class="btn btn-dark">Tambah ke Keranjang</button>
      </form>
    </div>
  <?php endif; ?>
  <script>
    // Notifikasi auto-dismiss
    setTimeout(function() {
      var notif = document.getElementById('notif-review');
      if (notif) {
        notif.style.transition = 'opacity 0.5s';
        notif.style.opacity = 0;
        setTimeout(function() {
          notif.remove();
        }, 500);
      }
    }, 2000);
  </script>
</body>

</html>