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

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Print - Allocation Unit</title>
  <meta content="" name="description">
  <meta content="" name="keywords">




  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- UNICOS -->
  <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.8/css/line.css">

  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">







  <style>
    thead th {
      border: .5px solid rgb(150, 150, 150) !important;
      /* Custom border for table header */
    }

    table {
      border: .5px solid rgb(150, 150, 150) !important;
      overflow-y: auto;
      overflow-x: auto !important;
      min-height: 60px;

    }

    .logo-left {
      max-width: 250px;
      /* Sesuaikan ukuran maksimum untuk logo kiri */
      height: auto;
    }

    .logo-right {
      max-width: 230px;
      /* Sesuaikan ukuran maksimum untuk logo kanan */
      height: auto;
    }

    @media print {

      header,
      footer {
        display: none;
      }

      body {
        background: #fff;
        padding: 10px;
      }
    }
  </style>
</head>

<body style="background:#fff;padding:10px">


  <main>

    <!-- Left side columns -->
    <div class="col-lg-12">
      <div class="row">
        <!-- Filter Stok Unit -->
        <div class="col-12">
          <div class="overflow-auto">
            <div class="d-flex  mb-2 mt-2 justify-content-between">
              <!-- Tombol Download Master -->
              <div class="col-sm-4">
                <img src="assets/img/logo_lt_md.png" alt="Gambar Kiri" class="img-fluid logo-left">
              </div>
              <!-- Form Upload Excel -->
              <div class="col-sm-4 d-flex justify-content-end align-items-center">
                <img src="assets/img/au_logo_kop.png" alt="Gambar Kanan" class="img-fluid logo-right">
              </div>
            </div>

            <div class="clearfix"></div>
            <div style="border-bottom:1px #000 solid;margin-bottom: 1px"></div>
            <div style="border-bottom:.5px #000 solid"></div>

            <div class="card-body">
              <!-- <h5 class="card-title">Allocation Report</h5> -->
              <div class="overflow-auto  mt-3">
                <h4 class="card-title text-center mt-4 mb-1" style="font-size:20px">LAPORAN ALLOCATION DEALER</h4>
                <h4 class="card-title text-center mt-1 mb-1" style="font-size:20px"><?php echo $dealer_name['subyek']; ?></h4>
                <h4 class="card-title text-center mt-3 mb-5" style="font-size:14px">Tanggal : <?php echo " $tanggal"; ?></h4>

                <!-- Table with stripped rows -->
                <table id="targetTable" class="table table-bordered align-middle text-center" style="font-size:12px">
                  <thead>
                    <tr>
                      <th class="text-center align-middle" style="padding:6px">TIPE</th>
                      <th class="text-center align-middle" style="padding:6px">WARNA</th>
                      <th class="text-center align-middle" style="padding:6px">JUMLAH</th>
                      <th class="text-center align-middle" style="padding:6px">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;">
                    <?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 -->


  </main><!-- End #main -->


  <!-- 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>
    window.print();
  </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>