<?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 & Title -->
        <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">📱 Voter Mobile Link History</h5>
        </div>
        <hr>

        <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
        $uid = $udata['phone'];

        if (isset($_GET['check_status'])) {
            $pend = mysqli_query($tng_conn, "SELECT * FROM voter_mobile_link_log WHERE phone='$uid' AND status='Pending'");
            if (mysqli_num_rows($pend) > 0) {
                while ($p = mysqli_fetch_assoc($pend)) {
                    $app_no = $p['application'];
                    $fee    = $p['fee'];
                    $phone  = $p['phone'];
                    $log_id = $p['id'];

                    $json = voter_mobile_link_status_verification_run(['application_no' => $app_no]);

                    if ($json['Message']=="Success" && $json['sampleCode']=="200") {
                        mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$phone'");
                        $bal = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone='$phone'"))['balance'];

                        mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type)
                            VALUES ('$phone','$fee','$bal','Voter Mobile Link Without OTP','1','Debit')");

                        mysqli_query($tng_conn, "UPDATE voter_mobile_link_log SET status='Success', remark='Mobile linking Success ✅' WHERE id=$log_id");
                    }
                    else if ($json['Message']=="Refunded" && $json['sampleCode']=="422") {
                        mysqli_query($tng_conn, "UPDATE users SET balance = balance + $fee WHERE phone='$phone'");
                        $bal = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone='$phone'"))['balance'];

                        mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type)
                            VALUES ('$phone','$fee','$bal','Voter Mobile Link Refund ❌','1','Refund')");

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

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

        $res = mysqli_query($tng_conn, "SELECT * FROM voter_mobile_link_log WHERE phone='$uid' 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>EPIC</th>
                <th>Mobile</th>
                <th>Date</th>
                <th>Status</th>
                <th>Remark</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $x=0;

              if (mysqli_num_rows($res) > 0) {
                  while ($data = mysqli_fetch_assoc($res)) {
                      $x++;
                      echo "<tr>";
                      echo "<td>$x</td>";
                      echo "<td>" . strtoupper($data['fullname']) . "</td>";
                      echo "<td>" . strtoupper($data['epic']) . "</td>";
                      echo "<td>" . strtoupper($data['mobile']) . "</td>";
                      echo "<td>" . strtoupper($data['created_at']) . "</td>";

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

                      echo "<td>" . $data['remark'] . "</td>";
                      echo "</tr>";
                  }
              } else {
                  // 🔥 FIXED → Always print EXACT 7 columns to avoid DataTables error
                  echo "
                  <tr>
                    <td>–</td>
                    <td>No Record</td>
                    <td>–</td>
                    <td>–</td>
                    <td>–</td>
                    <td><span class='badge bg-secondary'>No Data</span></td>
                    <td>No record found ❗</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 {
    vertical-align: middle;
    font-weight: 600;
    letter-spacing: 0.3px;
  }
  .table tbody tr:hover {
    background: #f5f8ff;
    transition: 0.2s ease;
  }
  .card { background: #fff; border-radius: 15px; }
  .btn-outline-primary { border-color: #0055ff; color: #0055ff; }
  .btn-outline-primary:hover { background-color: #0055ff; color: #fff; }
  .badge { font-size: 0.8rem; padding: 6px 10px; }
</style>
