<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
?>

<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">

        <!-- Back Button -->
        <div class="d-flex align-items-center justify-content-between mb-3">
          <a href="javascript:void(0);" onclick="window.history.back();" 
             class="btn btn-outline-primary rounded-pill px-4 py-2 fw-semibold">
            <i class="bi bi-arrow-left-circle me-2"></i> Go Back
          </a>
          <h5 class="mb-0 fw-bold text-primary">💰 All Voter OTP PDF History</h5>
        </div>
        <hr>

        <!-- CHECK STATUS BUTTON -->
        <div class="text-end mb-3">
            <a href="?check_status=1" class="btn btn-primary rounded-pill px-4 fw-semibold">
                🔄 Check Status
            </a>
        </div>

        <?php
        if (isset($_GET['check_status'])) {

            if ($udata['type'] == 'admin') {
                $pend = mysqli_query($tng_conn, "SELECT * FROM voter_pdf WHERE status='Pending'");
            } else {
                $pend = mysqli_query($tng_conn, "SELECT * FROM voter_pdf WHERE username='".$udata['phone']."' AND status='Pending'");
            }

            if (mysqli_num_rows($pend) > 0) {

                while ($p = mysqli_fetch_assoc($pend)) {

                    $app_no = $p['application_no'];
                    $log_id = $p['id'];
                    $phone  = $p['username'];
                    $fee    = $udata['voter_to_org_pdf_without_otp_a'] ?? 50; 


                    // 🔥 API CALL (your actual function)
                    $json = voter_pdf_status_api(["application_no" => $app_no]);

                    // SUCCESS
                    if ($json['Message'] == "Success" && $json['sampleCode'] == "200") {

                        $pdf = $json["Voter_Pdf"];

                        mysqli_query($tng_conn, "
                            UPDATE voter_pdf 
                            SET status='Success', 
                                pdf='".mysqli_real_escape_string($tng_conn, $pdf)."',
                                remark='PDF Ready 🎉'
                            WHERE id=$log_id
                        ");
                    }

                    // REFUND
                    else if ($json['Message'] == "Refunded" && $json['sampleCode'] == "422") {

                        mysqli_query($tng_conn, "UPDATE users SET balance = balance + $fee WHERE phone='$phone'");

                        mysqli_query($tng_conn, "
                            UPDATE voter_pdf 
                            SET status='Refunded', 
                                remark='Refunded ₹$fee ❌' 
                            WHERE id=$log_id
                        ");
                    }
                }
            }

            echo "<script>window.location='voter_otp_pdf_list.php';</script>";
            exit;
        }

        // NORMAL FETCH
        if ($udata['type'] == 'admin') {
            $res = mysqli_query($tng_conn, "SELECT * FROM voter_pdf ORDER BY id DESC");
        } else {
            $res = mysqli_query($tng_conn, "SELECT * FROM voter_pdf WHERE username='".$udata['phone']."' ORDER BY id DESC");
        }
        ?>

        <!-- TABLE -->
        <div class="table-responsive">
          <table id="walletTable" class="table table-hover table-striped align-middle text-center">
            <thead class="table-dark">
              <tr>
                <th>SL.</th>
                <th>Name</th>
                <th>Voter No</th>
                <th>Apply Date</th>
                <th>Status</th>
                <th>Remark</th>
                <th>Action</th>
              </tr>
            </thead>

            <tbody>
              <?php
              $x = 0;

              if (mysqli_num_rows($res) > 0) {
                  while ($data = mysqli_fetch_assoc($res)) {
                      $x++;
                      ?>
                      <tr>
                        <td><?= $x ?></td>
                        <td><?= htmlspecialchars($data['name']) ?></td>
                        <td><?= htmlspecialchars($data['aadhar']) ?></td>
                        <td><?= strtoupper($data['date']) ?></td>

                        <td>
                            <?php 
                            if ($data['status']=="Success") {
                                echo "<span class='badge bg-success'>Success</span>";
                            } elseif ($data['status']=="Refunded") {
                                echo "<span class='badge bg-danger'>Refunded</span>";
                            } else {
                                echo "<span class='badge bg-warning text-dark'>Pending</span>";
                            }
                            ?>
                        </td>

                        <td><?= $data['remark'] ?></td>

                        <td>
                            <?php if ($data['status']=="Success") { ?>
                                <a href="<?= $data['pdf'] ?>" 
                                   download="Voter_<?= $data['aadhar'] ?>.pdf"
                                   class="btn btn-success btn-sm">
                                  Download
                                </a>
                            <?php } else { ?>
                                <button class="btn btn-secondary btn-sm" disabled>No PDF</button>
                            <?php } ?>
                        </td>
                      </tr>
                      <?php
                  }
              } else {
                  echo "
                  <tr>
                    <td>–</td>
                    <td>No Record</td>
                    <td>–</td>
                    <td>–</td>
                    <td><span class='badge bg-secondary'>No Data</span></td>
                    <td>No record found ❗</td>
                    <td>–</td>
                  </tr>";
              }
              ?>
            </tbody>

          </table>
        </div>

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

<?php include('../template/tngweb/footer.php'); ?>

<!-- Scripts -->
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>

<script>
$(document).ready(function () {
    $('#walletTable').DataTable({
        lengthChange: false,
        pageLength: 10,
        order: [[0, "desc"]],
        buttons: ['copy', 'excel', 'pdf', 'print'],
        dom: '<"d-flex justify-content-between align-items-center mb-3"Bf>rt<"d-flex justify-content-between align-items-center"ip>'
    });
});
</script>

<style>
.table thead th { font-weight: 600; }
.table tbody tr:hover { background: #f5f8ff; transition: 0.2s; }
.card { border-radius: 15px; }
.btn-outline-primary:hover { background-color: #0055ff; color: #fff; }
.badge { padding: 6px 10px; }
</style>
