<?php
include('../includes/session.php');
include('../includes/config.php');

if (isset($_GET['action']) && $_GET['action'] == 'update' && isset($_GET['orderid'])) {
    header('Content-Type: application/json');
    $order_id = mysqli_real_escape_string($tng_conn, $_GET['orderid']);
    $api_key = "YOUR_API_KEY"; 

    $url = "https://dashbood.brotool.online/api/pan_find/aadhar_to_pan_find_status.php?api_key=$api_key&api_orderid=$order_id";
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch); curl_close($ch);
    $api_res = json_decode($res, true);
    
    if (isset($api_res['live_status'])) {
        $l_status = $api_res['live_status']; 
        $pan_val = $api_res['pan_number'] ?? '';
        $remark = mysqli_real_escape_string($tng_conn, $api_res['responce'] ?? 'Processed');

        $check_db = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT status, username FROM pan_find_requests WHERE order_id='$order_id'"));
        if($check_db['status'] != 'Pending') { echo json_encode(['status' => 'info', 'msg' => 'Already Updated']); exit; }

        if ($l_status == 'Successfully' || $l_status == 'Success') {
            mysqli_query($tng_conn, "UPDATE pan_find_requests SET status = 'Success', pan_card_no = '$pan_val', admin_remark = '$remark' WHERE order_id = '$order_id'");
            echo json_encode(['status' => 'success', 'msg' => $remark, 'pan' => $pan_val]);
        } 
        elseif ($l_status == 'Rejected') {
            $user_phone = $check_db['username'];
            $fee_refund = floatval($udata['tng_pan_panfind']);
            mysqli_begin_transaction($tng_conn);
            try {
                mysqli_query($tng_conn, "UPDATE pan_find_requests SET status = 'Rejected', pan_card_no = 'REJECTED', admin_remark = '$remark' WHERE order_id = '$order_id'");
                mysqli_query($tng_conn, "UPDATE users SET balance = balance + $fee_refund WHERE phone='$user_phone'");
                mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, purpose, status, type) VALUES ('$user_phone', '$fee_refund', 'Refund: PAN Find Rejected', '1', 'Credit')");
                mysqli_commit($tng_conn);
                echo json_encode(['status' => 'error', 'msg' => 'Rejected: ' . $remark]);
            } catch (Exception $e) { mysqli_rollback($tng_conn); }
        } else {
            echo json_encode(['status' => 'info', 'msg' => $remark]);
        }
    }
    exit;
}
include('../template/tngweb/header.php'); 
$user = $udata['phone'];
$res = mysqli_query($tng_conn, "SELECT * FROM pan_find_requests WHERE username='$user' ORDER BY id DESC");
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-dark text-white py-3"><h5 class="mb-0 text-center text-uppercase">PAN Find History</h5></div>
            <div class="card-body">
                <div class="table-responsive">
                     <table class="table table-bordered text-center align-middle">
                         <thead class="table-light">
                             <tr>
                                 <th>Date</th>
                                 <th>Aadhar</th>
                                 <th>PAN Result</th>
                                 <th>Remark/Message</th> <th>Status</th>
                                 <th>Action</th>
                             </tr>
                         </thead>
                         <tbody>
                             <?php while($row = mysqli_fetch_assoc($res)): ?>
                             <tr>
                                 <td><small><?php echo $row['date_time']; ?></small></td>
                                 <td><?php echo $row['aadhar_no']; ?></td>
                                 <td id="pan-<?php echo $row['order_id']; ?>"><b><?php echo ($row['pan_card_no'] != 'Pending') ? $row['pan_card_no'] : '---'; ?></b></td>
                
                                 <td id="remark-<?php echo $row['order_id']; ?>">
                                     <small class="text-muted"><?php echo $row['admin_remark'] ?? 'Waiting...'; ?></small>
                                 </td>

                                 <td><span class="badge <?php echo ($row['status'] == 'Success') ? 'bg-success' : (($row['status'] == 'Rejected') ? 'bg-danger' : 'bg-warning'); ?>" id="status-<?php echo $row['order_id']; ?>"><?php echo $row['status']; ?></span></td>
                
                                 <td id="action-<?php echo $row['order_id']; ?>">
                                     <?php if ($row['status'] == 'Pending'): ?>
                                         <button class="btn btn-sm btn-primary check-btn" data-id="<?php echo $row['order_id']; ?>">Check Status</button>
                                     <?php else: ?>
                                         <span class="text-muted small">Updated</span>
                                     <?php endif; ?>
                                 </td>
                             </tr>
                             <?php endwhile; ?>
                         </tbody>
                     </table>
                 </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$('.check-btn').on('click', function() {
    let orderid = $(this).data('id');
    Swal.fire({ title: 'Checking...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
    $.get(window.location.href, { action: 'update', orderid: orderid }, function(res) {
        if(res.status == 'success') {
            Swal.fire('Success', res.msg, 'success');
            $('#pan-'+orderid).html('<b>'+res.pan+'</b>');
            $('#status-'+orderid).removeClass('bg-warning').addClass('bg-success').text('Success');
            $('#action-'+orderid).html('<span class="text-muted small">Updated</span>');
        } else if(res.status == 'error') {
            Swal.fire('Rejected', res.msg, 'error');
            $('#status-'+orderid).removeClass('bg-warning').addClass('bg-danger').text('Rejected');
            $('#action-'+orderid).html('<span class="text-muted small">Refunded</span>');
        } else { Swal.fire('Update', res.msg, 'info'); }
    });
});
</script>
<?php include('../template/tngweb/footer.php'); ?>