<?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

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

$tanggal = date('Y-m-d');
// $tanggal = $_GET['tanggal'];

// Mendapatkan data stock wh
$query_stock = "SELECT * FROM `allocation_savewarehouse` WHERE tanggal = '$tanggal' AND soh != '0' AND dh != '0' AND ssh != '0'";
$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 nama_tipe, warna FROM `allocation_tipewarna`";
$query_tipewarna = "SELECT atw.nama_tipe, atw.warna
                    FROM allocation_tipewarna atw
                    INNER JOIN allocation_savewarehouse asw 
                    ON atw.nama_tipe = asw.tipe AND atw.warna = asw.warna
                    WHERE asw.tanggal = '$tanggal' AND asw.soh != '0' AND asw.dh != '0' AND asw.ssh != '0'";
$result_tipewarna = $conn->query($query_tipewarna);


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


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



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 = 'history'; // 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) {?>
              <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="myTableButton">
                          <th rowspan="2" class="fixed-width-no" style="padding:3px">No</th>
                          <th rowspan="2" class="fixed-width-button" style="padding:3px">Detail</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="myTableButton">
                          <th scope="row"></th>
                          <td></td>
                          <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="myTableButton">
                          <th scope="row"></th>
                          <td></td>
                          <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="myTableButton">
                          <th scope="row"></th>
                          <td></td>
                          <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="myTableButton">
                          <th scope="row"></th>
                          <td></td>
                          <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="myTableButton">
                            <th style="padding:3px"><?php echo $no++; ?></th>
                            <td style="padding:3px">
                              <form action="allocation_dealer_today.php" method="GET">
                                <input type="hidden" name="kode_lks" value="<?php echo $kode_lks; ?>">
                                <input type="hidden" name="tanggal" value="<?php echo $tanggal; ?>">
                                <button type="submit" class="btn btn-outline-info" style="--bs-btn-padding-y: .1rem; --bs-btn-padding-x: .5rem; --bs-btn-font-size: .80rem;"><i class="uil uil-file-search-alt"></i></button>
                              </form>
                            </td>
                            <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="myTableButton">
                          <th scope="row"></th>
                          <td></td>
                          <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>

                </div>

              </div>
              <?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 History</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>
    $(document).ready(function() {
      $('#dealer').select2({
        theme: 'bootstrap-5', // Menggunakan tema Bootstrap 5
        placeholder: "Pilih Dealer",
        allowClear: true
      });
    });

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

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

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


</body>

</html>