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

// Fetch service fee
$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='pan_to_msme_udyam_fee'"));
$fee = $price['price'] ?? '70';

$sampleCode = ''; 
$resdata = [];

if ($_POST['pan']) {
    $pan = strtoupper(trim($_POST['pan']));
    $appliedby = $udata['phone'];

    if ($udata['balance'] >= $fee) {

        $url = "$tng_apiurl/api/msme-udyam-api/v1/pan-to-msme-udyam-verification?pan=$pan&apikey=$tng_apikey";
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 30,
            CURLOPT_TIMEOUT => 30,
            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) ?? [];
        $errore = $resdata['error'] ?? '';
        $sampleCode = $resdata['sampleCode'] ?? '';

        
        if (!empty($errore)) {
            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    text: "' . addslashes($errore) . '",
                    timer: 5000,
                    timerProgressBar: true
                }).then(() => { window.location = ""; });
            </script>';
        }
       
        elseif ((string)$sampleCode === "200" || (int)$sampleCode === 200) {
            $debit_fee = $udata['balance'] - $fee;
            $parentPhone = $udata['parent'] ?? null;

           
            addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Pan to Msme Udyam Find Verification");

          
            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 to Msme Udyam Find Verification','1','Debit')");

            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                Swal.fire({
                    icon: "success",
                    title: "Success",
                    text: "Msme Udyam details fetched successfully!",
                    timer: 3000,
                    timerProgressBar: true
                });
            </script>';
        }
        else {
            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                Swal.fire({
                    icon: "error",
                    title: "Something went wrong",
                    text: "Unable to fetch Msme Udyam details.",
                    timer: 3000,
                    timerProgressBar: true
                }).then(() => { window.location = ""; });
            </script>';
        }

    } else {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            Swal.fire({
                icon: "error",
                title: "Wallet Balance is Low!",
                text: "Please Recharge Now!",
                timer: 2000,
                timerProgressBar: true
            }).then(() => { window.location = "wallet.php"; });
        </script>';
    }
}
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="mobile-menu-overlay"></div>
        <div class="main-container">
            <div class="col-lg-12">
                <div class="card" style="margin-left: 10px; padding-left: 30px; padding-top: 12px; box-shadow: 1px 5px 5px 5px;">
                    <div class="stat-widget-two">
                        <div class="stat-content">
                            <div class="stat-text">
                                <div class="container-fluid">
                                    <div class="row">
                                        
                                        <div class="col-lg-4 col-md-6 col-sm-6">
                                            <div class="card">
                                                <div class="card-body">
                                                    <div class="alert alert-primary" role="alert">
                                                        PAN to Msme Udyam Check
                                                        <a href="" class="alert-link">Verify Msme Udyam Find using PAN</a>
                                                    </div>
                                                    <form action="" method="POST" class="row g-3">
                                                        <div class="card-body">
                                                            <div class="col-md-12">
                                                                <div class="form-group">
                                                                    <label for="pan">Enter PAN Number</label>
                                                                    <input name="pan" type="text" id="pan" maxlength="10" minlength="10" placeholder="Enter Valid PAN Number" 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>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>

                                       
                                        <?php if (!empty($resdata) && ((string)$sampleCode === "200" || (int)$sampleCode === 200)) { ?>
                                        <div class="col-lg-8 col-md-6 col-sm-6">
                                            <div class="card" style="background-color: #EAF2F8;" id="printSection">
                                                <div class="card-body">
                                                    <h5 class="mb-3">Msme Udyam Details for PAN: <?php echo htmlspecialchars($pan); ?></h5>
                                                    <table class="table table-bordered table-striped">
                                                        <tbody>
                                                            <tr>
                                                                <th>PAN Number</th>
                                                                <td><?php echo htmlspecialchars($resdata['pan']); ?></td>
                                                            </tr>
                                                            <tr>
                                                                <th>Msme Udyam Number</th>
                                                                <td><?php echo htmlspecialchars($resdata['data']['udyam_number']); ?></td>
                                                            </tr>
                                                            <tr>
                                                                <th>Message</th>
                                                                <td><?php echo htmlspecialchars($resdata['message']); ?></td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                    <div class="text-end mt-3">
                                                        <button class="btn btn-primary" onclick="printDiv('printSection')">
                                                            <i class="fa fa-print"></i> Print / Save PDF
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php } ?>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <br><br><br><br>
            </div>
        </div>
    </div>
</div>

<script>
function printDiv(divId) {
    var printContents = document.getElementById(divId).innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>

<?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>
