<?php
// koneksi ke database
// error_reporting(0);
include 'connection.php';

// Mendapatkan data dealer untuk dropdown
$dealer_query = "SELECT subyek, kode_lks FROM fkt_dealer where grup='LT' AND nonaktif=0 and kode_lks NOT IN ('FLEET01','GUDANG UNIT') order by urutan";
$dealer_result = $conn->query($dealer_query);

// Mendapatkan data tipe untuk dropdown
$tipe_query = "SELECT tipe FROM allocation_stock GROUP BY tipe order by tipe";
$tipe_result = $conn->query($tipe_query);

?>

<!DOCTYPE html>
<html lang="en">
<?php
include 'head.php';
?>

<body>

  <?php
  include 'header.php';
  ?>



  <?php
  $activeMenu = 'allocation'; // Sesuaikan dengan halaman yang sedang dibuka
  include 'sidebar.php';
  ?>



  <main id="main" class="main">

    <div class="pagetitle">
      <h1>Allocation</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">Home</a></li>
          <li class="breadcrumb-item active">Allocation</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section dashboard">
      <div class="row">

        <!-- Left side columns -->
        <div class="col-lg-12">
          <div class="row">

            <!-- Filter Stok Unit -->
            <div class="col-12">
              <div class="card recent-sales overflow-auto">

                <div class="card-body">
                  <h5 class="card-title">Filter Stok Dealer</h5>

                  <form method="POST" action="" class="row g-3 align-items-end">
                    <div class="col-md-6">
                      <label for="dealer" class="form-label">Dealer</label>
                      <select name="kode_lks" id="dealer" class="form-control select2">
                        <option value="" disabled selected hidden>Pilih Dealer</option>
                        <?php
                        if ($dealer_result->num_rows > 0) {
                          while ($dealer = $dealer_result->fetch_assoc()) {
                        ?>
                            <option value="<?php echo "$dealer[kode_lks]" ?>"
                              <?php if (isset($_POST['kode_lks']) && $_POST['kode_lks'] == $dealer['kode_lks']) { ?>selected="" <?php } ?>>
                              <?php echo htmlspecialchars($dealer['subyek']) ?></option>
                        <?php
                          }
                        }
                        ?>
                      </select>
                    </div>

                    <div class="col-md-4">
                      <label for="tipe" class="form-label">Tipe</label>
                      <select name="tipe" id="tipe" class="form-control">
                        <option value="" disabled selected hidden>Pilih tipe</option>
                        <?php
                        if ($tipe_result->num_rows > 0) {
                          while ($tipe = $tipe_result->fetch_assoc()) {
                        ?>
                            <option value="<?php echo "$tipe[tipe]" ?>"
                              <?php if (isset($_POST['tipe']) && $_POST['tipe'] == $tipe['tipe']) { ?>selected="" <?php } ?>>
                              <?php echo htmlspecialchars($tipe['tipe']) ?></option>
                        <?php
                          }
                        }
                        ?>
                      </select>
                    </div>


                    <div class="col-md-2 d-flex justify-content-end">
                      <button type="submit" class="btn btn-primary mt-3 w-100">Tampilkan</button>
                    </div>
                  </form><!-- End Custom Styled Validation with Tooltips -->

                </div>

              </div>
            </div><!-- End Filter Stok Unit -->

            <!-- Table -->
            <div class="col-12">
              <div class="card recent-sales">

                <div class="card-body">



                  <?php
                  // Menangani form submission
                  if ($_SERVER["REQUEST_METHOD"] == "POST") {
                    $dealer_id = $_POST['kode_lks'];
                    $tipe = $_POST['tipe'];

                    // Validasi input
                    if (empty($dealer_id) || empty($tipe)) {
                      echo "<br><div class='alert alert-danger'>Pastikan anda memilih Dealer, tipe, dan warna.</div>";
                    } else {


                      // Query untuk mengambil data berdasarkan dealer_id, tipe, dan warna
                      $sql = "SELECT *
                          FROM allocation_stock
                          WHERE dealer_id = '$dealer_id' AND tipe = '$tipe'";
                      // echo $sql; // Debugging: menampilkan query
                      $result = $conn->query($sql);

                      if ($result->num_rows > 0) {
                        // Query untuk mengambil nama dealer secara terpisah
                        $sql_name = "SELECT *
                              FROM fkt_dealer
                              WHERE kode_lks = '$dealer_id' LIMIT 1";
                        $result_name = $conn->query($sql_name);

                        if ($result_name->num_rows > 0) {
                          $row_name = $result_name->fetch_assoc();
                          $subyek = $row_name['subyek'];
                        } else {
                          $subyek = "Nama dealer tidak ditemukan";
                        }
                  ?>
                        <!-- Display Dealer and Period -->

                        <div class="overflow-auto">
                          <h3 class="card-title text-center mt-4 mb-1"><strong>STOK DEALER <br><?php echo $subyek; ?></strong> </h3>

                          <table class='table table-hover table-bordered align-middle text-center'>
                            <thead class="thead-light align-middle">
                              <tr>
                                <th rowspan="3" width="200px">Tipe</th>
                                <th rowspan="3">Warna</th>
                                <th colspan="4">Pendapatan</th>
                              </tr>
                              <tr>
                                <th>Selling In</th>
                                <th>STU/Faktur</th>
                                <th>Stok Akhir</th>
                                <th  rowspan="2"><span data-bs-toggle="tooltip" data-bs-placement="top" title="Urgensi stock">Rasio Stock</th>
                              </tr>
                              <tr>
                                <th>Unit</th>
                                <th>Unit</th>
                                <th>Unit</th>
                              </tr>
                            </thead>
                            <tbody>
                            <?php
                            // Hitung jumlah baris untuk warna berdasarkan tipe
                            $warna_result = $conn->query("SELECT * FROM allocation_tipewarna WHERE nama_tipe = '$tipe'");
                            $row_count = $warna_result->num_rows;

                            if ($row_count > 0) {
                              // Menampilkan tipe dengan rowspan
                              echo "<tr>";
                              echo "<td rowspan=". $row_count . " class=\"text-start\">" . $tipe . "</td>";

                              // Looping melalui data warna dari allocation_tipewarna
                              while ($row_warna = $warna_result->fetch_assoc()) {
                                echo "<td>" . $row_warna['warna'] . "</td>"; // Menampilkan warna

                                // Query untuk mendapatkan data yang sesuai berdasarkan tipe dan warna
                                $result = $conn->query("SELECT * FROM allocation_stock WHERE dealer_id = '$dealer_id' AND tipe = '$tipe'");

                                $found = false; // Flag untuk cek apakah data ditemukan
                                while ($row = $result->fetch_assoc()) {
                                  // Jika warna dari allocation_stock sama dengan warna dari allocation_tipewarna
                                  if ($row_warna['warna'] == $row['warna']) {
                                    echo "<td>" . $row['qty'] . "</td>"; // Tampilkan qty
                                    echo "<td>0</td>"; // STU/Faktur
                                    echo "<td>" . $row['qty'] . "</td>"; // Stok Akhir
                                    echo "<td>0</td>"; // Rasio Stock
                                    $found = true;
                                  }
                                }

                                // Jika tidak ditemukan data, tampilkan 0
                                if (!$found) {
                                  echo "<td>0</td>";
                                  echo "<td>0</td>";
                                  echo "<td>0</td>";
                                  echo "<td>0</td>";
                                }

                                echo "</tr>";
                              }
                            } else {
                              echo "<tr><td colspan='5'>Tidak ada data warna untuk tipe yang dipilih</td></tr>";
                            }
                            ?>
                          </tbody>

                          </table>
                        </div>

                    <?php
                      } else {
                        echo "<div class='alert alert-danger mt-4 mb-1'>Tidak ada data yang ditemukan untuk Dealer dan Tipe yang dipilih.</div>";
                      }
                    }
                  } else { ?>
                    <!-- Default Title -->
                    <div class="alert alert-warning text-center mt-4 mb-1" role="alert">
                      <h3 class="card-title">Silahkan Pilih Dealer, tipe dan warna</h3>
                    </div>
                  <?php } ?>

                </div>

              </div>
            </div><!-- End Table -->


          </div>
        </div><!-- End Left side columns -->


      </div>
    </section>

  </main><!-- End #main -->


  <?php
  include 'footer.php';
  ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/chart.js/chart.umd.js"></script>
  <script src="assets/vendor/echarts/echarts.min.js"></script>
  <script src="assets/vendor/quill/quill.js"></script>
  <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>


  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>


  <script>
    $(document).ready(function() {
      $('#dealer').select2({
        theme: 'bootstrap-5', // Menggunakan tema Bootstrap 5
        placeholder: "Pilih Dealer",
        allowClear: true
      });
    });

    function loadTargetDealer(dealerCode, nameDealer, tipe, warna) {
      $.ajax({
        url: 'get_target_dealer_data.php',
        type: 'POST',
        data: {
          kode_lks: dealerCode,
          subyek: nameDealer,
          tipe: tipe,
          warna: warna
        },
        success: function(response) {
          // Tampilkan data di dalam modal
          $('#modalContent').html(response);

          // Update the edit button's href to point to target_dealer_edit.php with the right parameters
          $('#editBtn').click(function() {
            window.location.href = 'target_dealer_edit.php?kode_lks=' + dealerCode +
              '&subyek=' + nameDealer +
              '&tipe=' + tipe +
              '&warna=' + warna;
          });
        },
        error: function() {
          $('#modalContent').html('<p>Error loading data.</p>');
        }
      });
    }
  </script>

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


</body>

</html>