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


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

$resdata = '';
$sampleCode = '';

if ($_POST['udyam_number']) {
    $udyam_number = strtoupper(trim($_POST['udyam_number']));
    $appliedby = $udata['phone'];
    $debit_fee =  $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {
        $url = "$tng_apiurl/api/msme-udyam-api/v1/msme-udyam-to-premium-details-verification?udyam_number=$udyam_number&apikey=$tng_apikey";
        $curl = curl_init();
        curl_setopt_array($curl, array(
            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 ($errore) {
            echo '
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                $(function(){
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: "' . $errore . '",
                        timer: 5000,
                        timerProgressBar: true
                    });
                    setTimeout(() => { window.location = ""; }, 5000);
                });
            </script>';
        }
       
        elseif ((string)$sampleCode === "200" || (int)$sampleCode === 200) {
            $debit_fee = $udata['balance'] - $fee;
            $parentPhone = $udata['parent'] ?? null;
            addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Udyam Number 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','Udyam Number to Msme Udyam Find Verification','1','Debit')");
        }
    } else {
        echo '
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            $(function(){
                Swal.fire({
                    icon: "error",
                    title: "Wallet Balance is Low!",
                    text: "Please Recharge Now!",
                    timer: 2000,
                    timerProgressBar: true
                });
                setTimeout(() => { window.location = "wallet.php"; }, 1200);
            });
        </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">
                                        <!-- Form Section -->
                                        <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">
                                                        Udyam Number to MSME Udyam Check
                                                        <a href="" class="alert-link">Verify MSME Udyam using Udyam Number</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="udyam_number">Enter Udyam Number</label>
                                                                    <input name="udyam_number" type="text" id="udyam_number" maxlength="20" placeholder="Enter Valid Udyam 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 ($sampleCode == 200) { ?>
    <div class="col-lg-10 col-md-10 col-sm-12">
        <div class="card shadow" style="background-color: #EAF2F8;" id="printSection">
            <div class="card-body">
                <h4 class="mb-3 text-center text-primary">
                    MSME Udyam Details for PAN: <?php echo htmlspecialchars($pan); ?>
                </h4>

               
                <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['udyam_number']); ?></td></tr>
                        <tr><th>Message</th><td><?php echo htmlspecialchars($resdata['message']); ?></td></tr>
                    </tbody>
                </table>

              
                <h5 class="mt-4 text-primary">Enterprise Information</h5>
                <table class="table table-bordered table-sm">
                    <tbody>
                        <?php foreach ($resdata['enterprise_data'] as $key => $value) { ?>
                            <tr>
                                <th><?php echo ucwords(str_replace("_", " ", $key)); ?></th>
                                <td><?php echo htmlspecialchars($value); ?></td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>

                
                <?php if (!empty($resdata['enterprise_type_data'])): ?>
                <h5 class="mt-4 text-primary">Enterprise Type</h5>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>#</th><th>Enterprise Type</th><th>Classification Year</th><th>Classification Date</th></tr></thead>
                    <tbody>
                        <?php $i=1; foreach ($resdata['enterprise_type_data'] as $et) { ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <td><?php echo htmlspecialchars($et['enterprise_type']); ?></td>
                            <td><?php echo htmlspecialchars($et['classification_year']); ?></td>
                            <td><?php echo htmlspecialchars($et['classification_date']); ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
                <?php endif; ?>

               
                <?php if (!empty($resdata['nic_data_list'])): ?>
                <h5 class="mt-4 text-primary">NIC Details</h5>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>#</th><th>NIC 2 Digit</th><th>NIC 4 Digit</th><th>NIC 5 Digit</th><th>Activity Type</th><th>Date</th></tr></thead>
                    <tbody>
                        <?php $j=1; foreach ($resdata['nic_data_list'] as $nic) { ?>
                        <tr>
                            <td><?php echo $j++; ?></td>
                            <td><?php echo htmlspecialchars($nic['nic_2_digit']); ?></td>
                            <td><?php echo htmlspecialchars($nic['nic_4_digit']); ?></td>
                            <td><?php echo htmlspecialchars($nic['nic_5_digit']); ?></td>
                            <td><?php echo htmlspecialchars($nic['activity_type']); ?></td>
                            <td><?php echo htmlspecialchars($nic['date']); ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
                <?php endif; ?>

              
                <?php if (!empty($resdata['enterprise_units'])): ?>
                <h5 class="mt-4 text-primary">Enterprise Units</h5>
                <table class="table table-bordered table-sm">
                    <thead><tr><th>#</th><th>Unit Name</th><th>Address</th></tr></thead>
                    <tbody>
                        <?php $k=1; foreach ($resdata['enterprise_units'] as $unit) { ?>
                        <tr>
                            <td><?php echo $k++; ?></td>
                            <td><?php echo htmlspecialchars($unit['name']); ?></td>
                            <td><?php echo htmlspecialchars($unit['address']); ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
                <?php endif; ?>

                
                <?php if (!empty($resdata['pdf'])): 
                    $pdfBase64 = preg_replace('/^data:application\/pdf;base64,/', '', $resdata['pdf']);
                    $pdfDecoded = base64_decode($pdfBase64);
                    $pdfEncodedForUrl = "data:application/pdf;base64," . base64_encode($pdfDecoded);
                ?>
                    <div class="mt-4 text-center">
                        <a href="<?php echo $pdfEncodedForUrl; ?>" download="udyam_<?php echo $pan; ?>.pdf" class="btn btn-success">
                            <i class="fa fa-download"></i> Download Udyam PDF
                        </a>
                    </div>
                    <div class="mt-3">
                        <iframe src="<?php echo $pdfEncodedForUrl; ?>" width="100%" height="600px"></iframe>
                    </div>
                <?php endif; ?>

                
                <div class="text-end mt-4">
                    <button class="btn btn-primary" onclick="printDiv('printSection')">
                        <i class="fa fa-print"></i> Print / Save
                    </button>
                </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 } ?>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </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>
