<?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
$aom = isset($_SESSION['aom']) ? $_SESSION['aom'] : 'Coba'; // Jika belum login, tampilkan 'User' sebagai default

// koneksi ke database
include 'connection.php';

// Mendapatkan data key_sd_service1 untuk isi
$key_sd_kunci = "SELECT * FROM `allocation_key_stockdays`";
$key_sd_result = $conn->query($key_sd_kunci);

// Mendapatkan data tipe untuk dropdown
$tipe_query = "SELECT tipe FROM penjualan_tipe GROUP BY tipe";
$tipe_result = $conn->query($tipe_query);

// Mendapatkan data warna untuk dropdown
$warna_query = "SELECT warna FROM warna GROUP BY warna";
$warna_result = $conn->query($warna_query);


require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

// Fungsi untuk mengunduh template Excel
if (isset($_GET['download'])) {
  $spreadsheet = new Spreadsheet();
  $sheet = $spreadsheet->getActiveSheet();

  // Menulis header kolom dengan bold
  $sheet->setCellValue('A1', 'Tipe');
  $sheet->setCellValue('B1', 'Warna');
  $sheet->setCellValue('C1', 'Key_SD');
  $sheet->getStyle('A1:C1')->getFont()->setBold(true); // Set bold

  // Mengambil data dari tabel allocation_key_stockdays
  $query = "SELECT tipe, warna, key_sd FROM allocation_key_stockdays";
  $result = $conn->query($query);
  $row = 2; // Mulai dari baris kedua
  while ($data = $result->fetch_assoc()) {
      $sheet->setCellValue('A' . $row, $data['tipe']);
      $sheet->setCellValue('B' . $row, $data['warna']);
      $sheet->setCellValue('C' . $row, $data['key_sd']);
      $row++;
  }

  $writer = new Xlsx($spreadsheet);
  $filename = 'master_allocation_key_stockdays.xlsx';

  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="' . $filename . '"');
  header('Cache-Control: max-age=0');

  $writer->save('php://output');
  exit;
}

// Fungsi untuk mengunggah dan memproses file Excel
if (isset($_POST['upload'])) {
  $file = $_FILES['excel_file']['tmp_name'];
  $spreadsheet = IOFactory::load($file);
  $sheetData = $spreadsheet->getActiveSheet()->toArray();

  // Memulai dari baris kedua (mengabaikan header)
  for ($i = 1; $i < count($sheetData); $i++) {
      $tipe = $sheetData[$i][0];
      $warna = $sheetData[$i][1];
      $key_sd = $sheetData[$i][2];

      // Cek apakah tipe dan warna sudah ada
      $stmt = $conn->prepare("SELECT COUNT(*) FROM allocation_key_stockdays WHERE tipe = ? AND warna = ?");
      $stmt->bind_param("ss", $tipe, $warna);
      $stmt->execute();
      $stmt->bind_result($count);
      $stmt->fetch();
      $stmt->close();

      if ($count > 0) {
          // Update key_sd jika sudah ada
          $stmt = $conn->prepare("UPDATE allocation_key_stockdays SET key_sd = ? WHERE tipe = ? AND warna = ?");
          $stmt->bind_param("sss", $key_sd, $tipe, $warna);
          $stmt->execute();
          $stmt->close();
      } else {
          // Insert tipe, warna, dan key_sd baru
          $stmt = $conn->prepare("INSERT INTO allocation_key_stockdays (tipe, warna, key_sd) VALUES (?, ?, ?)");
          $stmt->bind_param("sss", $tipe, $warna, $key_sd);
          $stmt->execute();
          $stmt->close();
      }
  }

  // Menampilkan alert dan mengarahkan ulang ke halaman yang sama
  echo "<script>
          alert('File berhasil di upload');
          window.location.href = 'key_sd.php';
        </script>";
  exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title>Allocation Unit</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Select2 Bootstrap Theme -->
  <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />

  <!-- DataTables CSS -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

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

  <!-- Vendor CSS Files -->
  <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">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">

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

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

  <style>
    thead th {
      border: 1px solid rgb(230, 230, 230) !important;
    }

    table {
      overflow-y: auto;
      overflow-x: auto !important;
      min-height: 40px;
    }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  </style>
</head>

<body>



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


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


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


    <section class="section dashboard">

      <div class="card">
        <div class="card-body">

          <!-- Default Tabs -->
          <ul class="nav mt-4 nav-tabs d-flex" id="myTabjustified" role="tablist">

            <li class="nav-item flex-fill" role="presentation">
              <button class="nav-link w-100 active" id="data-ratio-tab" data-bs-toggle="tab" data-bs-target="#data-ratio-justified" type="button" role="tab" aria-controls="data-ratio" aria-selected="false">Data Key SD</button>
            </li>
            <li class="nav-item flex-fill" role="presentation">
              <button class="nav-link w-100" id="input-key_sd-tab-excel" data-bs-toggle="tab" data-bs-target="#input-key_sd-justified-excel" type="button" role="tab" aria-controls="input-key_sd-excel" aria-selected="true">Input Excel Key SD</button>
            </li>
          </ul>
          <div class="tab-content pt-2" id="myTabjustifiedContent">

            <div class="tab-pane fade show active" id="data-ratio-justified" role="tabpanel" aria-labelledby="data-ratio-tab">
              <h5 class="card-title">Daftar Key SD</h5>

              <!-- 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">Edit</th>
                    <th class="text-center align-middle" style="padding:8px">Nama Tipe</th>
                    <th class="text-center align-middle" style="padding:8px">Warna</th>
                    <th class="text-center align-middle" style="padding:8px">Key SD</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  if ($key_sd_result->num_rows > 0) {
                    while ($target = $key_sd_result->fetch_assoc()) {
                  ?>
                      <tr>
                        <td style="padding:3px">
                          <form action="key_sd_edit.php" method="GET">
                            <input type="hidden" name="idkeystockdays" value="<?php echo $target['idkeystockdays']; ?>">
                            <button type="submit" class="btn btn-outline-warning" style="--bs-btn-padding-y: .1rem; --bs-btn-padding-x: .5rem; --bs-btn-font-size: .80rem;"><i class="uil uil-edit-alt"></i></button>
                          </form>
                        </td>

                        <td style="padding:3px" class="text-start align-middle"><?php echo $target['tipe']; ?></td>
                        <td style="padding:3px" class="text-start align-middle"><?php echo $target['warna']; ?></td>
                        <td style="padding:3px" class="align-middle"><?php echo $target['key_sd']; ?></td>
                      </tr>
                  <?php
                    }
                  }
                  ?>
                </tbody>
              </table>
              <!-- End Table with stripped rows -->


            </div>



            <div class="tab-pane fade" id="input-key_sd-justified-excel" role="tabpanel" aria-labelledby="input-key_sd-tab-excel">
              <h5 class="card-title">Excel Key SD</h5>
              <p>File Excel yg di upload, harus berasal dari File Master</p>
              <div class="card-body d-flex justify-content-between mt-4">
                <!-- Tombol Download Master -->
                <div class="col-sm-4">
                  <a href="?download=true" class="btn btn-outline-primary w-100">
                    <i class="uil uil-file-download"></i> Download Master
                  </a>
                </div>

                <!-- Form Upload Excel -->
                <div class="col-sm-4">
                  <form action="" method="post" enctype="multipart/form-data">
                    <input class="form-control" type="file" name="excel_file" required>
                    <button type="submit" name="upload" class="btn btn-outline-success w-100 mt-2">
                      <i class="uil uil-file-upload"></i> Upload Excel
                    </button>
                  </form>
                </div>
              </div>

            </div>

          </div><!-- End Default Tabs -->

        </div>
      </div>

    </section>

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


  <!-- ======= Footer ======= -->
  <footer id="footer" class="footer">
    <div class="copyright">
      IT Lautan Teduh Interniaga <strong><span>&copy; 2024</span></strong>
    </div>
    <div class="credits">
      Created by <a href="https://github.com/Rizky-Boolean/"><strong>Fadhil IT</strong></a><strong></strong>
    </div>
  </footer><!-- End Footer -->

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

  <!-- jQuery (harus sebelum DataTables) -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <!-- DataTables JS -->
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>



  <!-- Main JS File -->
  <script src="assets/js/main.js"></script>

  <script>
    $(document).ready(function() {
      // Initialize select2 for dealer dropdown
      $('#dealer').select2({
        theme: 'bootstrap-5',
        placeholder: "Pilih Dealer",
        allowClear: true
      });

      // Event listener ketika dealer dipilih
      $('#dealer').on('change', function() {
        var selectedDealer = $(this).find('option:selected');
        var dealerCode = selectedDealer.val();
        var dealerName = selectedDealer.data('name');

        // Set value ke input idkeystockdays dan name_dealer
        $('#idkeystockdays').val(dealerCode);
        $('#name_dealer').val(dealerName);
      });
    });

    $(document).ready(function() {
      $('#targetTable').DataTable({
        "lengthMenu": [
          [15, 30, -1],
          [15, 30, "All"]
        ], // Mengubah teks lengthMenu
        "paging": true, // Enable pagination
        "searching": true, // Enable searching
        "ordering": true, // Enable column ordering
        "language": {
          "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
          "infoEmpty": "Menampilkan 0 sampai 0 dari 0 entri",
          "search": "Cari : ", // Mengubah teks pencarian
          "lengthMenu": "Tampil _MENU_ data",
          "paginate": {
            "previous": "<span aria-hidden='true'>&laquo;</span>",
            "next": "<span aria-hidden='true'>&raquo;</span>"
          }
        },
        "pagingType": "full_numbers", // Gaya pagination full dengan Bootstrap
        "dom": '<"top"lf>rt<"bottom"ip><"clear">' // Menempatkan lengthMenu (l) dan searching (f) di atas
      });
    });
  </script>


</body>

</html>