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

// Mendapatkan data stock wh
$query_stock = "SELECT * FROM `allocation_savewarehouse`";
$result_wh = $conn->query($query_stock);

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


$tanggal = date('d/m/Y');

// Query untuk mendapatkan tanggal dari allocation_savedealer
$query_tgl_d = "SELECT tanggal,SUM(al) AS tot FROM `allocation_savedealer` GROUP BY tanggal ORDER BY tanggal DESC";
$tgl_d_result = $conn->query($query_tgl_d);


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 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 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 = '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">
                  <!-- <h5 class="card-title">Allocation Report</h5> -->
                  <div class="overflow-auto  mt-3" style="max-height: 650px;">
                    <!-- Table with stripped rows -->
                    <table id="targetTable" class="table table-hover table-bordered align-middle text-center table-striped" style="font-size:12px">
                      <thead style="font-size:12px">
                        <tr>
                          <th class="text-center align-middle" style="padding:8px">Lihat</th>
                          <th class="text-center align-middle" style="padding:8px">Tanggal</th>
                          <th class="text-center align-middle" style="padding:8px">Jumlah Allocation</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php
                        if ($tgl_d_result->num_rows > 0) {
                          while ($target = $tgl_d_result->fetch_assoc()) {
                        ?>
                            <tr>
                              <td style="padding:3px"><form action="history_detail2.php" method="GET">
                                    <input type="hidden" name="tanggal" value="<?php echo $target['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" class="align-middle"><?php echo $target['tanggal']; ?></td>
                              <td style="padding:3px" class="align-middle"><?php echo $target['tot']; ?></td>
                            </tr>
                        <?php
                          }
                        }
                        ?>
                      </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>