<?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';
$_SESSION['aom'] = "chandra";

$tanggal = $_GET['tanggal'];
$kode_lks = $_GET['kode_lks'];


$query_al = "SELECT tipe,warna,al FROM `allocation_savedealer` WHERE tanggal = '$tanggal' AND kode_lks = '$kode_lks' AND al != '0'";
$all_result = $conn->query($query_al);

$query_tot_al = "SELECT tipe, warna, SUM(al) AS tot_al FROM `allocation_savedealer` WHERE tanggal = '$tanggal' AND kode_lks = '$kode_lks' AND al != '0' GROUP BY tipe";
$all_result_al = $conn->query($query_tot_al);

$query_dealer = "SELECT subyek FROM fkt_dealer WHERE kode_lks = '$kode_lks'";
$dealer = $conn->query($query_dealer);
$dealer_name = $dealer->fetch_assoc();

?>

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

<body>

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



  <?php
  $activeMenu = 'history2'; // 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">
                  <div class="overflow-auto" style="max-height: 650px;">
                    <h4 class="card-title text-center mb-3"><strong>LAPORAN ALLOCATION DEALER</strong><br><br><strong><?php echo $dealer_name['subyek']; ?></strong><br><br><strong style="font-size:14px"><?php echo " $tanggal"; ?></strong></h4>

                    <!-- Table with stripped rows -->
                    <table id="targetTable" class="table table-bordered align-middle text-center" style="font-size:14px">
                      <thead>
                        <tr>
                          <th class="text-center align-middle" style="padding:8px">TIPE</th>
                          <th class="text-center align-middle" style="padding:8px">WARNA</th>
                          <th class="text-center align-middle" style="padding:8px">JUMLAH</th>
                          <th class="text-center align-middle" style="padding:8px">TOTAL</th>
                        </tr>
                      </thead>
                      <?php
                      // Buat array untuk menyimpan total 'al' per tipe
                      $totals = array();

                      // Iterasi pertama untuk menghitung total 'al' per tipe
                      if ($all_result->num_rows > 0) {
                        while ($target = $all_result->fetch_assoc()) {
                          $tipe = $target['tipe'];

                          // Jika tipe sudah ada di array, tambahkan 'al' ke dalam total
                          if (isset($totals[$tipe])) {
                            $totals[$tipe] += $target['al'];
                          } else {
                            // Jika belum, inisialisasi dengan nilai 'al' saat ini
                            $totals[$tipe] = $target['al'];
                          }
                        }
                      }

                      // Reset pointer ke awal untuk iterasi kedua
                      $all_result->data_seek(0);

                      // Buat array untuk menghitung jumlah baris per tipe
                      $rowspan_count = array();

                      // Iterasi pertama untuk menghitung jumlah tipe yang sama
                      if ($all_result->num_rows > 0) {
                        while ($target = $all_result->fetch_assoc()) {
                          $tipe = $target['tipe'];

                          // Jika tipe sudah ada di array, tambahkan ke hitungan
                          if (isset($rowspan_count[$tipe])) {
                            $rowspan_count[$tipe]++;
                          } else {
                            // Jika belum ada, inisialisasi dengan 1
                            $rowspan_count[$tipe] = 1;
                          }
                        }
                      }

                      // Reset pointer ke awal untuk iterasi kedua
                      $all_result->data_seek(0);
                      ?>

                      <tbody style="font-weight: normal; font-size:14px;">
                        <?php
                        // Variabel untuk melacak tipe yang sudah ditampilkan
                        $displayed_tipe = array();
                        $total_allocation = 0;

                        // Iterasi kedua untuk menampilkan data
                        if ($all_result->num_rows > 0) {
                          while ($target = $all_result->fetch_assoc()) {
                            $tipe = $target['tipe'];
                            $al = $target['al'];
                            $tot_al = $totals[$tipe]; // Ambil total 'al' dari array

                            // Periksa apakah tipe sudah ditampilkan
                            if (!isset($displayed_tipe[$tipe])) {
                              // Jika belum ditampilkan, tampilkan tipe dan total dengan rowspan
                              $rowspan = $rowspan_count[$tipe];
                        ?>
                              <tr>
                                <td style="padding:3px" class="align-middle text-start" rowspan="<?php echo $rowspan; ?>"><?php echo $tipe; ?></td>
                                <td style="padding:3px" class="align-middle"><?php echo $target['warna']; ?></td>
                                <td style="padding:3px" class="align-middle"><?php echo $al; ?></td>
                                <td style="padding:3px" class="align-middle" rowspan="<?php echo $rowspan; ?>"><?php echo $tot_al;
                                                                                                                $total_allocation += $tot_al; ?></td>
                              </tr>
                            <?php
                              // Tandai tipe ini sebagai sudah ditampilkan
                              $displayed_tipe[$tipe] = true;
                            } else {
                              // Jika tipe sudah ditampilkan, sembunyikan kolom tipe dan total
                            ?>
                              <tr>
                                <td style="padding:3px" class="align-middle"><?php echo $target['warna']; ?></td>
                                <td style="padding:3px" class="align-middle"><?php echo $al; ?></td>
                              </tr>
                        <?php
                            }
                          }
                        }
                        ?>
                        <tr>
                          <td style="padding:3px" colspan="3" class="align-middle text-start"><strong>TOTAL ALLOCATION</strong></td>
                          <td style="padding:3px" class="align-middle"><strong><?php echo $total_allocation; ?></strong></td>
                        </tr>
                      </tbody>

                    </table>
                    <!-- End Table with stripped rows -->
                  </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>