<?php
// Di awal skrip PHP Anda
set_time_limit(0); // 0 berarti tidak ada batas waktu
// set_time_limit(300); // Menetapkan batas waktu menjadi 5 menit (300 detik)

// koneksi ke database
// error_reporting(0);
date_default_timezone_set('Asia/Jakarta');
include 'connection.php';
$_SESSION['aom'] = "chandra";

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

// 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 nama_tipe, warna FROM `allocation_tipewarna`";
$result_tipewarna = $conn->query($query_tipewarna);

// Mendapatkan rasio kunci dari tabel allocation_rasiokunci
$query_rasiokunci = "SELECT * FROM `allocation_rasiokunci`";
$result_rasiokunci = $conn->query($query_rasiokunci);
$key_ratio = [];
while ($row = $result_rasiokunci->fetch_assoc()) {
  $key_ratio[$row['tipe']][$row['warna']] = $row['rasio'] ?? 0; // Jika rasio null, tampilkan 0
}



// Menyusun array tipe dengan warna terkaitnya
$tipeWarna = [];
while ($row = $result_tipewarna->fetch_assoc()) {
  $tipeWarna[$row['nama_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);



// Mengambil semua data dealer dan qty dalam satu query menggunakan JOIN
// $query = "
//     SELECT d.subyek, d.kode_lks, a.tipe, a.warna, a.qty
//     FROM fkt_dealer d
//     LEFT JOIN allocation_stock a
//     ON d.kode_lks = a.dealer_id
//     WHERE d.grup='LT' AND d.nonaktif=0
//     AND d.kode_lks NOT IN ('FLEET01','GUDANG UNIT','MD')
//     AND d.aom='$_SESSION[aom]'
//     ORDER BY d.urutan";
$query = "
    SELECT d.subyek, d.kode_lks, a.tipe, a.warna, a.qty
    FROM fkt_dealer d
    LEFT JOIN allocation_stock a
    ON d.kode_lks = a.dealer_id
    WHERE 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 dealer dengan tipe, warna, dan qty
$qtyDataWh = [];
while ($row = $result_wh->fetch_assoc()) {
  $qtyDataWh[$row['tipe']][$row['warna']] = $row['qty'] ?? 0; // Jika qty 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 qty null, tampilkan 0
}

// Menyusun array dealer dengan tipe, warna, dan qty
$dealerData = [];
while ($row = $result->fetch_assoc()) {
  $dealerData[$row['kode_lks']]['subyek'] = $row['subyek'];
  $dealerData[$row['kode_lks']]['qty'][$row['tipe']][$row['warna']] = $row['qty'] ?? 0; // Jika qty null, tampilkan 0
}




if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  include 'connection.php'; // Include your database connection file



  // // Ambil nilai qty_st_wh, dist_harian_wh, dan sisa_stock_wh dari input form
  // $qty_st_wh = $_POST['qty_st_wh'] ?? [];
  // $dist_harian_wh = $_POST['dist_harian_wh'] ?? [];
  // $sisa_stock_wh = $_POST['sisa_stock_wh'] ?? [];

  // // Iterasi untuk setiap tipe dan warna
  // foreach ($qty_st_wh as $tipe => $warnaData) {
  //     foreach ($warnaData as $warna => $qty_st_wh_in) {
  //         $dist_harian_wh_in = $dist_harian_wh[$tipe][$warna] ?? 0;
  //         $sisa_stock_wh_in = $sisa_stock_wh[$tipe][$warna] ?? 0;

  //         // Insert into allocation_savewarehouse
  //         $sql_warehouse = "INSERT INTO allocation_savewarehouse
  //               (tanggal, tipe, warna, soh, dh, ssh, waktusimpan)
  //               VALUES (CURDATE(), '$tipe', '$warna', '$qty_st_wh_in', '$dist_harian_wh_in', '$sisa_stock_wh_in', NOW())";
  //         mysqli_query($conn, $sql_warehouse);
  //     }
  // }

  // Inisialisasi array untuk menyimpan total allocation per tipe dan warna
  $totalAllocation = [];

  // Loop through dealer data and save to allocation_savedealer
  foreach ($dealerData as $kode_lks => $data) {
    $kode_dealer = $data['subyek'];

    // Loop through tipe dan warna untuk mengambil data qty
    foreach ($tipeWarna as $tipe => $warnas) {
      foreach ($warnas as $warna) {
        // Ambil qty dari $data
        $qty_st_in = $data['qty'][$tipe][$warna] ?? 0; // Menampilkan qty stok (ST)
        $qty_sl_in = $sellDataDealer[$kode_lks][$tipe][$warna] ?? 0; // Menampilkan qty sell (SL)
        $rasio_in = ($qty_sl_in != 0) ? $qty_st_in / $qty_sl_in : 0;  // Rasio_in untuk dealer ini
        $allocation_in = 0; // Inisialisasi alokasi


        // $allocation_in = isset($_POST['dealer'][$kode_lks][$tipe][$warna]['al']) ? $_POST['dealer'][$kode_lks][$tipe][$warna]['al'] : 0;
        $allocation_in = $_POST['dealer'][$kode_lks][$tipe][$warna]['al'];

        // Simpan nilai allocation ke dalam totalAllocation untuk tipe dan warna
        if (!isset($totalAllocation[$tipe][$warna])) {
          $totalAllocation[$tipe][$warna] = 0; // Inisialisasi jika belum ada
        }
        $totalAllocation[$tipe][$warna] += $allocation_in; // Tambahkan allocation ke total


        // Insert into allocation_in_savedealer
        $sql_dealer = "INSERT INTO allocation_savedealer
                            (tanggal, kode_lks, tipe, warna, sl, st, rs, al, waktusimpan) 
                            VALUES (CURDATE(), '$kode_lks', '$tipe', '$warna', '$qty_sl_in', '$qty_st_in', '$rasio_in', '$allocation_in', NOW())";
        mysqli_query($conn, $sql_dealer);
      }
    }
  }


  // Loop through warehouse data and save to allocation_savewarehouse
  foreach ($_POST['warehouse'] as $tipe => $warnaData) {
    foreach ($warnaData as $warna => $data) {
      $qty_st_wh_in = $data['soh'];
      $dist_harian_wh_in = $totalAllocation[$tipe][$warna] ?? 0; // Gunakan total allocation untuk dist_harian_wh_in
      $sisa_stock_wh_in = $qty_st_wh_in - $dist_harian_wh_in;

      // Insert into allocation_savewarehouse
      $sql_warehouse = "INSERT INTO allocation_savewarehouse
                            (tanggal, tipe, warna, soh, dh, ssh, waktusimpan)
                            VALUES (CURDATE(), '$tipe', '$warna', '$qty_st_wh_in', '$dist_harian_wh_in', '$sisa_stock_wh_in', NOW())";
      mysqli_query($conn, $sql_warehouse);
    }
  }


  // Redirect or show success message
  echo "Data berhasil disimpan!";
}






// // Fungsi untuk menghitung rasio
// function hitungRasio($terjual, $stok, $alokasi) {
//   // return $terjual / ($stok + $alokasi);
//   // Cek jika stok + alokasi adalah 0, kembalikan rasio 0 atau nilai lain sesuai kebutuhan
//   if (($stok + $alokasi) == 0) {
//     return 0; // Anda dapat mengubah 0 menjadi nilai lain jika diperlukan
//   }

//   // Jika stok + alokasi tidak nol, lakukan pembagian
//   return $terjual / ($stok + $alokasi);
// }

// // Fungsi untuk menghitung alokasi otomatis
// function alokasiOtomatis(&$dealerData, &$sellDataDealer, &$qtyDataWh, &$key_ratio) {
//   foreach ($dealerData as $kode_lks => &$data) {
//       foreach ($data['qty'] as $tipe => $warnas) {
//           foreach ($warnas as $warna => $qty_st) {
//               $qty_sl = $sellDataDealer[$kode_lks][$tipe][$warna] ?? 0; // Menampilkan qty sell (SL)
//               $rasio = ($qty_sl != 0) ? $qty_st / $qty_sl : 0; // Rasio untuk dealer ini

//               $key_ratio_min = $key_ratio[$tipe][$warna] ?? 0;
//               $qty_stock_wh = $qtyDataWh[$tipe][$warna] ?? 0;
//               $qty_warehouse = $qty_stock_wh;

//               // Jika ada stok di gudang
//               while ($qty_warehouse > 0 && $rasio < $key_ratio_min) {
//                   // Cari dealer dengan rasio terkecil
//                   $minRasio = null;
//                   $dealerMinRasio = null;

//                   foreach ($dealerData as $kode_lks_compare => &$data_compare) {
//                       $qty_sl_compare = $sellDataDealer[$kode_lks_compare][$tipe][$warna] ?? 0;
//                       $qty_st_compare = $data_compare['qty'][$tipe][$warna] ?? 0;
//                       $alokasi_compare = $data_compare['alokasi'][$tipe][$warna] ?? 0;

//                       $rasio_compare = ($qty_sl_compare != 0) ? hitungRasio($qty_sl_compare, $qty_st_compare, $alokasi_compare) : 0;

//                       if ($minRasio === null || $rasio_compare < $minRasio) {
//                           $minRasio = $rasio_compare;
//                           $dealerMinRasio = &$data_compare;
//                       }
//                   }

//                   // Alokasi +1 untuk dealer dengan rasio terkecil
//                   if ($dealerMinRasio !== null) {
//                       $dealerMinRasio['alokasi'][$tipe][$warna] = ($dealerMinRasio['alokasi'][$tipe][$warna] ?? 0) + 1;
//                       $qty_warehouse--;
//                   }

//                   // Hitung ulang rasio setelah penambahan alokasi
//                   foreach ($dealerData as &$data_update) {
//                       $qty_sl_update = $sellDataDealer[$kode_lks][$tipe][$warna] ?? 0;
//                       $qty_st_update = $data_update['qty'][$tipe][$warna] ?? 0;
//                       $alokasi_update = $data_update['alokasi'][$tipe][$warna] ?? 0;

//                       $data_update['rasio'][$tipe][$warna] = ($qty_sl_update != 0) ? hitungRasio($qty_sl_update, $qty_st_update, $alokasi_update) : 0;
//                   }
//               }
//           }
//       }
//   }
// }



?>

<!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">

    <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
              $query1 = "SELECT * FROM `allocation_savedealer` WHERE tanggal=CURDATE()";
              $result1 = $conn->query($query1);
              $row1 = $result1->fetch_assoc();


              if (!empty($row1['idsavedealer'])) { ?>
                <!-- Default Title -->
                <div class="alert alert-warning text-center mt-4 mb-1" role="alert">
                  <h3 class="card-title">Data Shipping Hari ini Sudah Dibuat</h3>
                </div>
              <?php } else { ?>
                <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;">

                        <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 date('d/m/Y'); ?></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 $qtyDataWh
                                  $qty_st_wh = $qtyDataWh[$tipe][$warna] ?? 0;
                                  $tot_qty_st_wh_all += $qty_st_wh;

                                ?>
                                  <td colspan="4" class="stock_wh" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                    <?php echo $qty_st_wh; ?>
                                    <input type="hidden" name="warehouse[<?php echo $tipe; ?>][<?php echo $warna; ?>][soh]" value="<?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 = 0;
                                  $tot_dist_harian_wh_all += $dist_harian_wh;
                                ?>
                                  <td colspan="4" class="dist_harian_wh" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                    <?php echo $dist_harian_wh; ?>
                                    <input type="hidden" name="warehouse[<?php echo $tipe; ?>][<?php echo $warna; ?>][dh]" value="<?php echo $dist_harian_wh; ?>">
                                  </td>

                                <?php endforeach; ?>
                                <td colspan="4" class="table-secondary" data-tipe="<?php echo $tipe; ?>">
                                  <?php echo $tot_dist_harian_wh_all; ?>
                                </td>

                              <?php endforeach; ?>
                            </tr>
                            <tr class="sticky-row" 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 = (isset($qtyDataWh[$tipe][$warna]) ? $qtyDataWh[$tipe][$warna] : 0) - ($total_al_global_per_tipe_warna[$tipe][$warna] ?? 0);
                                  $tot_sisa_stock_wh_all += $sisa_stock_wh;
                                ?>
                                  <td colspan="4" class="sisa_stock_wh" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                    <?php echo $sisa_stock_wh; ?>
                                    <input type="hidden" name="warehouse[<?php echo $tipe; ?>][<?php echo $warna; ?>][ssh]" value="<?php echo $sisa_stock_wh; ?>">
                                  </td>
                                <?php endforeach; ?>
                                <!-- Cek jika $tot_sisa_stock_wh_all negatif -->
                                <td colspan="4" class="table-secondary" data-tipe="<?php echo $tipe; ?>">
                                  <?php echo $tot_sisa_stock_wh_all; ?>
                                </td>
                              <?php endforeach; ?>
                            </tr>

                            <!-- Baris HEADER Ke-2 -->
                            <tr class="sticky-row-two" 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="RASIO">RS</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 RASIO">RS</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;

                            // Panggil fungsi alokasi otomatis
                            // alokasiOtomatis($dealerData, $sellDataDealer, $qtyDataWh, $key_ratio);

                            // 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):
                              $kode_dealer = $kode_lks ?>
                              <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_st =  $data['qty'][$tipe][$warna] ?? 0; // Menampilkan qty stok (ST)
                                    $qty_stock =  $data['qty'][$tipe][$warna] ?? 0; // Menampilkan qty stok (ST)
                                    $qty_sl =  $sellDataDealer[$kode_lks][$tipe][$warna] ?? 0; // Menampilkan qty sell (SL)
                                    $rasio = ($qty_sl != 0) ? $qty_st / $qty_sl : 0;  // Rasio untuk dealer ini
                                    $rasio_bagi = ($qty_sl != 0) ? $qty_st / $qty_sl : 0;  // Rasio untuk dealer ini

                                    $key_ratio_min = $key_ratio[$tipe][$warna] ?? 0;
                                    $qty_stock_wh = $qtyDataWh[$tipe][$warna] ?? 0;
                                    $qty_warehouse = $qty_stock_wh;

                                    // value hasil alokasi
                                    $allocation = 0;
                                    // // Panggil alokasi untuk dealer, tipe, dan warna yang sesuai
                                    // $allocation = $data['alokasi'][$tipe][$warna] ?? 0; // Jika tidak ada alokasi, default 0
                                    // Menambahkan qty ke total dealer
                                    $tot_qty_sl_dealer += $qty_sl;
                                    $tot_qty_st_dealer += $qty_st;
                                    $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;


                                    // Jika rasio dealer lebih kecil dari key_ratio_min dan stok gudang masih ada
                                    if ($qty_warehouse > 0 && $qty_sl != 0 && $rasio_bagi < $key_ratio_min) {
                                      // Loop untuk melakukan alokasi sampai stok habis atau rasio tidak lebih kecil
                                      while ($rasio_bagi < $key_ratio_min && $qty_warehouse > $qty_stock) {
                                        $allocation += 1;  // Tambahkan alokasi
                                        $qty_stock += 1;    // Kurangi stok dealer
                                        $qty_warehouse -= 1;    // Kurangi stok gudang

                                        // Update rasio setelah penambahan alokasi
                                        $rasio_bagi = ($qty_sl != 0) ? $qty_stock / $qty_sl : 0;
                                      }
                                    }


                                ?>


                                    <td style="padding:3px" class="sl_value" data-dealer="<?php echo $kode_dealer; ?>" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                      <?php echo $qty_sl; ?>
                                      <input type="hidden" name="dealer[<?php echo $kode_dealer; ?>][<?php echo $tipe; ?>][<?php echo $warna; ?>][sl]" value="<?php echo $qty_sl; ?>">
                                    </td> <!-- SL -->

                                    <td style="padding:3px" class="st_value" data-dealer="<?php echo $kode_dealer; ?>" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                      <?php echo $qty_st; ?>
                                      <input type="hidden" name="dealer[<?php echo $kode_dealer; ?>][<?php echo $tipe; ?>][<?php echo $warna; ?>][st]" value="<?php echo $qty_st; ?>">
                                    </td> <!-- ST -->

                                    <td style="padding:3px" class="rs_value" data-dealer="<?php echo $kode_dealer; ?>" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>">
                                      <?php echo number_format($rasio, 1); ?>
                                      <input type="hidden" name="dealer[<?php echo $kode_dealer; ?>][<?php echo $tipe; ?>][<?php echo $warna; ?>][rs]" value="<?php echo $rasio; ?>">
                                    </td> <!-- RS -->

                                    <td style="padding:3px">
                                      <input type="text" name="dealer[<?php echo $kode_dealer; ?>][<?php echo $tipe; ?>][<?php echo $warna; ?>][al]" class="allocation-input" data-dealer="<?php echo $kode_dealer; ?>" data-tipe="<?php echo $tipe; ?>" data-warna="<?php echo $warna; ?>" style="width:20px;padding:0;margin:0;text-align:center" value="<?php echo $allocation; ?>" data-lastValue="<?php echo $allocation; ?>" />
                                    </td> <!-- AL -->



                                  <?php endforeach; ?>

                                  <!-- 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(($tot_qty_st_dealer == 0 || $tot_qty_sl_dealer == 0) ? 0 : $tot_qty_st_dealer / $tot_qty_sl_dealer, 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_al_global_per_tipe[$tipe] = ($total_al_global_per_tipe[$tipe] ?? 0) + $tot_qty_al_dealer; // Total AL
                                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): ?>
                                  <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_st_global_per_tipe_warna[$tipe][$warna] == 0 || $total_sl_global_per_tipe_warna[$tipe][$warna] == 0) ? 0 : ($total_st_global_per_tipe_warna[$tipe][$warna] / $total_sl_global_per_tipe_warna[$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; ?>
                                <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_st_global_per_tipe[$tipe] == 0 || $total_sl_global_per_tipe[$tipe] == 0) ? 0 : ($total_st_global_per_tipe[$tipe] / $total_sl_global_per_tipe[$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="submit" class="btn btn-primary mt-3" id="saveButton">Simpan Data</button>
                    </div>
                  </div>
                </form>
              <?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).ready(function() {
      $('#jalankanButton').click(function() {
        // Kirim permintaan AJAX ke server untuk menjalankan alokasi
        $.ajax({
          url: 'jalankan_alokasi.php', // File PHP yang akan menangani logika alokasi
          method: 'POST',
          success: function(response) {
            alert('Alokasi berhasil dijalankan!'); // Notifikasi setelah sukses
            location.reload(); // Reload halaman untuk menampilkan hasil alokasi terbaru
          },
          error: function(xhr, status, error) {
            alert('Terjadi kesalahan: ' + error); // Menampilkan pesan kesalahan jika gagal
          }
        });
      });
    });
  </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');
    //     }
    //   }
    // });








    // // Event listener untuk tombol "Simpan Data"
    // document.getElementById('saveButton').addEventListener('click', function() {
    //   // Loop melalui setiap row tipe dan warna untuk memperbarui hidden input
    //   document.querySelectorAll('tr').forEach(function(row) {
    //     // Ambil tipe dan warna dari atribut data
    //     var tipe = row.querySelector('.stock_wh')?.getAttribute('data-tipe');
    //     var warna = row.querySelector('.stock_wh')?.getAttribute('data-warna');

    //     if (tipe && warna) {
    //       // Ambil nilai dari kolom stock, distribusi harian, dan sisa stok
    //       var stockOnHand = parseInt(row.querySelector('.stock_wh')?.innerHTML) || 0;
    //       var distribusiHarian = parseInt(row.querySelector('.dist_harian_wh')?.innerHTML) || 0;
    //       var sisaStock = parseInt(row.querySelector('.sisa_stock_wh')?.innerHTML) || 0;

    //       // Update nilai hidden input dengan nilai yang ada di tampilan
    //       var hiddenQtyElem = row.querySelector('input.hidden-qty[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');
    //       var hiddenDistElem = row.querySelector('input.hidden-dist[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');
    //       var hiddenSisaElem = row.querySelector('input.hidden-sisa[data-tipe="' + tipe + '"][data-warna="' + warna + '"]');

    //       if (hiddenQtyElem) hiddenQtyElem.value = stockOnHand;
    //       if (hiddenDistElem) hiddenDistElem.value = distribusiHarian;
    //       if (hiddenSisaElem) hiddenSisaElem.value = sisaStock;
    //     }
    //   });
    // });




    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>