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

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


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






// 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
$sellDataWh = [];
while ($row = $result_sl->fetch_assoc()) {
  $sellDataWh[$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
}

?>

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

<body>

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



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



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

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

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

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

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

                <div class="card-body">
                  <!-- <h5 class="card-title">Allocation Report</h5> -->
                  <div class="overflow-auto  mt-3" style="max-height: 650px;">
                    <!-- <form action="">
                      <input type="submit">
                    </form> -->

                    <table class="table table-hover table-bordered align-middle text-center table-striped" style="font-size:11px">
                      <thead class="align-middle text-center sticky-row-head">
                        <tr id="myTable">
                          <th rowspan="2" class="fixed-width-no" style="padding:3px">No</th>
                          <th rowspan="2" class="fixed-width-name" style="padding:3px">Tanggal: <?php echo 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"><?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"><?php echo $dist_harian_wh; ?></td>
                            <?php endforeach; ?>
                            <td colspan="4" class="table-secondary"><?php echo $tot_dist_harian_wh_all; ?></td>
                          <?php endforeach; ?>
                        </tr>
                        <tr id="myTable">
                          <th scope="row"></th>
                          <td>SISA STOCK HARIAN</td>
                          <!-- Loop untuk mengisi data per tipe dan warna -->
                          <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                            <?php
                            // inisialisasi tot_sisa_stock_wh_all
                            $tot_sisa_stock_wh_all = 0;
                            foreach ($warnas as $warna):
                              // inisialisasi sisa_stock_wh
                              $sisa_stock_wh = 0;
                              $tot_sisa_stock_wh_all += $sisa_stock_wh;
                            ?>
                              <td colspan="4"><?php echo $sisa_stock_wh; ?></td>
                            <?php endforeach; ?>
                            <td colspan="4" class="table-secondary"><?php echo $tot_sisa_stock_wh_all; ?></td>
                          <?php endforeach; ?>
                        </tr>

                        <!-- Baris HEADER Ke-2 -->
                        <tr class="sticky-row" id="myTable">
                          <th scope="row"></th>
                          <td><strong>DEALER</strong></td>
                          <?php foreach ($tipeWarna as $tipe => $warnas): ?>
                            <?php foreach ($warnas as $warna): ?>
                              <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="DO">SL</span></strong></td>
                              <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="STOCK">ST</span></strong></td>
                              <td><strong><span data-bs-toggle="tooltip" data-bs-placement="top" title="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;

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

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

                            <?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):
                                // Ambil data SL dan ST
                                $qty_st =  $data['qty'][$tipe][$warna] ?? 0;
                                $qty_sl =  $sellDataWh[$kode_lks][$tipe][$warna] ?? 0;

                                // Hitung rasio
                                if ($qty_sl == 0 || $qty_st == 0) {
                                  $rasio = 0;
                                } else {
                                  $rasio = $qty_st / $qty_sl;
                                }

                                // Tambah nilai alokasi (misal alokasi diset ke 0 untuk sekarang)
                                $allocation = 1;

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


                                // 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($rasio, 1); ?></td> <!-- RS -->
                                <td style="padding:3px"><input type="text" name="" style="width:20px;padding:0;margin:0;text-align:center" value="<?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>

                </div>

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