<?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'] : 'User'; // Jika belum login, tampilkan 'User' sebagai default
$user = isset($_SESSION['user']) ? $_SESSION['user'] : 'warehouse'; // Jika belum login, tampilkan 'User' sebagai default
$jenis = isset($_SESSION['jenis']) ? $_SESSION['jenis'] : 'Coba'; // Jika belum login, tampilkan 'User' sebagai default


// Di awal skrip PHP Anda
set_time_limit(0); // 0 berarti tidak ada batas waktu
error_reporting(0);
date_default_timezone_set('Asia/Jakarta');
include 'connection.php';


// 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);

// 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
}

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



// 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 * FROM `allocation_savewarehouse` WHERE tanggal = CURDATE()";
$tdy_in_wh_result = $conn->query($query_tgl_wh);

// Query untuk mendapatkan tanggal dari allocation_savedealer
$query_tgl_d = "SELECT * FROM `allocation_savedealer` WHERE tanggal = CURDATE()";
$tdy_in_d_result = $conn->query($query_tgl_d);



if ($jenis == 'aom') {
  $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='$user'
      ORDER BY d.urutan";
} else {
  $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.kode_lks NOT IN (SELECT kode_lks FROM `allocation_savedealer` WHERE tanggal = CURDATE() GROUP BY kode_lks)
      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
$qtyDataWhSv = [];
while ($row = $tdy_in_wh_result->fetch_assoc()) {
  $qtyDataWhSv[$row['tipe']][$row['warna']] = $row['dh'] ?? 0; // Jika qty null, tampilkan 0
}
// 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
}


// Query untuk mendapatkan tanggal dari allocation_savewarehouse
$query_not_aom = "SELECT d.aom
      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.kode_lks NOT IN (SELECT kode_lks FROM `allocation_savedealer` WHERE tanggal = CURDATE() GROUP BY kode_lks)
      GROUP BY aom";
$not_aom_result = $conn->query($query_not_aom);


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

  if ($jenis == 'aom') {
    $sql_aom_s1 = "INSERT INTO allocation_step1
        (aom, tanggal, waktu)
        VALUES ('$user', CURDATE(), CURTIME())";
    mysqli_query($conn, $sql_aom_s1);
  } else {
    // Jika bukan 'aom', masukkan semua aom yang ada di $not_aom_result
    while ($row = $not_aom_result->fetch_assoc()) {
      $aom_value = $row['aom'];
      // Pastikan aom_value aman untuk digunakan dalam query
      $aom_value = $conn->real_escape_string($aom_value);
      $sql_aom_s1 = "INSERT INTO allocation_step1 (aom, tanggal, waktu)
      VALUES ('$aom_value', CURDATE(), CURTIME())";
      $conn->query($sql_aom_s1);
    }
  }


  // 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) {
      // Cek apakah terdapat data pada $tdy_in_wh_result
      if ($tdy_in_wh_result->num_rows == 0) {
        $qty_st_wh_in = $data['soh'];
        $dist_harian_wh_in = $totalAllocation[$tipe][$warna] ?? 0;
        $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);
      } else {
        // Jika ada data, jalankan Rumus B
        $sql_wh_insrted = "SELECT dh, ssh FROM `allocation_savewarehouse` WHERE tanggal = CURDATE() AND tipe = '$tipe' AND warna = '$warna'";
        $result_wh_insrted = $conn->query($sql_wh_insrted);
        $row = $result_wh_insrted->fetch_assoc();
        $dh_insrtd = $row['dh'] ?? 0;
        $ssh_insrtd = $row['ssh'] ?? 0;

        // Hitung ulang distribusi harian dan sisa stok
        $dist_harian_wh_in = $totalAllocation[$tipe][$warna] ?? 0;
        $tot_dist_harian_wh = $dist_harian_wh_in + $dh_insrtd;
        $sisa_stock_wh_in = $ssh_insrtd - $dist_harian_wh_in;

        // Update tabel allocation_savewarehouse
        $sql_warehouse = "UPDATE allocation_savewarehouse SET
                                dh = '$tot_dist_harian_wh',
                                ssh = '$sisa_stock_wh_in'
                                WHERE tanggal = CURDATE() AND tipe = '$tipe' AND warna = '$warna'";
        $conn->query($sql_warehouse); // Konsisten menggunakan ->query()


        // // Jika ada data, jalankan Rumus B
        // $sql_wh_insrted = "SELECT dh, ssh FROM `allocation_savewarehouse` WHERE tanggal = CURDATE() AND tipe = '$tipe' AND warna = '$warna'";
        // $result_wh_insrted = $conn->query($sql_wh_insrted);

        // $dh_insrtd = $result_wh_insrted['dh'];
        // $ssh_insrtd = $result_wh_insrted['ssh'];

        // $dist_harian_wh_in = $totalAllocation[$tipe][$warna] ?? 0;

        // $tot_dist_harian_wh = $dist_harian_wh_in + $dh_insrtd;
        // $sisa_stock_wh_in = $ssh_insrtd - $tot_dist_harian_wh;

        // // Insert into allocation_savewarehouse
        // $sql_warehouse = "UPDATE allocation_savewarehouse SET
        //                       dh = '$tot_dist_harian_wh',
        //                       ssh = '$sisa_stock_wh_in'
        //                       WHERE tanggal = CURDATE() AND tipe = '$tipe' AND warna = '$warna'";
        // mysqli_query($conn, $sql_warehouse);
      }
    }
  }


  // // 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
  // Menampilkan alert dan mengarahkan ulang ke halaman yang sama
  echo "<script>
          alert('File berhasil di upload');
          window.location.href = 'allocation.php';
        </script>";
  exit;
}





?>

<!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);
              $row_save_dealer = $result1->fetch_assoc();
              $query2 = "SELECT * FROM `allocation_step1` WHERE tanggal=CURDATE() AND aom = '$user'";
              $result2 = $conn->query($query2);
              $row_check_aom = $result2->fetch_assoc();

              // Memeriksa apakah kedua tabel memiliki tanggal yang sama dengan hari ini
              if (!empty($row_save_dealer['idsavedealer']) && !empty($row_check_aom['aom'] == $user)) { ?>
                <div class="card recent-sales overflow-auto">
                  <div class="card-body">
                    <!-- Default Title -->
                    <div class="alert alert-success text-center mt-4 mb-1" role="alert">
                      <h3 class="card-title">Data Allocation Telah Selesai Dibuat</h3>
                    </div>
                  </div>
                </div>
              <?php } else if ($result->num_rows === 0) { ?>
                <div class="card recent-sales overflow-auto">
                  <div class="card-body">
                    <!-- Default Title -->
                    <div class="alert alert-success text-center mt-4 mb-1" role="alert">
                      <h3 class="card-title">Data Allocation Telah Selesai Dibuat</h3>
                    </div>
                  </div>
                </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;
                                  $qty_st_wh_sv = $qtyDataWhSv[$tipe][$warna] ?? 0;
                                  $qty_tot_sv_wh = $qty_st_wh - $qty_st_wh_sv;
                                  $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_tot_sv_wh; ?>
                                    <input type="hidden" name="warehouse[<?php echo $tipe; ?>][<?php echo $warna; ?>][soh]" value="<?php echo $qty_tot_sv_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; ?>">
                                  <span data-bs-toggle="tooltip" data-bs-placement="top" title="Akan Keluar Setelah Data Disimpan">-</span> <?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; ?>">
                                  <span data-bs-toggle="tooltip" data-bs-placement="top" title="Akan Keluar Setelah Data Disimpan">-</span> <?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="SALE">DO</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 SALE">DO</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):
                              $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;
                                    $key_stockday = $key_stockdays[$tipe][$warna] ?? 0;
                                    $qty_stock_wh = $qtyDataWh[$tipe][$warna] ?? 0;
                                    $qty_stock_wh_sv = $qtyDataWhSv[$tipe][$warna] ?? 0;
                                    $qty_warehouse = $qty_stock_wh - $qty_stock_wh_sv;

                                    // value hasil alokasi
                                    $allocation = 0;
                                    $daily_sale = 0;
                                    $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;


                                    $daily_sale = $qty_sl / $tot_hari_now;
                                    $allocation = ($key_stockday * $daily_sale) - $qty_st;

                                    if ($qty_sl == 0 || $allocation < 0 || $qty_warehouse == 0) {
                                      $allocation = 0;
                                    } else if ($qty_warehouse <= 2) {
                                      $allocation = 0;
                                    } else {
                                      $allocation = ceil($allocation); // Jika desimal, bulatkan ke atas
                                    }

                                    // // Jika qty_warehouse di antara 11 dan 33
                                    // if ($qty_warehouse < 33 && $qty_warehouse > 10) {
                                    //   // Jalankan Kondisi if dan while
                                    //   if ($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) {
                                    //       // Cek apakah allocation sudah sama dengan qty_sl di dalam loop
                                    //       if ($allocation == $qty_sl) {
                                    //         // Hentikan loop jika allocation sudah sama dengan qty_sl
                                    //         break;
                                    //       }
                                    //       $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;
                                    //       // Cek lagi apakah allocation sudah sama dengan qty_sl setelah update
                                    //       if ($allocation == $qty_sl) {
                                    //         // Hentikan loop jika allocation sudah sama dengan qty_sl
                                    //         break;
                                    //       }
                                    //     }
                                    //   }
                                    // }
                                    // // Jika qty_warehouse kurang dari 11
                                    // elseif ($qty_warehouse < 11) {
                                    //   if ($qty_st == 0) {
                                    //     // Jalankan Kondisi if dan while
                                    //     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;
                                    //       }
                                    //     }
                                    //   }
                                    // }
                                    // // Kondisi selain itu
                                    // else {
                                    //   // Jalankan Kondisi if dan while
                                    //   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;
                                    //     }
                                    //   }
                                    // }



                                    // // 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($daily_sale, 1); ?>
                                      <input type="hidden" name="dealer[<?php echo $kode_dealer; ?>][<?php echo $tipe; ?>][<?php echo $warna; ?>][rs]" value="<?php echo $daily_sale; ?>">
                                    </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;
                                  $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
                                  $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):
                                  $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="submit" class="btn btn-primary mt-3" id="saveButton" disabled>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.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>