<?php
if (session_status() == PHP_SESSION_NONE) {
  session_start();
}
include '../../config.php';
include '../sidebar.php';

// Ambil data produk dan kategorinya
$query = "SELECT produk.*, kategori_produk.nama AS nama_kategori FROM produk 
          LEFT JOIN kategori_produk ON produk.kategori_id = kategori_produk.id ORDER BY dibuat_pada DESC";
$result = mysqli_query($conn, $query);

// Ambil kategori untuk dropdown
$kategori = mysqli_query($conn, "SELECT * FROM kategori_produk");
?>

<!DOCTYPE html>
<html lang="id">

<head>
  <title>Data Produk</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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: #f4f7f6;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      color: #333;
    }

    .main-header {
      font-size: 2.2rem;
      font-weight: 700;
      color: #2c3e50;
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 2px solid #eee;
      text-align: center;
    }

    .table {
      background-color: #fff;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
      margin-top: 20px;
    }

    .table thead th {
      background-color: #ecf0f1;
      color: #555;
      font-weight: 600;
      border-bottom: 1px solid #dee2e6;
      padding: 12px 15px;
      text-transform: uppercase;
      font-size: 0.9em;
    }

    .table tbody tr:hover {
      background-color: #f9f9f9;
    }

    .table td {
      padding: 12px 15px;
      vertical-align: middle;
      font-size: 0.95em;
    }

    .aksi-btns {
      display: flex;
      gap: 8px;
    }

    .btn-primary {
      background-color: #34495e;
      border-color: #34495e;
      transition: all 0.3s ease;
      font-weight: 600;
      padding: 10px 20px;
      border-radius: 8px;
    }

    .btn-primary:hover {
      background-color: #2c3e50;
      border-color: #2c3e50;
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    .btn-sm {
      padding: .3rem .75rem;
      font-size: .875rem;
      border-radius: .4rem;
    }

    .btn-close {
      font-size: 0.9em;
    }

    .alert {
      border-radius: 8px;
      font-size: 1.05em;
      padding: 15px 20px;
      margin-bottom: 25px;
    }

    .alert-success {
      background-color: #d4edda;
      color: #155724;
      border-color: #c3e6cb;
    }

    .btn-edit,
    .btn-hapus {
      background: transparent !important;
      border: none !important;
      color: #222 !important;
      font-weight: 600;
      box-shadow: none !important;
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }

    .btn-edit i,
    .btn-hapus i {
      color: #222 !important;
    }

    @media (max-width: 900px) {
      .table-responsive {
        font-size: 0.97rem;
      }
    }
  </style>
</head>

<body>
  <div class="container-fluid">
    <div class="card" style="border-radius:16px;box-shadow:0 4px 20px rgba(0,0,0,0.05);background:#fff;width:100%;max-width:100%;padding:32px 24px 24px 24px;margin-top:32px;">
      <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#modalTambah"><i class="bi bi-plus-circle"></i> Tambah Produk</button>
      <?php if (isset($_SESSION['alert'])): ?>
        <div class="alert alert-<?= $_SESSION['alert']['type'] ?? 'success' ?> alert-dismissible fade show" role="alert">
          <?= $_SESSION['alert']['message'] ?? $_SESSION['alert'] ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['alert']); ?>
      <?php endif; ?>
      <div class="table-responsive">
        <table class="table table-hover">
          <thead>
            <tr>
              <th>Nama</th>
              <th>Harga</th>
              <th>Kategori</th>
              <th>Gambar</th>
              <th>Ukuran & Stok</th>
              <th>Diskon</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row = mysqli_fetch_assoc($result)) : ?>
              <tr>
                <td><?= htmlspecialchars($row['nama']) ?></td>
                <td>Rp<?= number_format($row['harga']) ?></td>
                <td><?= htmlspecialchars($row['nama_kategori']) ?></td>
                <td><img src="../../upload/<?= $row['gambar'] ?>" width="60"></td>
                <td>
                  <?php
                  $ukuran_result = mysqli_query($conn, "SELECT * FROM ukuran_produk WHERE produk_id = {$row['id']}");
                  while ($uk = mysqli_fetch_assoc($ukuran_result)) {
                    echo htmlspecialchars($uk['ukuran']) . ' (' . $uk['stok'] . ')<br>';
                  }
                  ?>
                </td>
                <td>
                  <?php
                  if (!empty($row['diskon_id'])) {
                    $diskon = mysqli_query($conn, "SELECT * FROM diskon WHERE id = {$row['diskon_id']} AND aktif = 'ya'");
                    if ($d = mysqli_fetch_assoc($diskon)) {
                      echo htmlspecialchars($d['nama_diskon']) . ' (' . $d['persen'] . '%)';
                    } else {
                      echo '-';
                    }
                  } else {
                    echo '-';
                  }
                  ?>
                </td>
                <td>
                  <div class="aksi-btns">
                    <button class="btn btn-edit btn-sm" data-bs-toggle="modal" data-bs-target="#modalEdit<?= $row['id'] ?>"><i class="bi bi-pencil"></i> Edit</button>
                    <a href="hapus_produk.php?id=<?= $row['id'] ?>" onclick="return confirm('Yakin hapus?')" class="btn btn-hapus btn-sm"><i class="bi bi-trash"></i> Hapus</a>
                  </div>
                </td>
              </tr>

              <?php
              ob_start(); // tampung output modal ke buffer
              ?>
              <div class="modal fade" id="modalEdit<?= $row['id'] ?>" tabindex="-1">
                <div class="modal-dialog">
                  <form action="edit_produk.php" method="POST" enctype="multipart/form-data" class="modal-content">
                    <div class="modal-header">
                      <h5>Edit Produk</h5>
                      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                      <input type="hidden" name="id" value="<?= $row['id'] ?>">
                      <div class="mb-2">
                        <label>Nama</label>
                        <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($row['nama']) ?>" required>
                      </div>
                      <div class="mb-2">
                        <label>Deskripsi</label>
                        <textarea name="deskripsi" class="form-control"><?= htmlspecialchars($row['deskripsi']) ?></textarea>
                      </div>
                      <div class="mb-2">
                        <label>Harga</label>
                        <input type="number" name="harga" class="form-control" value="<?= $row['harga'] ?>" required>
                      </div>
                      <div class="mb-3">
                        <?php $ukuran_result = mysqli_query($conn, "SELECT * FROM ukuran_produk WHERE produk_id = {$row['id']}"); ?>
                        <label>Ukuran & Stok</label>
                        <div id="ukuran-container-<?= $row['id'] ?>">
                          <?php while ($uk = mysqli_fetch_assoc($ukuran_result)): ?>
                            <div class="row mb-2 ukuran-item">
                              <div class="col">
                                <input type="text" name="ukuran[]" class="form-control" value="<?= htmlspecialchars($uk['ukuran']) ?>" required>
                              </div>
                              <div class="col">
                                <input type="number" name="stok_ukuran[]" class="form-control" value="<?= $uk['stok'] ?>" required>
                              </div>
                              <div class="col-auto">
                                <button type="button" class="btn btn-danger btn-remove">Hapus</button>
                              </div>
                            </div>
                          <?php endwhile; ?>
                        </div>
                        <button type="button" class="btn btn-sm btn-secondary tambah-ukuran" data-target="#ukuran-container-<?= $row['id'] ?>">+ Tambah Ukuran</button>
                      </div>

                      <div class="mb-2">
                        <label>Kategori</label>
                        <select name="kategori_id" class="form-control" required>
                          <?php mysqli_data_seek($kategori, 0);
                          while ($kat = mysqli_fetch_assoc($kategori)): ?>
                            <option value="<?= $kat['id'] ?>" <?= $kat['id'] == $row['kategori_id'] ? 'selected' : '' ?>>
                              <?= $kat['nama'] ?>
                            </option>
                          <?php endwhile; ?>
                        </select>
                      </div>
                      <div class="mb-2">
                        <label>Gambar</label>
                        <input type="file" name="gambar" class="form-control">
                        <small>Biarkan kosong jika tidak ganti gambar</small>
                      </div>
                      <div class="mb-3">
                        <label for="diskon_id_edit_<?= $row['id'] ?>" class="form-label">Diskon</label>
                        <select name="diskon_id" id="diskon_id_edit_<?= $row['id'] ?>" class="form-select">
                          <option value="">Tanpa Diskon</option>
                          <?php
                          $diskon_opt = mysqli_query($conn, "SELECT * FROM diskon WHERE aktif = 'ya'");
                          while ($d = mysqli_fetch_assoc($diskon_opt)) {
                            $selected = ($row['diskon_id'] == $d['id']) ? 'selected' : '';
                            echo '<option value="' . $d['id'] . '" ' . $selected . '>' . htmlspecialchars($d['nama_diskon']) . ' (' . $d['persen'] . '%)</option>';
                          }
                          ?>
                        </select>
                      </div>
                    </div>
                    <div class="modal-footer">
                      <button class="btn btn-primary">Simpan</button>
                      <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    </div>
                  </form>
                </div>
              </div>
              <?php
              $modalEdit[] = ob_get_clean(); // simpan modal ke array
              ?>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Cetak semua modal edit produk di bawah tabel -->
  <?php
  if (!empty($modalEdit)) {
    foreach ($modalEdit as $modal) {
      echo $modal;
    }
  }
  ?>


  <!-- Modal Tambah -->
  <div class="modal fade" id="modalTambah" tabindex="-1">
    <div class="modal-dialog">
      <form action="tambah_produk.php" method="POST" enctype="multipart/form-data" class="modal-content">
        <div class="modal-header">
          <h5>Tambah Produk</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="mb-2">
            <label>Nama</label>
            <input type="text" name="nama" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Deskripsi</label>
            <textarea name="deskripsi" class="form-control"></textarea>
          </div>
          <div class="mb-2">
            <label>Harga</label>
            <input type="number" name="harga" class="form-control" required>
          </div>
          <div id="ukuran-container">
            <div class="row mb-2 ukuran-item">
              <div class="col">
                <input type="text" name="ukuran[]" class="form-control" placeholder="Ukuran (contoh: S)" required>
              </div>
              <div class="col">
                <input type="number" name="stok_ukuran[]" class="form-control" placeholder="Stok ukuran ini" required>
              </div>
              <div class="col-auto">
                <button type="button" class="btn btn-danger btn-remove">Hapus</button>
              </div>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-secondary" id="tambah-ukuran">+ Tambah Ukuran</button>
          <div class="mb-2">
            <label>Kategori</label>
            <select name="kategori_id" class="form-control" required>
              <option value="">-- Pilih Kategori --</option>
              <?php mysqli_data_seek($kategori, 0);
              while ($kat = mysqli_fetch_assoc($kategori)): ?>
                <option value="<?= $kat['id'] ?>"><?= $kat['nama'] ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="mb-2">
            <label>Gambar</label>
            <input type="file" name="gambar" class="form-control" required>
          </div>
          <div class="mb-3">
            <label for="diskon_id" class="form-label">Diskon</label>
            <select name="diskon_id" id="diskon_id" class="form-select">
              <option value="">Tanpa Diskon</option>
              <?php
              $diskon_opt = mysqli_query($conn, "SELECT * FROM diskon WHERE aktif = 'ya'");
              while ($d = mysqli_fetch_assoc($diskon_opt)) {
                echo '<option value="' . $d['id'] . '">' . htmlspecialchars($d['nama_diskon']) . ' (' . $d['persen'] . '%)</option>';
              }
              ?>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary">Simpan</button>
          <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    document.getElementById('tambah-ukuran').addEventListener('click', function() {
      const container = document.getElementById('ukuran-container');
      const item = document.createElement('div');
      item.className = 'row mb-2 ukuran-item';
      item.innerHTML = `
      <div class="col">
        <input type="text" name="ukuran[]" class="form-control" placeholder="Ukuran (contoh: M)" required>
      </div>
      <div class="col">
        <input type="number" name="stok_ukuran[]" class="form-control" placeholder="Stok ukuran ini" required>
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-danger btn-remove">Hapus</button>
      </div>
    `;
      container.appendChild(item);
    });

    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('btn-remove')) {
        e.target.closest('.ukuran-item').remove();
      }
    });

    document.querySelectorAll('.tambah-ukuran').forEach(button => {
      button.addEventListener('click', function() {
        const containerId = this.getAttribute('data-target');
        const container = document.querySelector(containerId);
        const newRow = document.createElement('div');
        newRow.className = 'row mb-2 ukuran-item';
        newRow.innerHTML = `
      <div class="col">
        <input type="text" name="ukuran[]" class="form-control" placeholder="Ukuran (contoh: S)" required>
      </div>
      <div class="col">
        <input type="number" name="stok_ukuran[]" class="form-control" placeholder="Stok ukuran ini" required>
      </div>
      <div class="col-auto">
        <button type="button" class="btn btn-danger btn-remove">Hapus</button>
      </div>
    `;
        container.appendChild(newRow);
      });
    });

    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('btn-remove')) {
        e.target.closest('.ukuran-item').remove();
      }
    });
  </script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>