<?php 
// if (isset($_SESSION['user'])) 
// {
//   $id = $_SESSION['user'];
//   $stmt = $pdo->prepare("SELECT * FROM user_akses WHERE id = :id");
//   $stmt->bindParam(':id', $id, PDO::PARAM_INT);
//   $stmt->execute();
//   $data = $stmt->fetchAll();
//   $nama = $data[0]['nama'];
//   $nomor = $data[0]['nomor_whatsapp'];
//   $username = $data[0]['username'];
//   $email = $data[0]['email'];
//   $profile = $data[0]['profile'];
// } 
// elseif (isset($_SESSION['master'])) 
// {
//   $id = $_SESSION['master'];
//   $stmt = $pdo->prepare("SELECT * FROM data_server WHERE id = :id");
//   $stmt->bindParam(':id', $id, PDO::PARAM_INT);
//   $stmt->execute();
//   $data = $stmt->fetchAll();
//   $nama = $data[0]['nama_pemilik'];
//   $nomor = $data[0]['nomor_whatsapp'];
//   $username = $data[0]['username'];
//   $email = $data[0]['email'];
//   $profile = $data[0]['profile'];
// }

$id = $page[1];
$stmt = $pdo->prepare("SELECT * FROM data_server WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();
$nama = $data[0]['nama_pemilik'];
$nomor = $data[0]['nomor_whatsapp'];
$username = $data[0]['username'];
$email = $data[0]['email'];
$profile = $data[0]['profile'];
// echo "<pre>";
// print_r($data);
// echo "</pre>";

?>
<!-- Main content -->
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header bg-info">
            <div class="row">
              <div class="col-sm-6">
                <h3 class="card-title">Detail Data Server</h3>
              </div>
              <div class="col-sm-6">
              </div>
            </div>
          </div>
          <!-- /.card-header -->
            <div class="card-body">
              <div class="row">
                <div class="col-md-5">
                  <div class="card">
                    <div class="card-body">
                      <form method="post" enctype="multipart/form-data">
                        <table class="table table-borderless">
                          <center>
                            <label>Foto Profile</label>
                            <div class="uploadImage" data-id="profile" style="width: 25%; zoom: 60%;">
                              <span>Click to upload image</span>
                              <img src="#" alt="Image preview">
                              <div class="progressContainer">
                                <div class="progressBar"></div>
                              </div>
                            </div>
                          </center>
                          <tbody>
                            <tr>
                              <td class="p-2">Nama</td>
                              <td class="p-2">:</td>
                              <td class="p-2"><input type="text" class="form-control" value="<?php echo $nama; ?>" name="nama" required="required"></td>
                            </tr>
                            <tr>
                              <td class="p-2">Nomor WhatsApp</td>
                              <td class="p-2">:</td>
                              <td class="p-2"><input type="text" class="form-control" value="<?php echo $nomor; ?>" name="nomor" required="required"></td>
                            </tr>
                            <tr>
                              <td class="p-2">Username</td>
                              <td class="p-2">:</td>
                              <td class="p-2"><input type="text" class="form-control" value="<?php echo $username; ?>" name="username" required="required"></td>
                            </tr>
                            <tr>
                              <td class="p-2">Email</td>
                              <td class="p-2">:</td>
                              <td class="p-2"><input type="text" class="form-control" value="<?php echo $email; ?>" name="email" required="required"></td>
                            </tr>
                          </tbody>
                        </table>
                        <input type="submit" class="btn btn-sm btn-primary m-1" name="simpan" value="Simpan">
                      </form>

<?php if (isset($_SESSION['user'])) { ?>

<button class="btn btn-primary btn-block text-center" id="absenButton" onclick="handleAbsen()">Loading...</button>
<script>
  let absenStatus = 'belum'; // default

  function updateButtonFromStatus() {
    absenStatus = AndroidInterface.getTrackingStatus();
    const btn = document.getElementById('absenButton');

    if (absenStatus === 'masuk') {
      btn.innerText = 'Absen Keluar';
    } else {
      btn.innerText = 'Absen Masuk';
    }
  }

  function handleAbsen() {
    const userId = '<?=$id?>';
    const btn = document.getElementById('absenButton');

    if (absenStatus === 'masuk') {
      AndroidInterface.stopTracking();
      absenStatus = 'belum';
      btn.innerText = 'Absen Masuk';
    } else {
      AndroidInterface.startTracking(userId);
      absenStatus = 'masuk';
      btn.innerText = 'Absen Keluar';
    }
  }

  window.onload = updateButtonFromStatus;
</script>

<?php } ?>


                      <hr>
                      <form method="post" enctype="multipart/form-data">
                        <table class="table table-borderless">
                          <center>
                            <label>Ubah Password</label>
                          </center>
                          <tbody>
                            <tr>
                              <td class="p-2">Password</td>
                              <td class="p-2">:</td>
                              <td class="p-2">
                              <div class="input-group mb-4">
                                  <input type="password" class="form-control" name="password" placeholder="Password">
                                  <div class="input-group-append">
                                      <div class="input-group-text">
                                          <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                                      </div>
                                  </div>
                              </div>
                              </td>
                            </tr>
                            <tr>
                              <td class="p-2">Confirm Password</td>
                              <td class="p-2">:</td>
                              <td class="p-2">
                              <div class="input-group mb-4">
                                  <input type="password" class="form-control" name="confirm_password" placeholder="Ulangi Password">
                                  <div class="input-group-append">
                                      <div class="input-group-text">
                                          <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                                      </div>
                                  </div>
                              </div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                        <input type="submit" class="btn btn-sm btn-primary m-1" name="simpanPassword" value="Simpan Password">
                      </form>
                    </div>
                  </div>
                </div>
                <div class="col-md-7">
                  <?php $data1111 = "123"; if (isset($id) && $data1111 == "123") { ?>
                  <div class="card">
                    <div class="card-body">
                      <a type="button" class="btn btn-info btn-sm mb-3" data-toggle="modal" data-target="#staticBackdrop">Perpanjang Sewa</a>
                      <?php
                        $expiredDate = $data[0]['expaired_date'];
                        $currentDate = date('Y-m-d');
                        $diff = strtotime($expiredDate) - strtotime($currentDate);
                        $daysLeft = ceil($diff / (60 * 60 * 24));
                      ?>
                      <?php if ($daysLeft <= 0) { ?>
                      <div class="card bg-danger text-center mb-1">
                        <p class="mb-0">Telah berakhir <b><?php echo substr($daysLeft,1); ?></b> hari lalu</p>
                      </div>
                      <?php } else { ?>
                      <div class="card bg-success text-center mb-1">
                        <p class="mb-0">Akan berakhir <b><?php echo $daysLeft; ?></b> hari lagi</p>
                      </div>
                      <?php } ?>
                       <h5 class="text-center">Tanggal Kedaluarsa : <?php echo $expiredDate; ?></h5>
                       <hr>
                      <!-- Modal Tambah -->
                      <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                        <div class="modal-dialog">
                          <div class="modal-content">
                            <form method="post" enctype="multipart/form-data">
                              <div class="modal-header bg-primary">
                                  <h5 class="modal-title" id="staticBackdropLabel">Pilih Periode Pembayaran</h5>
                                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                      <span aria-hidden="true">&times;</span>
                                  </button>
                              </div>
                              <div class="modal-body" style="font-size: 20px;">
                                  <?php
                                  $harga_sewa = $data[0]['harga_sewa'];
                                  $harga1bln = $harga_sewa;
                                  $harga3bln = $harga_sewa * 3 * 0.95;
                                  $harga6bln = $harga_sewa * 6 * 0.90;
                                  $harga12bln = $harga_sewa * 12 * 0.85;
                                  ?>
                                  <div class="form-group">
                                      <div class="custom-control custom-radio">
                                          <input class="custom-control-input" type="radio" id="customRadio1" value="<?php echo $harga1bln; ?>" name="customRadio" checked>
                                          <label for="customRadio1" class="custom-control-label">Pembayaran 1 Bulan => Rp. <?php echo number_format($harga1bln, 0, ',', '.'); ?></label>
                                      </div>
                                  </div>
                                  <div class="form-group">
                                      <div class="custom-control custom-radio">
                                          <input class="custom-control-input" type="radio" id="customRadio2" value="<?php echo $harga3bln; ?>" name="customRadio">
                                          <label for="customRadio2" class="custom-control-label">Pembayaran 3 Bulan => Rp. <?php echo number_format($harga3bln, 0, ',', '.'); ?></label>
                                      </div>
                                  </div>
                                  <div class="form-group">
                                      <div class="custom-control custom-radio">
                                          <input class="custom-control-input" type="radio" id="customRadio3" value="<?php echo $harga6bln; ?>" name="customRadio">
                                          <label for="customRadio3" class="custom-control-label">Pembayaran 6 Bulan => Rp. <?php echo number_format($harga6bln, 0, ',', '.'); ?></label>
                                      </div>
                                  </div>
                                  <div class="form-group">
                                      <div class="custom-control custom-radio">
                                          <input class="custom-control-input" type="radio" id="customRadio4" value="<?php echo $harga12bln; ?>" name="customRadio">
                                          <label for="customRadio4" class="custom-control-label">Pembayaran 12 Bulan => Rp. <?php echo number_format($harga12bln, 0, ',', '.'); ?></label>
                                      </div>
                                  </div>
                              </div>
                              <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                  <input type="submit" name="konfirmasi" class="btn btn-primary" value="Konfirmasi">
                              </div>
                          </form>

                          <?php

                          if (isset($_POST['konfirmasi'])) {
                              $harga = $_POST['customRadio'] ?? 0;
                              $expaired = $UserMaster['expaired_date'];
                              $keterangan = '';

                              switch ($harga) {
                                  case $harga1bln:
                                      $expaired = date('Y-m-d', strtotime('+1 month', strtotime($expaired)));
                                      $keterangan = "Pembayaran sewa Apk BilsPro 1 Bulan";
                                      break;
                                  case $harga3bln:
                                      $expaired = date('Y-m-d', strtotime('+3 months', strtotime($expaired)));
                                      $keterangan = "Pembayaran sewa Apk BilsPro 3 Bulan";
                                      break;
                                  case $harga6bln:
                                      $expaired = date('Y-m-d', strtotime('+6 months', strtotime($expaired)));
                                      $keterangan = "Pembayaran sewa Apk BilsPro 6 Bulan";
                                      break;
                                  case $harga12bln:
                                      $expaired = date('Y-m-d', strtotime('+12 months', strtotime($expaired)));
                                      $keterangan = "Pembayaran sewa Apk BilsPro 12 Bulan";
                                      break;
                                  default:
                                      // Handle the case where the value of customRadio is not expected
                                      $expaired = $UserMaster['expaired_date'];
                                      $keterangan = "Pembayaran tidak valid";
                                      break;
                              }

                              // Set waktu transaksi
                              $waktu = date('Y-m-d H:i:s');

                              function generateOrderId($pdo) {
                                  do {
                                      //"ORDER_ID_" .
                                      $order_id = sprintf('%010d', mt_rand(0, 9999999999999)); // Generate 13 digit number
                                      $stmt = $pdo->prepare("SELECT COUNT(*) FROM apk_payment WHERE order_id = :order_id");
                                      $stmt->bindParam(':order_id', $order_id);
                                      $stmt->execute();
                                      $exists = $stmt->fetchColumn();
                                  } while ($exists > 0);
                                  return $order_id;
                              }

                              $order_id = generateOrderId($pdo);

                              // Prepare and execute the SQL statement
                              $stmt = $pdo->prepare("INSERT INTO apk_payment 
                                  (id_data_server, order_id, keterangan, waktu_transaksi, nominal, expaired_time, status) 
                                  VALUES 
                                  (:id, :order_id, :keterangan, :waktu_transaksi, :nominal, :expaired_time, 'BELUM DIBAYAR')");
                              $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                              $stmt->bindParam(':order_id', $order_id);
                              $stmt->bindParam(':keterangan', $keterangan);
                              $stmt->bindParam(':waktu_transaksi', $waktu);
                              $stmt->bindParam(':nominal', $harga);
                              $stmt->bindParam(':expaired_time', $expaired);

                              // Execute the statement
                              if ($stmt->execute()) {
                                  sweetAlert("Pembayaran Telah dibuat, silahkan lanjutkan proses pembayaran", "success");
                                  // Redirect to checkout process or any other page
                                  // header("Location: ../midtrans/examples/snap/checkout-process-simple-version.php");
                                  // exit();
                              } else {
                                  sweetAlert("Terjadi kesalahan dalam proses pembayaran", "error");
                              }
                          }
                          ?>

                          </div>
                        </div>
                      </div>
                      <h6>Riwayat Pembayaran</h6>
                      <table id="example2" class="table table-bordered" style="zoom: 90%;">
                        <thead>
                          <tr>
                            <th>Order Time</th>
                            <th>Priode</th>
                            <th>Nominal</th>
                            <th>Status</th>
                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                          // Query untuk mengambil data dari tabel apk_payment
                          $stmt = $pdo->prepare("SELECT * FROM apk_payment WHERE id_data_server = :id ORDER BY waktu_transaksi");
                          $stmt->bindParam(':id', $id);
                          $stmt->execute();

                          // Ambil semua hasil dari query
                          $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                          foreach ($results as $row) {
                          ?>
                          <tr>
                              <td><?php echo htmlspecialchars($row['waktu_transaksi']); ?></td>
                              <td><?php echo htmlspecialchars($row['keterangan']); ?></td>
                              <td><?php echo number_format($row['nominal'], 0, ',', '.'); ?></td>
                              <td><?php echo htmlspecialchars($row['status']); ?></td>
                              <td>
                                <form method="post">
                                  <?php if($row['status'] == 'PENDING' || $row['status'] == 'BELUM DIBAYAR') { ?>
                                    <a href="payment/paydisini/?order_id=<?php echo htmlspecialchars($row['order_id']); ?>" class="btn btn-sm btn-primary m-1">Bayar</a>
                                  <?php if($row['status'] == 'BELUM DIBAYAR') { ?>
                                    <input type="submit" name="hapus<?php echo $row['id']; ?>" class="btn btn-sm btn-danger m-1" value="Hapus" >
                                  <?php } } else { ?>
                                  <a href="payment/paydisini/?order_id=<?php echo htmlspecialchars($row['order_id']); ?>" class="btn btn-sm btn-secondary m-1">Detail</a>
                                  <?php } ?>
                                </form>
                              </td>
                          </tr>
                          <?php
                            if(isset($_POST['hapus'.$row['id']])) 
                            {
                              $iddata = $row['id'];
                              deleteAlert("apk_payment",$iddata );
                            }
                          }
                          ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <?php } else { if($status_menu == "Tidak Aktif") { ?>
                  <div class="card">
                    <div class="card-body">
                      <center>
                        <h2 class="text-danger"><b>ACCESS DENIED</b></h2>
                        <img src="dist/img/denied.jpg" width="50%">
                        <h5>Silahkan hubungi admin untuk mengaktifkan akses aplikasi</h5>
                      </center>
                    </div>
                  </div>
                  <?php } } ?>
                </div>
              </div>
            </div>
            <div class="card-footer">

            </div>
          </div>
      </div>
    </div>
  </div>
</section>

<?php
//   if (isset($_POST['simpanPassword'])) {
//     if ($_POST['password'] == $_POST['confirm_password']) {
//       $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
//       if (isset($_SESSION['user']['id'])) {
//         $stmt = $pdo->prepare("UPDATE user_akses SET password = :password WHERE id = :idtik");
//         $stmt->bindParam(':password', $hashedPassword);
//         $stmt->bindParam(':idtik', $id, PDO::PARAM_INT);
//         $stmt->execute();
//         session_destroy();
//         sweetAlert("Password telah di ubah silahkan Login kembali", "success", baseurl('../login'));
//       } elseif(isset($_SESSION['master']['id'])) {
//         $stmt = $pdo->prepare("UPDATE data_server SET password = :password WHERE id = :idtik");
//         $stmt->bindParam(':password', $hashedPassword);
//         $stmt->bindParam(':idtik', $id, PDO::PARAM_INT);
//         $stmt->execute();
//         session_destroy();
//         sweetAlert("Password telah di ubah silahkan Login kembali", "success", baseurl('../login'));
//       }
//     }else{
//       sweetAlert("Password tidak sesuai, mohon periksa kembali", "info");
//     }
//   }
  
// if (isset($_POST['simpan'])) {
//     // Validasi jika file sudah di-upload
//     if (!empty($_SESSION['uploaded_files']['profile'])) {
//         try {
//             // Pastikan PDO instance sudah diinisialisasi (contoh: $pdo)
//             $id = $_SESSION['user'] ?? $_SESSION['master'] ?? null;
//             if ($id === null) {
//                 sweetAlert("ID pengguna tidak ditemukan.", "error");
//                 exit;
//             }

//             // Tentukan tabel dan kolom sesuai role
//             if (isset($_SESSION['user'])) {
//                 $table = "user_akses";
//                 $columns = [
//                     'email' => $_POST['email'],
//                     'nama' => $_POST['nama'],
//                     'nomor_whatsapp' => $_POST['nomor'],
//                     'username' => $_POST['username'],
//                     'profile' => $_SESSION['uploaded_files']['profile'],
//                 ];
//             } elseif (isset($_SESSION['master'])) {
//                 $table = "data_server";
//                 $columns = [
//                     'email' => $_POST['email'],
//                     'nama_pemilik' => $_POST['nama'],
//                     'nomor_whatsapp' => $_POST['nomor'],
//                     'username' => $_POST['username'],
//                     'profile' => $_SESSION['uploaded_files']['profile'],
//                 ];
//             } else {
//                 sweetAlert("Role pengguna tidak valid.", "error");
//                 exit;
//             }

//             // Siapkan query dan bind parameter
//             $setPart = [];
//             foreach ($columns as $key => $value) {
//                 $setPart[] = "$key = :$key";
//             }
//             $query = "UPDATE $table SET " . implode(", ", $setPart) . " WHERE id = :id";
//             $stmt = $pdo->prepare($query);

//             foreach ($columns as $key => $value) {
//                 $stmt->bindValue(":$key", $value);
//             }
//             $stmt->bindValue(':id', $id, PDO::PARAM_INT);

//             // Eksekusi query
//             $stmt->execute();

//             // Feedback ke pengguna
//             sweetAlert("Profile telah di edit", "success");
//         } catch (PDOException $e) {
//             sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
//         }
//     } else {
//         sweetAlert("Gambar belum di upload", "error");
//     }
// }

// $_SESSION['uploaded_files']['profile'] = $profile;
?>
<script>
document.querySelectorAll('.toggle-password').forEach(function(toggle) {
    toggle.addEventListener('click', function() {
        // Mengambil elemen input yang bersangkutan
        const input = this.closest('.input-group').querySelector('input');
        
        // Mengubah tipe input
        if (input.type === 'password') {
            input.type = 'text';
            this.classList.remove('fa-eye');
            this.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            this.classList.remove('fa-eye-slash');
            this.classList.add('fa-eye');
        }
    });
});
</script>