<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');
echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
$price = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT * FROM pricing WHERE service_name='Pan_To_Aadhar_Find_a' "));
$fee = $price['price'] ?? '150';
$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($ahk_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) {
        $applyUrl = "$tng_apiurl/api/v2/Pan2Uid/Pan2Uid_Apply?apikey=$tng_apikey&pan=$PanNo";

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $applyUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        $resdata = json_decode($response, true);
        $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($ahk_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($ahk_conn, $appliedby, $fee, $parentPhone, "Pan To Aadhar Manual Verification");
                $debit = mysqli_query($ahk_conn, "UPDATE users SET balance = balance - $fee WHERE phone = '$appliedby'");
                mysqli_query($ahk_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($ahk_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 {
            $checkUrl = "$tng_apiurl/api/v2/Pan2Uid/CheckStatus?apikey=$tng_apikey&pan=$checkPan";

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $checkUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            $response = curl_exec($curl);
            curl_close($curl);

            $data = json_decode($response, true);
            $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($ahk_conn, "SELECT balance FROM users WHERE phone = '$username'"));
                $newBalance = $udata['balance'] + $fee;

                $refund = mysqli_query($ahk_conn, "UPDATE users SET balance = balance + $fee WHERE phone = '$username'");
                $log = mysqli_query($ahk_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$username', '$fee', '$newBalance', 'PAN UID Find Refund', '1', 'Credit')");
                $updateStatus = mysqli_query($ahk_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($ahk_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($ahk_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>

        <!-- HISTORY SECTION -->
        <div class="row">
            <div class="col-xl-12">
                <div class="card">
                    <div class="card-body">
                       <div class="table-responsive mt-3">
                       <table id="historyTable" class="table table-bordered table-striped display nowrap" style="width:100%">
                           <thead>
                               <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>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/vfs_fonts.js"></script>
<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 src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
<?php include('../template/ahkweb/footer.php'); ?>