<?php

$data = ['unique_code' => $order_id];
$response = statusTransaction($data);
$dataRespon = json_decode($response);

$waktu_tentukan = $dataRespon->data->expired;
$waktu_sekarang = date('Y-m-d H:i:s');
if (strtotime($waktu_tentukan) < strtotime($waktu_sekarang)) {
  $data = ['unique_code' => $order_id];
  deleteTransaction($data); 
}

// Query untuk mengambil data dari tabel apk_payment dan data_server
$stmt = $pdo->prepare("SELECT apk_payment.id,apk_payment.status,apk_payment.update_time,apk_payment.waktu_transaksi,apk_payment.expaired_time,apk_payment.nominal,apk_payment.data_get,apk_payment.keterangan, data_server.nama_pemilik, data_server.nama_server, data_server.username, data_server.nomor_whatsapp
    FROM apk_payment
    LEFT JOIN data_server ON apk_payment.id_data_server = data_server.id
    WHERE apk_payment.order_id = :order_id");
$stmt->bindParam(':order_id', $order_id);
$stmt->execute();
// Ambil satu baris data hasil query
$result = $stmt->fetch();
    // Ambil data dari hasil query
    $amount = $result['nominal'];
    $name = $result['keterangan'];
    $first_name = $result['nama_pemilik'];
    $last_name = '('.$result['nama_server'].')';
    $email = $result['username'].'@mail.com'; // Mengganti $mail.com dengan @mail.com
    $phone = $result['nomor_whatsapp'];

session_start();

function generateOrderId($pdo) {
  do {
      $order_id = sprintf('%013d', 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;
}
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BilsPro</title>
    <link rel="icon" href="../../dist/img/logo-sm.png" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <style>
      input[type="radio"]:checked + label img {
            border: 2px solid rgba(200, 200, 200);
            border-radius: 5px;
            padding: 5px;
          }
       body {
          background-image: url('../../dist/img/bg-payment.jpg');
          background-size: cover;
          background-position: center;
          background-repeat: no-repeat;
      }
    </style>

  </head>
    <body>
        <br>
        <br>
          <div class="container" style="max-width: 900px;">
            <center>
              <img src="../../dist/img/logo.png" width="230px" class="mb-4">
            </center>
            <div class="card">
              <div class="card-header bg-warning">
                <h5>Detail Pembayaran</h5>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6">
                    <table class="table table-borderless">
                      <tbody>
                        <tr>
                          <td>Nama Usaha</td>
                          <td><b><?php echo $result['nama_server']; ?></b></td>
                        </tr>
                        <tr>
                          <td>Nama Pemilik</td>
                          <td><b><?php echo $result['nama_pemilik']; ?></b></td>
                        </tr>
                        <tr>
                          <td>Telepon</td>
                          <td><b><?php echo $result['nomor_whatsapp']; ?></b></td>
                        </tr>
                        <tr>
                          <td>Waktu</td>
                          <td><?php echo $result['waktu_transaksi']; ?></td>
                        </tr>
                        <tr>
                          <td>Keterangan</td>
                          <td><b><?php echo $result['keterangan']; ?></b></td>
                        </tr>
                        <tr>
                          <td>Expaired Date</td>
                          <td><h5 style="color: orange;"><?php echo $result['expaired_time']; ?></h5></td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <div class="col-md-6">
                    <div class="card">
                      <div class="card-body">
                        <center>
                          <p class="m-0">Status Pembayaran</p>
                          <h3 class="mt-2" style="color: orange;"><b><?php echo $dataRespon->data->status; ?></b></h3>
                        </center>
                        <hr>
                        <table class="table table-borderless">
                          <tbody>
                            <tr>
                              <td>Total</td>
                              <td style="text-align: right;"><h2><?php echo number_format($result['nominal']); ?></h2></td>
                            </tr>
                          </tbody>
                        </table>
                        <hr>

                        <center>
                          <small><p id="countdown"></p></small>
                        </center>
                          <?php 
                          // print_r($dataRespon);
                          $dataGet = json_decode($result['data_get']);
                          if ($dataRespon->data->status == 'Pending') {
                            if ($dataGet->data->service == '11') {
                              echo '<center><h5>QRIS</h5><img src="'.$dataGet->data->qrcode_url.'" width="85%">';
                              echo '<p>*SCAN QR Untuk melakukan pembayaran</p>';
                              echo '<a href="?order_id='.$_GET['order_id'].'" class="btn btn-primary btn-sm">Cek Status Pebayaran</a><br><br>';
                            } else {
                              echo '<center><p>'.$dataGet->data->service_name.'</p>';
                              echo '<h4>'.$dataGet->data->virtual_account.'</h4>';
                              echo '<p>*Copy VA Untuk melakukan pembayaran</p>';
                              echo '<a href="?order_id='.$_GET['order_id'].'">Cek Status Pebayaran</a><br><br>';
                            }
                            echo '<a data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                                Lihat Cara pembayaran
                              </a>
                              <div class="collapse" id="collapseExample">
                              <div class="card card-body">';
                            foreach ($dataGet->payment_guide as $step) {
                              // Menampilkan judul
                              echo "<h6>{$step->title}</h6>";

                              echo "<ul>";
                              foreach ($step->content as $item) {
                                  echo "<li>{$item}</li>";
                              }
                              echo "</ul>";
                            }
                            echo '</div></div></center>';
                          }
                          elseif ($dataRespon->data->status == 'Canceled') {
                            $stmt = $pdo->prepare("UPDATE apk_payment SET status = 'CANCELED' WHERE order_id = :order_id");
                            $stmt->execute([
                                ':order_id' => $order_id 
                            ]);

                            if (strtotime(substr($result['waktu_transaksi'], 0, 10)) == strtotime(date('Y-m-d'))) {
                              echo '<center>'.$dataRespon->service->type.' anda telah Expaired, silahkan buat metode pembayaran baru<br><br>';
                              echo '<button id="pay-button" class="btn btn-primary">PILIH METODE PEMBAYARAN</button></center>';
                            } else {
                              echo '<center>'.$dataRespon->service->type.' anda telah Expaired, silahkan buat pembayaran baru di Dashboard';
                            }
                          }
                          elseif ($dataRespon->data->status == 'Success') {
                            echo '<center><img src="../../dist/img/tick.gif" width="40%">';
                            echo "<p>Pembayaran Berhasil</p>";
                            echo "<p>".$result['update_time']."</p>";
                          }

                          ?>

                          <!-- Modal -->
                          <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered modal-sm">
                              <div class="modal-content">
                                <div class="modal-header bg-warning">
                                  <img src="../../dist/img/logo_long_white.png" width="100px">
                                </div>
                                <small><small>
                                <div class="modal-body" style="background-color: rgb(240, 240, 240); text-align: left;">
                                  Total Pembayaran
                                  <h5>Rp. <?php echo number_format($result['nominal']); ?></h5>
                                  <span>Order ID : <?php echo $order_id; ?></span>
                                </div>
                                  <form method="post">
                                    <div class="modal-body" style="text-align: left; min-height: 250px;">
                                      <div class="mb-3">
                                        <label class="form-label">Virtual Account</label><br>
                                        <!-- Virtual Account -->
                                        <div class="form-check form-check-inline">
                                          <input class="form-check-input" type="radio" name="paymentMethod" id="bri" value="bri" style="display: none;">
                                          <label class="form-check-label" for="bri">
                                            <img src="../../dist/img/bri.png" width="50px" class="mb-1" alt="BRI">
                                          </label>
                                        </div>

                                        <div class="form-check form-check-inline">
                                          <input class="form-check-input" type="radio" name="paymentMethod" id="bni" value="bni" style="display: none;">
                                          <label class="form-check-label" for="bni">
                                            <img src="../../dist/img/bni.png" width="50px" class="mb-1" alt="BNI">
                                          </label>
                                        </div>

                                        <div class="form-check form-check-inline">
                                          <input class="form-check-input" type="radio" name="paymentMethod" id="mandiri" value="mandiri" style="display: none;">
                                          <label class="form-check-label" for="mandiri">
                                            <img src="../../dist/img/mandiri.png" width="50px" class="mb-1" alt="Mandiri">
                                          </label>
                                        </div><br>

                                        <!-- Qris -->
                                        <label class="form-label">Qris</label><br>
                                        <div class="form-check form-check-inline">
                                          <input class="form-check-input" type="radio" name="paymentMethod" id="qris" value="qris" style="display: none;">
                                          <label class="form-check-label" for="qris">
                                            <img src="../../dist/img/qris.png" width="50px" class="mb-1" alt="QRIS">
                                          </label>
                                        </div>
                                      </div>
                                    </div>
                                    <div class="modal-body" style="border-bottom-left-radius: 20px; border-bottom-right-radius: 20px;">
                                      <div class="d-grid gap-2">
                                        <input type="submit" name="bayar" class="btn btn-primary btn-sm btn-block" style="border-radius: 20px;" value="Bayar Sekarang">
                                      </div>
                                    </div>
                                  </form>
                                </small></small>
                              </div>
                            </div>
                          </div>
                          <!-- END Modal -->
                          <?php
                            if (isset($_POST['bayar'])) { // Tambahkan tanda kurung penutup
                                // Pastikan paymentMethod ada di POST
                                if (isset($_POST['paymentMethod'])) {
                                    // Tentukan valid_time berdasarkan paymentMethod
                                    $valid_time = ($_POST['paymentMethod'] === 'qris') ? '300' : '3600';

                                    $new_order_id = generateOrderId($pdo);

                                    // Membuat data transaksi
                                    $data = [
                                        'unique_code' => $new_order_id,
                                        'service' => $_POST['paymentMethod'],
                                        'amount' => $result['nominal'],
                                        'note' => $result['keterangan'],
                                        'valid_time' => $valid_time
                                    ];

                                    // Panggil fungsi untuk membuat transaksi
                                    $response = CreateTransaction($data);

                                    $dataCreate = json_decode($response);
                                    if ($dataCreate->success === true) {
                                      $id = $result['id'];
                                      // Persiapkan dan eksekusi query untuk memperbarui data
                                      $stmt = $pdo->prepare("UPDATE apk_payment SET data_get = :data_get, status = 'PENDING', order_id = :order_id WHERE id = :id");
                                      $stmt->execute([
                                          ':data_get' => $response,
                                          ':order_id' => $new_order_id,
                                          ':id' => $id
                                      ]);
                                      sweetAlert("Pembayaran Baru telah dibuat", "success", "?order_id=".$new_order_id);
                                    } else {
                                      sweetAlert("Error: Gagal buat pembayaran", "error");
                                    }
                                } else {
                                  sweetAlert("Error: Payment method not provided.", "error");
                                }
                            }
                            ?>
                      </div>
                    </div>
                  </div>
                </div>  
              </div>
              <center style="margin-bottom: 10px;">
                <span><small>Support By </small><img src="https://web.paydisini.co.id/assets/logo.png" width="70px"></span>
              </center>
            </div>
            <center>
              <div class="mt-3 mb-4">
                <a href="<?= "https://" . $_SERVER['HTTP_HOST'] . "/?" . encrypt_url('setting_profile'); ?>">Kembali ke Dashboard</a>
              </div>
            </center>
          </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
    <script>
      document.getElementById('pay-button').addEventListener('click', function() {
        var myModal = new bootstrap.Modal(document.getElementById('paymentModal'));
        myModal.show();
      });
    </script>
    <script>
    // Set waktu target (dalam format YYYY-MM-DD HH:MM:SS)
    var targetDate = new Date("<?php echo $dataRespon->data->expired; ?>");

    var status = "<?php echo $dataRespon->data->status; ?>";
    // Update setiap detik
    if (status === "Pending") {
        var countdownFunction = setInterval(function() {
            // Dapatkan waktu sekarang
            var now = new Date().getTime();
            
            // Hitung selisih waktu
            var distance = targetDate - now;

            // Hitung jam, menit, detik
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

            // Inisialisasi string countdown
            var countdownText = "";

            // Hanya tampilkan jam jika lebih dari 0
            if (hours > 0) {
                countdownText += hours + " jam ";
            }

            // Hanya tampilkan menit jika lebih dari 0
            if (minutes > 0 || hours > 0) { // Menit tetap tampil jika jam > 0
                countdownText += minutes + " menit ";
            }

            // Tampilkan detik, selalu tampilkan
            countdownText += seconds + " detik";

            // Update elemen dengan ID 'countdown'
            document.getElementById("countdown").innerHTML = countdownText;

            // Jika waktu habis
            if (distance < 0) {
                clearInterval(countdownFunction);
                document.getElementById("countdown").innerHTML = "Waktu habis";
                location.reload();
            }
        }, 1000);
    }
</script>

  </body>
</html>