<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$fee    = $udata['Pan_To_Aadhar_Find_a'];
checkServiceStatus($udata, 'Pan_To_Aadhar_Find_a_status');
echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
$appliedby = $udata['phone'];


if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['PanNo'])) {
    $PanNo = strtoupper(trim($_POST['PanNo']));
    $wallet_balance = $udata['balance'];
    $debit_fee = $wallet_balance - $fee;

    $exists = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT id FROM pan2uid_find WHERE panNo='$PanNo' AND username='$appliedby' AND status='Pending'"));
    if ($exists) {
        echo "<script>Swal.fire('Pending Request', 'This PAN already has a pending request.', 'info');</script>";
        return;
    }

  
    if ($wallet_balance >= $fee) {
        $request = [
        'pan' => $PanNo,
        ];

        $resdata = Pan2Uid_Apply_verification_api_run($request);
        $message = $resdata['message'] ?? ($resdata['error'] ?? 'Server Error');
        $sampleCode = $resdata['sampleCode'] ?? '';
        $pan = $resdata['pan'] ?? '';

        if ($sampleCode == "200") {
            $time = date("Y-m-d H:i:s");
            $insert = mysqli_query($tng_conn, "INSERT INTO pan2uid_find(panNo, status, username, date) VALUES ('$pan', 'Pending', '$appliedby', '$time')");

            if ($insert) {
                // Deduct wallet and log
                $parentPhone = $udata['parent'] ?? null;
        addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Pan To Aadhar Manual Verification");
                $debit = mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone = '$appliedby'");
                mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$appliedby','$fee','$debit_fee','PAN UID Find','1','Debit')");
                echo "<script>Swal.fire('$message', 'Success', 'success');</script>";
            } else {
                echo "<script>Swal.fire('Insert Failed', 'Database error.', 'error');</script>";
            }
        } else {
            echo "<script>Swal.fire('API Error', '$message', 'error');</script>";
        }
    } else {
        echo "<script>Swal.fire('Low Balance', 'Recharge your wallet.', 'error'); setTimeout(() => { window.location = 'wallet.php'; }, 2000);</script>";
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['check_status_id'])) {
    $rowId = intval($_POST['check_status_id']);
    $rowData = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT * FROM pan2uid_find WHERE id='$rowId' LIMIT 1"));

    if (!$rowData) {
        echo "<script>Swal.fire('Error', 'Record not found.', 'error');</script>";
    } else {
        $checkPan = $rowData['panNo'];
        $username = $rowData['username'];
        $currentStatus = $rowData['status'];

        if ($currentStatus === 'Refunded') {
            echo "<script>Swal.fire('Already Refunded', 'This request was already refunded.', 'info');</script>";
        } else {
            $request = [
        'pan' => $checkPan,
        ];

        $data = Pan2Uid_CheckStatus_verification_api_run($request);
            $statusCode = $data['sampleCode'] ?? '';
            $statusMessage = strtolower($data['Message'] ?? '');
            $uid = $data['aadhar'] ?? '';
            $name = $data['fullname'] ?? '';
            $dob = $data['dob'] ?? '';
            $gender = $data['gender'] ?? '';

            if ($statusMessage === 'Refunded') {
                $udata = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone = '$username'"));
                $newBalance = $udata['balance'] + $fee;

                $refund = mysqli_query($tng_conn, "UPDATE users SET balance = balance + $fee WHERE phone = '$username'");
                $log = mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$username', '$fee', '$newBalance', 'PAN UID Find Refund', '1', 'Credit')");
                $updateStatus = mysqli_query($tng_conn, "UPDATE pan2uid_find SET status='Refunded' WHERE id='$rowId'");

                if ($refund && $log && $updateStatus) {
                    echo "<script>Swal.fire('Refunded', 'Amount refunded successfully.', 'success');</script>";
                } else {
                    echo "<script>Swal.fire('Error', 'Refund failed.', 'error');</script>";
                }

            } elseif ($statusCode == '200') {
                $update = mysqli_query($tng_conn, "UPDATE pan2uid_find SET aadhaar='$uid', name='$name', dob='$dob', gender='$gender', status='completed' WHERE id='$rowId'");
                if ($update) {
                    echo "<script>Swal.fire('Success', 'Details updated successfully.', 'success');</script>";
                } else {
                    echo "<script>Swal.fire('Error', 'Database update failed.', 'error');</script>";
                }
            } else {
                $apiError = $data['error'] ?? $data['message'] ?? 'Unknown error';
                echo "<script>Swal.fire('API Error', '$apiError', 'error');</script>";
            }
        }
    }
}

$appliedby = $udata['phone'];
$resultData = mysqli_query($tng_conn, "SELECT * FROM pan2uid_find WHERE username='$appliedby' ORDER BY id DESC");
?>



<div class="page-wrapper">
    <div class="page-content">
        <div class="row mb-4">
            <div class="col-xl-4 mx-auto">
        
                <h6 class="mb-0 text-uppercase">PAN to Aadhaar Find</h6>
                <div class="card border-top border-0 border-4 border-primary">
                    <div class="card-body p-4">
                        <form method="POST">
                            <div class="form-group">
                                <label>PAN Number</label>
                                <input type="text" name="PanNo" id="PanNo" class="form-control" placeholder="Enter PAN Number" minlength="10" maxlength="10" required />
                            </div>
                            <br>
                            <button type="submit" name="submit_pan" class="btn btn-primary">Submit</button>
                        </form>
                        <p><strong>Note:</strong> Wallet ₹<?php echo $fee; ?> will be deducted per request.</p>
                    </div>
                </div>
            </div>
        </div>

       
        <!-- 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 Reacharge History</h5>
        </div>
        <hr>  

        <div class="table-responsive">
          <table id="walletTable" class="table table-hover table-striped align-middle text-center">
            <thead class="table-dark">
              <tr>
                                   <th>#</th>
                                   <th>PAN</th>
                                   <th>Aadhaar</th>
                                   <th>Name</th>
                                   <th>DOB</th>
                                   <th>Gender</th>
                                   <th>Status</th>
                                   <th>Date</th>
                                   <th>Action</th>
                               </tr>
                           </thead>
                           <tbody>
                <?php 
                $count = 1;
                if (mysqli_num_rows($resultData) > 0) {
                    while ($row = mysqli_fetch_assoc($resultData)) {
                    ?>
                    <tr>
                        <td><?php echo $count; ?></td>
                        <td><?php echo $row['panNo']; ?></td>
                        <td><?php echo $row['aadhaar']; ?></td>
                        <td><?php echo $row['name']; ?></td>
                        <td><?php echo $row['dob']; ?></td>
                        <td><?php echo $row['gender']; ?></td>
                        <td><?php echo strtoupper($row['status']); ?></td>
                        <td><?php echo $row['date']; ?></td>
                        <td>
                            <?php if ($row['status'] == 'Pending') { ?>
                                <form method="POST" style="display:inline-block;">
                                    <input type="hidden" name="check_status_id" value="<?php echo $row['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-info">Check Status</button>
                                </form>
                            <?php } elseif ($row['status'] == 'Refunded') { ?>
                                <span class="badge bg-danger"><?php echo strtoupper($row['status']); ?></span>
                            <?php } else { ?>
                                <span class="badge bg-success"><?php echo strtoupper($row['status']); ?></span>
                            <?php } ?>
                        </td>
                    </tr>
                    <?php
                    $count++;
                }
            } else {
                // echo "<tr><td colspan='9' class='text-center'>No history found.</td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
    $('#historyTable').DataTable({
        responsive: true,
        dom: 'Bfrtip', // Buttons + Search + Pagination
        buttons: [
            'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5', 'print'
        ],
        pageLength: 10,
        lengthMenu: [5, 10, 25, 50, 100],
        order: [[ 0, "desc" ]]
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const form = document.querySelector("form");
    const submitBtn = document.getElementById("submit");

    let isSubmitting = false;

    form.addEventListener("submit", function (e) {
        if (isSubmitting) {
            e.preventDefault();
            return;
        }
        isSubmitting = true;       
        submitBtn.disabled = true; 
    });
});
</script>
           
<!--end page wrapper -->

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

<!-- ✅ DataTables CDN & 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>
  /* 🌟 Stylish Table */
  .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;
  }

  .dataTables_wrapper .dataTables_filter input {
    border-radius: 8px;
    padding: 5px 10px;
  }

  .dataTables_wrapper .dataTables_paginate .paginate_button {
    border-radius: 5px;
  }

  .dataTables_wrapper .dt-buttons .btn {
    border-radius: 20px !important;
    font-size: 0.85rem;
    margin-right: 6px;
  }

  .badge {
    font-size: 0.8rem;
    padding: 6px 10px;
  }
</style>
