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

// Fetch fee from database
$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='rtps_pdf_fee'"));
$fee = $price['price'];
$resdata = []; 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['appRefNum'], $_POST['name'])) {
    $appRefNum = $_POST['appRefNum'];
    $name = ucwords(trim($_POST['name']));
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {
        
        $url = "$tng_apiurl/rtps_pdf_verification?appRefNum=" . urlencode($appRefNum) . "&name=" . urlencode($name) . "&apikey=" . urlencode($tng_apikey);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $resdata = json_decode($response, true) ?? [];

        $appRefNum = $resdata['appRefNum'] ?? '';
        $name = $resdata['name'] ?? '';
        $pdf = $resdata['pdf'] ?? '';
        $statusCode = $resdata['sampleCode'] ?? '';
        $errore = $resdata['error'] ?? '';

        if ($errore) {
            echo "<script>$(function(){ Swal.fire('$errore', 'Something went wrong.', 'error') }); setTimeout(() => { window.location=''; }, 5000);</script>";
        } elseif ($statusCode === "200") {
         
             date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
            $parentPhone = $udata['parent'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Bihar  Rtps Card PDF Verification");
           $database = mysqli_query($ahk_conn, "INSERT INTO `rtps_pdf`(`name`, `username`, `aadhar`, `pdf`, `date`) VALUES ('{$resdata['name']}','{$udata['phone']}','{$resdata['appRefNum']}','{$resdata['pdf']}','$timestamp')");
               mysqli_query($ahk_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $updatehistory = mysqli_query($ahk_conn, "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('$appliedby','$fee','$debit_fee','Bihar  Rtps Card PDF Verification','1','Debit')");
        
          
        }
    } else {
        echo "<script>$(function(){ Swal.fire('Wallet Balance is Low!', 'Please Recharge Now!', 'error') }); setTimeout(() => { window.location='wallet.php'; }, 1200);</script>";
    }
}
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="main-container">
            <div class="col-lg-6">
                <div class="card" style="margin-left: 10px; padding-left: 30px; padding-top: 12px; box-shadow: 1px 5px 5px 5px;">
                    <div class="card-body">
                        <div class="alert alert-danger" role="alert">
                            BIHAR RTPS CERTIFICATE PDF
                        </div>
                        <form action="" method="POST" class="row g-3">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="appRefNum">Enter Application Number</label>
                                    <input name="appRefNum" type="text" id="appRefNum" maxlength="20" placeholder="BCCCO/2025/XXXXX" class="form-control" required>
                                </div>
                                <hr>
                                <div class="form-group">
                                    <label for="name">Enter Full Name</label>
                                    <input name="name" type="text" id="name" maxlength="50" minlength="4" placeholder="Enter Full Name" class="form-control" required>
                                </div>
                                <hr>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                    </div>
                                    <div class="col-md-6 text-end">
                                        <button class="btn btn-success" name="submit" id="submit"><i class="fa fa-check-circle"></i> Submit</button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <?php if (!empty($resdata) && $resdata['sampleCode'] === "200") { ?>
                            <div class="col-lg-12 mt-4">
                                <div class="card" style="background-color: #FCF3CF;" id="printSection">
                                    <div class="card-body">
                                        <h5>
Bihar Rtps Pdf
  <a href="Bihar_Rtps_Certificate_pdf_list.php" style="font-size:14px; margin-left:10px; text-decoration:none; color:blue;">
    (View List)
  </a>
</h5>
                                        <table class="table table-bordered table-striped">
                                            <tbody>
                                                <tr>
                                                    <th>Application Number</th>
                                                    <td><?php echo htmlspecialchars($appRefNum); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Full Name</th>
                                                    <td><?php echo htmlspecialchars($name); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>PDF</th>
                                                    <td>
                                                        <a href="<?php echo htmlspecialchars($pdf); ?>" download="<?php echo htmlspecialchars($appRefNum); ?>.pdf" class="btn btn-sm btn-success">Download PDF</a>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                </div>
                <br><br><br><br>
            </div>
        </div>
    </div>
</div>

<?php include('../template/ahkweb/footer.php'); ?>
<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>
</html>
