<?php

$idTiket = array();
$listid = mysqli_query($con,"SELECT id_pelanggan FROM tiket_gangguan WHERE status IN (1,2,3,4) $SqlDataId");
while ($tiapId = mysqli_fetch_assoc($listid)) {
    $idTiket[] = $tiapId['id_pelanggan'];
}

// print_r($idTiket);

$datapel = array();
$ambil = $con->query("SELECT * FROM pelanggan WHERE status ='aktif' $SqlDataId ORDER BY nama ASC");
while ($tiap = $ambil->fetch_assoc()) {
    $datapel[] = $tiap;
}
// echo base_url();
// echo encryptNumberID('123');
?>
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header bg-primary">
            <div class="row">
              <div class="col-sm-6">
                <h5>Buat Tiket</h5>
              </div>
              <div class="col-sm-6"></div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <form method="post" enctype="multipart/form-data">
             <div class="row">
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Pilih Server</label>
                    <select class="form-control" required="required" name="ids">
                      <option value="">Pilih</option>
                      <?php 
                      $List->set_list("data_server", $SqlDataWH);
                      foreach ($List->get_list() as $key => $value): ?>
                        <option value="<?php echo htmlspecialchars($value['id']); ?>"><?php echo htmlspecialchars($value['nama_server']); ?></option>
                      <?php endforeach ?>
                    </select>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Jenis Gangguan</label>
                    <select id="jenis" class="form-control" name="jenis">
                      <option value="">Pilih Jenis</option>
                      <option value="Pelanggan">Pelanggan</option>
                      <option value="Jalur Utama">Jalur Utama</option>
                      <option value="Lainnya">Lainnya</option>
                    </select>
                  </div>
                </div>
              </div>
              <div id="form-content"></div>
            </div>
            <div class="card-footer">
              <input type="submit" name="tambah" class="btn btn-primary" value="Tambah">
            </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<?php
if (isset($_POST['tambah'])) {
  $cekinput = true;
    if ($_POST['jenis'] == 'Pelanggan') {
        if(!in_array($_POST['pelanggan'],$idTiket)) {
            $stmt = $pdo->prepare("SELECT id_data_server, alamat, latitude, longitude FROM pelanggan WHERE id = :idp");
            $stmt->bindParam(':idp', $_POST['pelanggan'], PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
            $idds = $result['id_data_server'];
            $idpel = $_POST['pelanggan'];
            $idpet = $UserId;
            $jenis = $_POST['jenis'];
            $permasalahan = $_POST['masalah'];
            $timestart = date('Y-m-d H:i:s');
            $lokasi = $result['alamat'];
            $latitude = $result['latitude'];
            $longitude = $result['longitude'];
        } else {
            $cekinput = false;
        }
    } else {
    $idds = $_POST['ids'];
    $idpel = '0';
    $idpet = $UserId;
    $jenis = $_POST['jenis'];
    $permasalahan = $_POST['masalah'];
    $timestart = date('Y-m-d H:i:s'); 
    $lokasi = $_POST['tempat'];
    $latitude = NULL;
    $longitude = NULL;
    }
    
    
    $stmt = $pdo->prepare("INSERT INTO tiket_gangguan (id_data_server, id_pelanggan, id_pembuat_tiket, jenis_tiket, permasalahan, start_time, status, lokasi, latitude, longitude) VALUES 
    (:idds, :idpel, :idpet, :jenis, :permasalahan, :timestart, '1', :lokasi, :latitude, :longitude)");
    $stmt->bindParam(':idds', $idds, PDO::PARAM_INT);
    $stmt->bindParam(':idpel', $idpel, PDO::PARAM_INT);
    $stmt->bindParam(':idpet', $idpet, PDO::PARAM_INT);
    $stmt->bindParam(':jenis', $jenis);
    $stmt->bindParam(':permasalahan', $permasalahan);
    $stmt->bindParam(':timestart', $timestart);
    $stmt->bindParam(':lokasi', $lokasi);
    $stmt->bindParam(':latitude', $latitude);
    $stmt->bindParam(':longitude', $longitude);
    $stmt->execute();
    
    $lastId = $pdo->lastInsertId();

    if($cekinput){
        $tiketId = encryptNumberID($lastId);
        // 4. Update kolom tiket_id
        $update = $pdo->prepare("UPDATE tiket_gangguan SET tiket_id = :tiket_id WHERE id = :id");
        $update->bindParam(':tiket_id', $tiketId);
        $update->bindParam(':id', $lastId, PDO::PARAM_INT);
        $update->execute();
        sweetAlert("Tiket gangguan telah dibuat", "success", "?".encrypt_url('tiket_buat'));
    }
    else {
        sweetAlert("Pelanggan sudah di buatkan Tiket atau Tiket masih dalam proses", "error");
    }
}
?>


<script type="text/javascript">

document.addEventListener('DOMContentLoaded', function() {
    const jenisSelect = document.getElementById('jenis');
    const formContent = document.getElementById('form-content');
    
    // Show appropriate form based on selected type
    jenisSelect.addEventListener('change', function() {
        const jenis = this.value;
        formContent.innerHTML = '';

        if (jenis === 'Pelanggan') {
            formContent.innerHTML = `
                <div class="form-group">
                    <label>Nama Pelanggan</label>
                    <select class="form-control select2bs4" name="pelanggan" required="required">
                        <option value="">Pilih</option>
                        ${<?php echo json_encode($datapel); ?>.map(pelanggan => 
                            `<option value="${pelanggan.id}">${pelanggan.nama} (${pelanggan.alamat})</option>`
                        ).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label>Indikasi Masalah</label>
                    <textarea name="masalah" rows="5" class="form-control" required="required"></textarea>
                </div>
                <input type="hidden" name="jenis1" value="${jenis}">
            `;
            $('.select2bs4').select2({
                  theme: 'bootstrap4',
                  placeholder: 'Pilih Pelanggan',
                  allowClear: true
              });
        } else if (jenis === 'Jalur Utama' || jenis === 'Lainnya') {
            formContent.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Tempat</label>
                            <input type="text" class="form-control" name="tempat" required="required">
                        </div>
                        <div class="form-group">
                            <label>Indikasi Masalah</label>
                            <textarea name="masalah" rows="5" class="form-control" required="required"></textarea>
                        </div>
                    </div>
                    <div class="col-md-6">
                    
                    </div>
                </div>
            `;
            // Initialize map after content is added
            if (typeof initMap === 'function') {
                initMap();
            }
        }
    });

    // Pre-select the previous value
    const previousJenis = "<?php echo $_POST['jenis'] ?? ''; ?>";
    if (previousJenis) {
        jenisSelect.value = previousJenis;
        jenisSelect.dispatchEvent(new Event('change'));
    }
});

</script>