<?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 rasio_service1 untuk isi
$rasio_kunci = "SELECT * FROM `allocation_rasiokunci`";
$rasio_result = $conn->query($rasio_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);

// Cek jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // Mengambil data dari form
  $tipe = $_POST['tipe'];
  $warna = $_POST['warna'];
  $rasio = $_POST['rasio'];
  // $tipe = isset($_POST['tipe']) ? $_POST['tipe'] : '';
  // $warna = isset($_POST['warna']) ? $_POST['warna'] : '';
  // $rasio = isset($_POST['rasio']) ? $_POST['rasio'] : '';

  // Cek apakah data sudah ada di dalam database
  $check_query = "SELECT * FROM allocation_rasiokunci WHERE tipe='$tipe' AND warna='$warna'";
  $check_result = $conn->query($check_query);

  // Pastikan semua data diambil
  if (!empty($tipe) && !empty($warna) && !empty($rasio)) {
    echo $tipe;
    echo $warna;
    echo $rasio;
    if ($check_result->num_rows > 0) {
      // Jika data sudah ada, lakukan update
      $update_query = "UPDATE allocation_rasiokunci SET
          rasio = '$rasio'
          WHERE tipe = '$tipe'
          AND warna = '$warna'";

      if ($conn->query($update_query) === TRUE) {
        // Redirect ke halaman target.php setelah update berhasil
        header("Location: key_ratio.php");
        exit(); // pastikan script berhenti setelah redirect
      } else {
        echo "Error updating data: " . $conn->error;
      }
    } else {
      // Jika data belum ada, lakukan insert
      $insert_query = "INSERT INTO allocation_rasiokunci (tipe, warna, rasio)
                      VALUES ('$tipe', '$warna', '$rasio')";

      if ($conn->query($insert_query) === TRUE) {
        // Redirect ke halaman key_ratio.php setelah insert berhasil
        header("Location: key_ratio.php");
        exit(); // pastikan script berhenti setelah redirect
      } else {
        echo "Error inserting data: " . $conn->error;
      }
    }
  } else {
    echo "Pastikan semua data terisi.";
  }
}

?>

<!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_ratio'; // 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 Rasio</button>
            </li>
            <li class="nav-item flex-fill" role="presentation">
              <button class="nav-link w-100" id="input-rasio-tab" data-bs-toggle="tab" data-bs-target="#input-rasio-justified" type="button" role="tab" aria-controls="input-rasio" aria-selected="true">Input Rasio</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 Rasio</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">Rasio</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  if ($rasio_result->num_rows > 0) {
                    while ($target = $rasio_result->fetch_assoc()) {
                  ?>
                      <tr>
                        <td style="padding:3px"><form action="key_ratio_edit.php" method="GET">
                              <input type="hidden" name="idrasiokunci" value="<?php echo $target['idrasiokunci']; ?>">
                              <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 number_format($target['rasio'], 1); ?></td>
                      </tr>
                  <?php
                    }
                  }
                  ?>
                </tbody>
              </table>
              <!-- End Table with stripped rows -->


            </div>



            <div class="tab-pane fade" id="input-rasio-justified" role="tabpanel" aria-labelledby="input-rasio-tab">
              <h5 class="card-title">Tambah Rasio</h5>
              
              <!-- Form untuk menambahkan data -->
              <form method="POST" onsubmit="return confirmSubmit()">
                
                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" style="font-size:14px">Tipe</label>
                  <div class="col-sm-10">
                    <select name="tipe" id="tipe" class="form-control select2" style="font-size:14px" required>
                      <option value="" disabled selected hidden>Pilih Tipe</option>
                      <?php
                      if ($tipe_result->num_rows > 0) {
                        while ($tipe = $tipe_result->fetch_assoc()) {
                      ?>
                          <option value="<?php echo $tipe['tipe']; ?>"
                            data-name="<?php echo htmlspecialchars($tipe['tipe']); ?>">
                            <?php echo htmlspecialchars($tipe['tipe']); ?>
                          </option>
                      <?php
                        }
                      }
                      ?>
                    </select>
                  </div>
                </div>

                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" style="font-size:14px">Warna</label>
                  <div class="col-sm-10">
                    <select name="warna" id="warna" class="form-control select2" style="font-size:14px" required>
                      <option value="" disabled selected hidden>Pilih Warna</option>
                      <?php
                      if ($warna_result->num_rows > 0) {
                        while ($warna = $warna_result->fetch_assoc()) {
                      ?>
                          <option value="<?php echo $warna['warna']; ?>"
                            data-name="<?php echo htmlspecialchars($warna['warna']); ?>">
                            <?php echo htmlspecialchars($warna['warna']); ?>
                          </option>
                      <?php
                        }
                      }
                      ?>
                    </select>
                  </div>
                </div>

                <div class="row mb-3">
                  <label class="col-sm-2 col-form-label" style="font-size:14px">Rasio</label>
                  <div class="col-sm-10">
                    <input type="number" class="form-control" name="rasio" placeholder="Masukkan rasio" style="font-size:14px" value="<?php echo $rasio; ?>" step="0.01"  required>
                  </div>
                </div>

                <div class="col-12 d-flex justify-content-start">
                  <button class="btn btn-primary mt-3 me-2" type="submit">Simpan</button>
                </div>
              </form><!-- END General Form Elements -->
            </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 idrasiokunci dan name_dealer
        $('#idrasiokunci').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>