<?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();
}

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

// Mendapatkan data dealer untuk dropdown
$dealer_query = "SELECT name_dealer, code_dealer FROM dealer";
$dealer_result = $conn->query($dealer_query);

// Cek jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // Mengambil data dari form
  $site_id = $_POST['site_id'];
  $name_dealer = $_POST['name_dealer'];
  $bulan = $_POST['bulan'];
  $tahun = $_POST['tahun'];
  $jml_tech = $_POST['jml_tech'];
  $unit_ksg = $_POST['unit_ksg'];
  $unit_ksb = $_POST['unit_ksb'];
  $jasa_ksg = $_POST['jasa_ksg'];
  $jasa_ksb = $_POST['jasa_ksb'];
  $part_ws = $_POST['part_ws'];
  $oli_ws = $_POST['oli_ws'];
  $hari_kerja = $_POST['hari_kerja'];

  // Mengambil dealer_code dari form
  $dealer_code = $_POST['dealer_code'];

  // Cek apakah data sudah ada di dalam database
  $check_query = "SELECT * FROM target_service WHERE site_id='$dealer_code' AND bulan='$bulan' AND tahun='$tahun'";
  $check_result = $conn->query($check_query);

  if ($check_result->num_rows > 0) {
    // Jika data sudah ada, lakukan update
    $update_query = "UPDATE target_service SET
        jml_tech = '$jml_tech',
        unit_ksg = '$unit_ksg',
        unit_ksb = '$unit_ksb',
        jasa_ksg = '$jasa_ksg',
        jasa_ksb = '$jasa_ksb',
        part_ws = '$part_ws',
        oli_ws = '$oli_ws',
        hari_kerja = '$hari_kerja'
        WHERE site_id = '$dealer_code'
        AND bulan = '$bulan'
        AND tahun = '$tahun'";

    if ($conn->query($update_query) === TRUE) {
      // Redirect ke halaman target.php setelah update berhasil
      header("Location: target.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 target_service (site_id, name_dealer, bulan, tahun, jml_tech, unit_ksg, unit_ksb, jasa_ksg, jasa_ksb, part_ws, oli_ws, hari_kerja)
                    VALUES ('$dealer_code', '$name_dealer', '$bulan', '$tahun', '$jml_tech', '$unit_ksg', '$unit_ksb', '$jasa_ksg', '$jasa_ksb', '$part_ws', '$oli_ws', '$hari_kerja')";

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


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

<body>

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

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

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

    <div class="pagetitle">
      <h1>Tambah Claim Dealer</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">Home</a></li>
          <li class="breadcrumb-item"><a href="target.php">Claim</a></li>
          <li class="breadcrumb-item active">Tambah Claim Dealer</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section dashboard">
      <div class="row">

        <!-- Left side columns -->
        <div class="col-lg-12">
          <div class="row">

            <!-- Form -->
            <div class="col-12">
              <div class="card recent-sales overflow-auto">

                <div class="card-body">
                  <h5 class="card-title">Claim Teknisi</h5>
                  <p>Data yang dimasukkan <b>Harus sesuai dengan DPACK WEB</b>, jika tidak sesuai maka akan GAGAL INPUT.</p>

                  <!-- Form untuk menambahkan data -->
                  <form method="POST" onsubmit="return confirmSubmit()">
                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Dealer</label>
                      <div class="col-sm-10">
                        <select name="dealer_code" id="dealer" class="form-control select2" required>
                          <option value="" disabled selected hidden>Pilih Dealer</option>
                          <?php
                          if ($dealer_result->num_rows > 0) {
                            while ($dealer = $dealer_result->fetch_assoc()) {
                          ?>
                              <option value="<?php echo $dealer['code_dealer']; ?>"
                                data-name="<?php echo htmlspecialchars($dealer['name_dealer']); ?>">
                                <?php echo htmlspecialchars($dealer['name_dealer']); ?>
                              </option>
                          <?php
                            }
                          }
                          ?>
                        </select>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Tahun</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="tahun" placeholder="Masukkan Tahun" value="<?php echo $tahun; ?>" required>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Bulan</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="bulan" placeholder="Masukkan Bulan" value="<?php echo $bulan; ?>" required>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Jumlah Teknisi</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="jml_tech" placeholder="Masukkan Jumlah Teknisi" value="<?php echo $jml_tech; ?>" required>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Unit KSG</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="unit_ksg" placeholder="Masukkan Unit KSG" value="<?php echo $unit_ksg; ?>" required>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Unit KSB</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="unit_ksb" placeholder="Masukkan Unit KSB" value="<?php echo $unit_ksb; ?>" required>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Jasa KSG</label>
                      <div class="col-sm-10">
                        <div class="input-group">
                          <span class="input-group-text">Rp</span>
                          <input type="number" class="form-control" name="jasa_ksg" placeholder="Masukkan Jasa KSG" value="<?php echo $jasa_ksg; ?>" required>
                        </div>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Jasa KSB</label>
                      <div class="col-sm-10">
                        <div class="input-group">
                          <span class="input-group-text">Rp</span>
                          <input type="number" class="form-control" name="jasa_ksb" placeholder="Masukkan Jasa KSB" value="<?php echo $jasa_ksb; ?>" required>
                        </div>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Part w/s</label>
                      <div class="col-sm-10">
                        <div class="input-group">
                          <span class="input-group-text">Rp</span>
                          <input type="number" class="form-control" name="part_ws" placeholder="Masukkan Part w/s" value="<?php echo $part_ws; ?>" required>
                        </div>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Oli w/s</label>
                      <div class="col-sm-10">
                        <div class="input-group">
                          <span class="input-group-text">Rp</span>
                          <input type="number" class="form-control" name="oli_ws" placeholder="Masukkan Oli w/s" value="<?php echo $oli_ws; ?>" required>
                        </div>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <label class="col-sm-2 col-form-label">Hari Kerja</label>
                      <div class="col-sm-10">
                        <input type="number" class="form-control" name="hari_kerja" placeholder="Masukkan Hari Kerja" value="<?php echo $hari_kerja; ?>" 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>
                      <button class="btn btn-secondary mt-3" type="button" onclick="window.history.back()">Batal</button>
                    </div>
                  </form><!-- END General Form Elements -->

                </div>

              </div>
            </div><!-- End Filter Laporan -->

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

  <!-- Konfirmasi sebelum submit form -->
  <script>
    function confirmSubmit() {
      return confirm('Apakah Anda yakin ingin menyimpan data ini?');
    }
    $(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 site_id dan name_dealer
        $('#site_id').val(dealerCode);
        $('#name_dealer').val(dealerName);
      });
    });
  </script>

</body>

</html>