<?php
session_start();

// Cek apakah user sudah login
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  // Jika belum login, redirect ke halaman login
  header("Location: login.php");
  exit();
}

$nama = isset($_SESSION['nama']) ? $_SESSION['nama'] : ''; // Jika belum login, tampilkan 'User' sebagai default
$user = isset($_SESSION['user']) ? $_SESSION['user'] : ''; // Jika belum login, tampilkan 'User' sebagai default
$jenis = isset($_SESSION['jenis']) ? $_SESSION['jenis'] : ''; // Jika belum login, tampilkan 'User' sebagai default

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


$tanggal = date('Y-m-d');

// Mendapatkan data stock wh
$query_stock = "SELECT * FROM `allocation_savewarehouse` WHERE tanggal = '$tanggal'";
$result_wh = $conn->query($query_stock);
// // Mendapatkan data stock wh
// $query_stock = "SELECT * FROM `allocation_stockwh`";
// $result_wh = $conn->query($query_stock);

// Mendapatkan data penjualan tiap dealer
$query_sl = "SELECT * FROM `allocation_sl` WHERE bulan = MONTH(CURDATE()) AND tahun = YEAR(CURDATE())";
$result_sl = $conn->query($query_sl);

// Mendapatkan data tipe dan warna
$query_tipewarna = "SELECT DISTINCT tipe, warna FROM `allocation_stockwh`";
$result_tipewarna = $conn->query($query_tipewarna);



// Menyusun array tipe dengan warna terkaitnya
$tipeWarna = [];
while ($row = $result_tipewarna->fetch_assoc()) {
  $tipeWarna[$row['tipe']][] = $row['warna'];
}

// Hitung jumlah tipe dan warna untuk pengaturan colspan
$jumlah_tipe = count($tipeWarna);
$colspan_per_tipe = 4; // Asumsi 4 kolom per warna
$colspan_total = $colspan_per_tipe * $jumlah_tipe;


// Query untuk mendapatkan tanggal dari allocation_savewarehouse
$query_tgl_wh = "SELECT tanggal FROM `allocation_savewarehouse` GROUP BY tanggal";
$tgl_wh_result = $conn->query($query_tgl_wh);

// Query untuk mendapatkan tanggal dari allocation_savedealer
$query_tgl_d = "SELECT tanggal FROM `allocation_savedealer` GROUP BY tanggal";
$tgl_d_result = $conn->query($query_tgl_d);



if ($jenis == 'aom') {
  $query = "
      SELECT d.subyek, d.kode_lks, a.tipe, a.warna, a.sl, a.st, a.rs, a.al
      FROM fkt_dealer d
      LEFT JOIN allocation_savedealer a
      ON d.kode_lks = a.kode_lks
      WHERE a.tanggal='$tanggal' AND d.grup='LT' AND d.nonaktif = 0
      AND d.kode_lks NOT IN ('FLEET01','GUDANG UNIT','MD')
      AND d.aom='$user'
      ORDER BY d.urutan";
} else {
  $query = "
      SELECT d.subyek, d.kode_lks, a.tipe, a.warna, a.sl, a.st, a.rs, a.al
      FROM fkt_dealer d
      LEFT JOIN allocation_savedealer a
      ON d.kode_lks = a.kode_lks
      WHERE a.tanggal='$tanggal' AND d.grup='LT' AND d.nonaktif = 0
      AND d.kode_lks NOT IN ('FLEET01','GUDANG UNIT','MD')
      ORDER BY d.urutan";
}



$result = $conn->query($query);

// Menyusun array tipe, warna dengan soh, dh, dan ssh
$qtyWhSoh = [];
$qtyWhDh = [];
$qtyWhSsh = [];

while ($row = $result_wh->fetch_assoc()) {
  // Mengisi array dengan data yang didapat dari query
  $tipe = $row['tipe'];
  $warna = $row['warna'];

  $qtyWhSoh[$tipe][$warna] = $row['soh'] ?? 0;  // Jika soh null, tampilkan 0
  $qtyWhDh[$tipe][$warna] = $row['dh'] ?? 0;    // Jika dh null, tampilkan 0
  $qtyWhSsh[$tipe][$warna] = $row['ssh'] ?? 0;  // Jika ssh null, tampilkan 0
}


// Menyusun array dealer dengan tipe, warna, dan qty
$sellDataDealer = [];
while ($row = $result_sl->fetch_assoc()) {
  $sellDataDealer[$row['dealer_id']][$row['tipe']][$row['warna']] = $row['qty'] ?? 0; // Jika sl null, tampilkan 0
}

// Menyusun array dealer dengan tipe, warna, dan sl
$dealerData = [];
$dealerDataSl = [];
$dealerDataSt = [];
$dealerDataRs = [];
$dealerDataAl = [];
while ($row = $result->fetch_assoc()) {
  $dealerData[$row['kode_lks']]['subyek'] = $row['subyek'];
  $dealerDataSl[$row['kode_lks']][$row['tipe']][$row['warna']] = $row['sl'] ?? 0;  // Menyimpan SL
  $dealerDataSt[$row['kode_lks']][$row['tipe']][$row['warna']] = $row['st'] ?? 0;  // Menyimpan ST
  $dealerDataRs[$row['kode_lks']][$row['tipe']][$row['warna']] = $row['rs'] ?? 0;  // Menyimpan RS
  $dealerDataAl[$row['kode_lks']][$row['tipe']][$row['warna']] = $row['al'] ?? 0;  // Menyimpan AL

}

?>

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

<body>

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



  <?php
  $activeMenu = 'shipping'; // 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> -->

    <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">
              <?php
              // Inisialisasi variabel untuk menyimpan status apakah tanggal ditemukan
              $ada_tgl_wh = false;
              $ada_tgl_d = false;

              // Cek apakah hasil query allocation_savewarehouse ada yang sama dengan $tanggal
              while ($row_wh = $tgl_wh_result->fetch_assoc()) {
                // Jika ditemukan tanggal yang sama
                if ($row_wh['tanggal'] == $tanggal) {
                  $ada_tgl_wh = true;
                  break; // Hentikan loop jika tanggal ditemukan
                }
              }

              // Cek apakah hasil query allocation_savedealer ada yang sama dengan $tanggal
              while ($row_d = $tgl_d_result->fetch_assoc()) {
                // Jika ditemukan tanggal yang sama
                if ($row_d['tanggal'] == $tanggal) {
                  $ada_tgl_d = true;
                  break; // Hentikan loop jika tanggal ditemukan
                }
              }
              // Memeriksa apakah kedua tabel memiliki tanggal yang sama dengan hari ini
              if ($ada_tgl_wh && $ada_tgl_d) { ?>
                <form method="POST">
                  <div class="card recent-sales overflow-auto">
                    <div class="card-body">
                      <!-- <h5 class="card-title">Allocation Report</h5> -->
                      <div class="overflow-auto  mt-3" style="max-height: 650px;">
                        <!-- <form action="">
                        <input type="submit">
                      </form> -->

                        <table class="table table-hover table-bordered align-middle text-center table-striped" style="font-size:11px">
                          <thead class="align-middle text-center sticky-row-head">
                            <tr id="myTable">
                              <th rowspan="2" class="fixed-width-no" style="padding:3px">No</th>
                              <th rowspan="2" class="fixed-width-name" style="padding:3px">Tanggal: <?php echo $tanggal; ?></th>
                              <!-- Loop Tipe -->
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <th colspan="<?php echo $colspan_per_tipe * count($warnas); ?>" style="padding:3px"><?php echo $tipe; ?></th>
                                <th colspan="4" class="table-secondary" style="padding:3px">TOTAL</th>
                              <?php endforeach; ?>
                            </tr>
                            <tr>
                              <!-- Loop Tipe dan Warna -->
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php foreach ($warnas as $warna): ?>
                                  <th colspan="4" style="padding:3px"><?php echo $warna; ?></th>
                                <?php endforeach; ?>
                                <th colspan="4" class="table-secondary" style="padding:3px"><?php echo $tipe; ?></th>
                              <?php endforeach; ?>
                            </tr>
                          </thead>
                          <tbody>
                            <tr id="myTable">
                              <th scope="row"></th>
                              <td>STOCK ON HAND</td>
                              <!-- Loop untuk mengisi data per tipe dan warna -->
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php
                                // Inisialisasi total qty per tipe dan warna
                                $tot_qty_st_wh_all = 0;
                                foreach ($warnas as $warna):
                                  // Ambil qty stock untuk tipe dan warna dari $qtyWhSoh
                                  $qty_st_wh = $qtyWhSoh[$tipe][$warna] ?? 0;
                                  $tot_qty_st_wh_all += $qty_st_wh;
                                ?>
                                  <td colspan="4"><?php echo $qty_st_wh; ?></td>
                                <?php endforeach; ?>
                                <td colspan="4" class="table-secondary"><?php echo $tot_qty_st_wh_all; ?></td>
                              <?php endforeach; ?>
                            </tr>

                            <tr id="myTable">
                              <th scope="row"></th>
                              <td>DISTRIBUSI HARIAN</td>
                              <!-- Loop untuk mengisi data per tipe dan warna -->
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php
                                // inisialisasi tot_dist_harian_wh_all
                                $tot_dist_harian_wh_all = 0;
                                foreach ($warnas as $warna):
                                  // inisialisasi dist_harian_wh
                                  $dist_harian_wh = $qtyWhDh[$tipe][$warna] ?? 0;
                                  $tot_dist_harian_wh_all += $dist_harian_wh;
                                ?>
                                  <td colspan="4"><?php echo $dist_harian_wh; ?></td>
                                <?php endforeach; ?>
                                <td colspan="4" class="table-secondary"><?php echo $tot_dist_harian_wh_all; ?></td>
                              <?php endforeach; ?>
                            </tr>
                            <tr id="myTable">
                              <th scope="row"></th>
                              <td>SISA STOCK HARIAN</td>
                              <!-- Loop untuk mengisi data per tipe dan warna -->
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php
                                // inisialisasi tot_sisa_stock_wh_all
                                $tot_sisa_stock_wh_all = 0;
                                foreach ($warnas as $warna):
                                  // inisialisasi sisa_stock_wh
                                  $sisa_stock_wh = $qtyWhSsh[$tipe][$warna] ?? 0;
                                  $tot_sisa_stock_wh_all += $sisa_stock_wh;
                                ?>
                                  <td colspan="4" <?php if ($sisa_stock_wh < 0) echo 'class="table-danger"'; ?>><?php echo $sisa_stock_wh; ?></td>
                                <?php endforeach; ?>
                                <td colspan="4" class="table-secondary"><?php echo $tot_sisa_stock_wh_all; ?></td>
                              <?php endforeach; ?>
                            </tr>

                            <!-- Baris HEADER Ke-2 -->
                            <tr class="sticky-row" id="myTable">
                              <th scope="row"></th>
                              <td><strong>DEALER</strong></td>
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php foreach ($warnas as $warna): ?>
                                  <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="DO">SL</span></strong></td>
                                  <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="STOCK">ST</span></strong></td>
                                  <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="DAILY SALE">DS</span></strong></td>
                                  <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="ALOKASI">AL</span></strong></td>
                                <?php endforeach; ?>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL DO">SL</span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL STOCK">ST</span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL DAILY SALE">DS</span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL ALOKASI">AL</span></strong></td>
                              <?php endforeach; ?>
                            </tr>

                            <!-- Baris DAFTAR DEALER -->
                            <?php
                            $no = 1;

                            // Mendapatkan tanggal hari ini
                            $hari_now = new DateTime();
                            $start_hari = new DateTime($hari_now->format('Y-m-01')); // Tanggal 1 bulan ini
                            $tot_hari_now = 0; // Inisialisasi jumlah hari kerja

                            // Loop dari tanggal 1 hingga hari ini
                            while ($start_hari <= $hari_now) {
                              // Jika bukan hari Minggu (0 = Minggu)
                              if ($start_hari->format('w') != 0) {
                                $tot_hari_now++;
                              }
                              // Tambah satu hari
                              $start_hari->modify('+1 day');
                            }

                            // Inisialisasi total global untuk SL, ST, dan AL PER TIPE
                            $total_sl_global_per_tipe = [];
                            $total_st_global_per_tipe = [];
                            $total_al_global_per_tipe = [];
                            $total_sl_global_per_tipe_warna = [];
                            $total_st_global_per_tipe_warna = [];
                            $total_al_global_per_tipe_warna = [];

                            foreach ($dealerData as $kode_lks => $data): ?>
                              <tr id="myTable">
                                <th style="padding:3px"><?php echo $no++; ?></th>
                                <td style="padding:3px;text-align:left"><?php echo $data['subyek']; ?></td>

                                <!-- Loop tipe dan warna untuk menampilkan data qty -->
                                <?php foreach ($tipeWarna as $tipe => $warnas):
                                  // Inisialisasi total untuk dealer
                                  $tot_qty_sl_dealer = 0;
                                  $tot_qty_st_dealer = 0;
                                  $tot_qty_al_dealer = 0;

                                  foreach ($warnas as $warna):
                                    $qty_sl = $dealerDataSl[$kode_lks][$tipe][$warna] ?? 0; // Menampilkan qty sell (SL)
                                    $qty_st = $dealerDataSt[$kode_lks][$tipe][$warna] ?? 0; // Menampilkan qty stok (ST)
                                    $rasio = $dealerDataRs[$kode_lks][$tipe][$warna] ?? 0;  // Rasio untuk dealer ini
                                    $allocation = $dealerDataAl[$kode_lks][$tipe][$warna] ?? 0; // Alokasi (AL)

                                    // Menambahkan qty ke total dealer
                                    $tot_qty_sl_dealer += $qty_sl;
                                    $tot_qty_st_dealer += $qty_st;
                                    $daily_sale = $qty_sl / $tot_hari_now;
                                    $tot_qty_al_dealer += $allocation;

                                    // Tambahkan ke total global per tipe dan warna
                                    $total_sl_global_per_tipe_warna[$tipe][$warna] = ($total_sl_global_per_tipe_warna[$tipe][$warna] ?? 0) + $qty_sl;
                                    $total_st_global_per_tipe_warna[$tipe][$warna] = ($total_st_global_per_tipe_warna[$tipe][$warna] ?? 0) + $qty_st;
                                    $total_al_global_per_tipe_warna[$tipe][$warna] = ($total_al_global_per_tipe_warna[$tipe][$warna] ?? 0) + $allocation;

                                    // Tampilkan data
                                ?>
                                    <td style="padding:3px"><?php echo $qty_sl; ?></td> <!-- SL -->
                                    <td style="padding:3px"><?php echo $qty_st; ?></td> <!-- ST -->
                                    <td style="padding:3px"><?php echo number_format($daily_sale, 1); ?></td> <!-- RS -->
                                    <td style="padding:3px"><?php echo $allocation; ?></td> <!-- AL -->
                                  <?php endforeach;
                                  $daily_sale_total = $tot_qty_sl_dealer / $tot_hari_now; ?>

                                  <!-- Total untuk dealer pada tipe tersebut -->
                                  <td class="table-secondary" style="padding:3px"><?php echo $tot_qty_sl_dealer; ?></td> <!-- TOTAL SL -->
                                  <td class="table-secondary" style="padding:3px"><?php echo $tot_qty_st_dealer; ?></td> <!-- TOTAL ST -->
                                  <td class="table-secondary" style="padding:3px"><?php echo number_format($daily_sale_total, 1); ?></td> <!-- TOTAL RS -->
                                  <td class="table-secondary" style="padding:3px"><?php echo $tot_qty_al_dealer; ?></td> <!-- TOTAL AL -->

                                  <?php
                                  // Menambahkan total dealer ke total global per tipe
                                  $total_sl_global_per_tipe[$tipe] = ($total_sl_global_per_tipe[$tipe] ?? 0) + $tot_qty_sl_dealer; // Total SL
                                  $total_st_global_per_tipe[$tipe] = ($total_st_global_per_tipe[$tipe] ?? 0) + $tot_qty_st_dealer; // Total ST
                                  $total_ds_global_per_tipe[$tipe] = ($total_ds_global_per_tipe[$tipe] ?? 0) + $daily_sale_total;
                                  $total_al_global_per_tipe[$tipe] = ($total_al_global_per_tipe[$tipe] ?? 0) + $tot_qty_al_dealer; // Total AL
                                  ?>
                                <?php endforeach; ?>
                              </tr>
                            <?php endforeach; ?>

                            <!-- Baris Total Global per Tipe -->
                            <tr class="sticky-row" id="myTable">
                              <th scope="row"></th>
                              <td><strong>Total</strong></td>
                              <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                                <?php foreach ($warnas as $warna):
                                  $total_ds_global_per_tipe_warna = $total_sl_global_per_tipe_warna[$tipe][$warna] / $tot_hari_now; ?>
                                  <td><strong><?php echo $total_sl_global_per_tipe_warna[$tipe][$warna] ?? 0; ?></strong></td> <!-- Total SL -->
                                  <td><strong><?php echo $total_st_global_per_tipe_warna[$tipe][$warna] ?? 0; ?></strong></td> <!-- Total ST -->
                                  <td><strong><?php echo number_format($total_ds_global_per_tipe_warna, 1); ?></strong></td> <!-- Total RS -->
                                  <td><strong><?php echo $total_al_global_per_tipe_warna[$tipe][$warna] ?? 0; ?></strong></td> <!-- Total AL -->
                                <?php endforeach;
                                $total_ds_global_per_tipe = $total_sl_global_per_tipe[$tipe] / $tot_hari_now; ?>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL DO"><?php echo $total_sl_global_per_tipe[$tipe] ?? 0; ?></strong></span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL STOCK"><?php echo $total_st_global_per_tipe[$tipe] ?? 0; ?></strong></span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL RASIO"><?php echo number_format($total_ds_global_per_tipe, 1); ?></span></strong></td>
                                <td class="table-secondary"><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="TOTAL ALOKASI"><?php echo $total_al_global_per_tipe[$tipe] ?? 0; ?></span></strong></td>
                              <?php endforeach; ?>
                            </tr>

                          </tbody>
                        </table>

                      </div>
                      <!-- Tambahkan Button Jalankan -->
                      <button type="button" class="btn btn-primary mt-3" id="saveButton" onClick="window.location.href='shipping_edit.php'">Ubah Data</button>
                    </div>
                  </div>
                </form>
              <?php } else { ?>
                <div class="card recent-sales overflow-auto">
                  <div class="card-body">
                    <!-- Default Title -->
                    <div class="alert alert-warning text-center mt-4 mb-1" role="alert">
                      <h3 class="card-title">Data Allocation hari ini belum dibuat. Belum bisa memunculkan Shipping</h3>
                    </div>
                  </div>
                </div>
              <?php } ?>
            </div><!-- End Filter Stok Unit -->


          </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 src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


  <script>
    // document.addEventListener('DOMContentLoaded', function() {
    //   var saveButton = document.getElementById('saveButton');

    //   document.querySelectorAll('.allocation-input').forEach(function(input) {
    //     var tipe = input.getAttribute('data-tipe');
    //     var warna = input.getAttribute('data-warna');
    //     var alokasi = parseInt(input.value) || 0;

    //     var distribusiHarianElem = document.querySelector('.dist_harian_wh[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');

    //     if (distribusiHarianElem) {
    //       var currentDistribusi = parseInt(distribusiHarianElem.innerHTML) || 0;
    //       var newDistribusi = currentDistribusi - (parseInt(input.dataset.lastValue) || 0) + alokasi;
    //       distribusiHarianElem.innerHTML = newDistribusi;
    //       input.dataset.lastValue = alokasi;

    //       updateTotalDistribusi(tipe);
    //       updateSisaStock(tipe, warna);

    //       if (newDistribusi < 0) {
    //         distribusiHarianElem.classList.add('table-danger');
    //       } else {
    //         distribusiHarianElem.classList.remove('table-danger');
    //       }
    //     }

    //     input.addEventListener('change', function() {
    //       var alokasi = parseInt(this.value) || 0;
    //       var tipe = this.getAttribute('data-tipe');
    //       var warna = this.getAttribute('data-warna');

    //       var distribusiHarianElem = document.querySelector('.dist_harian_wh[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');

    //       if (distribusiHarianElem) {
    //         var currentDistribusi = parseInt(distribusiHarianElem.innerHTML) || 0;
    //         var newDistribusi = currentDistribusi - (parseInt(this.dataset.lastValue) || 0) + alokasi;
    //         distribusiHarianElem.innerHTML = newDistribusi;
    //         this.dataset.lastValue = alokasi;

    //         updateTotalDistribusi(tipe);
    //         updateSisaStock(tipe, warna);

    //         if (newDistribusi < 0) {
    //           distribusiHarianElem.classList.add('table-danger');
    //         } else {
    //           distribusiHarianElem.classList.remove('table-danger');
    //         }
    //       }
    //     });

    //     var event = new Event('change');
    //     input.dispatchEvent(event);
    //   });

    //   function updateSisaStock(tipe, warna) {
    //     var stockElem = document.querySelector('.stock_wh[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');
    //     var stockOnHand = parseInt(stockElem.innerHTML) || 0;

    //     var distribusiHarianElem = document.querySelector('.dist_harian_wh[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');
    //     var totalDistribusi = parseInt(distribusiHarianElem.innerHTML) || 0;

    //     var sisaStock = stockOnHand - totalDistribusi;

    //     var sisaStockElem = document.querySelector('.sisa_stock_wh[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');
    //     sisaStockElem.innerHTML = sisaStock;

    //     if (sisaStock < 0) {
    //       sisaStockElem.classList.add('table-danger');
    //     } else {
    //       sisaStockElem.classList.remove('table-danger');
    //     }

    //     checkDisableButton();
    //   }

    //   function updateTotalDistribusi(tipe) {
    //     var total = 0;
    //     document.querySelectorAll('.dist_harian_wh[data-tipe="' + tipe + '"]').forEach(function(td) {
    //       total += parseInt(td.innerHTML) || 0;
    //     });

    //     var totalDistribusiElem = document.querySelector('.table-secondary[data-tipe-total="' + tipe + '"]');
    //     if (totalDistribusiElem) {
    //       totalDistribusiElem.innerHTML = total;
    //     }

    //     checkDisableButton();
    //   }

    //   function checkDisableButton() {
    //     var disable = false;

    //     document.querySelectorAll('.dist_harian_wh').forEach(function(elem) {
    //       var distribusi = parseInt(elem.innerHTML) || 0;
    //       if (distribusi < 0) {
    //         disable = true;
    //       }
    //     });

    //     document.querySelectorAll('.sisa_stock_wh').forEach(function(elem) {
    //       var sisaStock = parseInt(elem.innerHTML) || 0;
    //       if (sisaStock < 0) {
    //         disable = true;
    //       }
    //     });

    //     if (disable) {
    //       saveButton.setAttribute('disabled', 'disabled');
    //     } else {
    //       saveButton.removeAttribute('disabled');
    //     }
    //   }
    // });

    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>