<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');
date_default_timezone_set('Asia/Kolkata');
$resdata = []; // Initialize for use in HTML
if (isset($_POST['check']) && $_POST['check'] === "aadhaar") {
    $aadhaar_check = mysqli_real_escape_string($ahk_conn, $_POST['aadhaar_no']);
    // $url = file_get_contents("https://" . htmlspecialchars($flexsecureapiurl) . "/api/v2/Pan_find.php?aadhaarNum=$aadhaar_check");
    $result = json_decode($url, true);

    if ($result['status'] === 'success') {
        if ($result['code'] === '200') {
            echo '<script>$(function(){ Swal.fire("We Found Linked Data", "' . htmlspecialchars($result['message']) . '", "success") });</script>';
        } elseif ($result['code'] === '422') {
            echo '<script>$(function(){ Swal.fire("Aadhaar Not Linked To Any PAN", "' . htmlspecialchars($result['message']) . '", "error") });</script>';
        } elseif ($result['code'] === '404') {
            echo '<script>$(function(){ Swal.fire("Invalid Aadhaar Number", "' . htmlspecialchars($result['message']) . '", "warning") });</script>';
        }
    }

    if (!empty($_POST['aadhaar_no'])) {
        $aadhaar = mysqli_real_escape_string($ahk_conn, $_POST['aadhaar_no']);
        $application_no = "INSTANT" . rand(100000, 999999);
        $username = $udata['phone'];
        $appliedby = $udata['phone'];

        $price_query = mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='Aadhaar_To_Pan_find'");
        $price = mysqli_fetch_assoc($price_query);
        $fee = $price['price'];
        $wallet_amount = $udata['balance'];
        $debit_fee = $wallet_amount - $fee;

        if ($wallet_amount >= $fee) {
            $url = "https://" . htmlspecialchars($flexsecureapiurl) . "/serviceApi/FlexSecureV1/Pan/pan_Find_link.php?apiKey=" . urlencode($flexsecure_key) . "&aadhaar_no=" . urlencode($aadhaar);

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => "GET",
            ]);
            $response = curl_exec($curl);
            curl_close($curl);

            $resdata = json_decode($response, true);

            if ($resdata['status'] === true && $resdata['statusCode'] == 100) {
                $pan = $resdata['pan_no'];
                $name = $resdata['name'];
                $dob = $resdata['dob'];
                $message = $resdata['message'];
                $message_code = $resdata['statusCode'];

                $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 Number Find', '1', 'Debit')");

                if ($debit) {
                    mysqli_query($ahk_conn, "INSERT INTO instantpan_find (application_no, username, aadhaar_no, pan_no, clint_id, status, status_code, fee, old_balance, new_balance, message) VALUES ('$application_no', '$username', '$aadhaar', '$pan', '$clint', '$message_code', '$response', '{$udata['pan_no_fee']}', '$wallet_amount', '$debit_fee', '$message')");
                    echo "<script>$(function(){ Swal.fire('PAN No for $aadhaar is $pan', '$application_no', 'success') });</script>";
                } else {
                    echo "<script>$(function(){ Swal.fire('Balance Debited but Data Not Inserted', 'DATA INSERT ERROR', 'warning') }); setTimeout(() => { window.location=''; }, 1200);</script>";
                }
            } else {
                $message = isset($resdata['message']) ? $resdata['message'] : "SERVER DOWN PLEASE TRY AFTER SOMETIME";
                echo "<script>$(function(){ Swal.fire('Error', '" . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . "', 'error') });</script>";
            }
        } else {
            echo "<script>$(function(){ Swal.fire('Wallet Balance is Low!', 'Please Recharge Now!', 'error') }); setTimeout(() => { window.location='wallet.php'; }, 1200);</script>";
        }
    }
}
?>

<!-- HTML UI -->
<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb with Action Buttons -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">Services</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted" aria-current="page">Pan Find Service</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="instant_pan_list" class="btn btn-success">
                    <i class="bi bi-list-ul me-1"></i> Pan Find List
                </a>
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
				<!--end breadcrumb-->
			 <div class="container-fluid pt-4 px-4">
                <div class="row">
                    <!-- Left Side: Form Section -->
                    <div class="col-lg-5 mb-4">
                        <div class="card">
                            <div class="card-body">
                               <h3 class="card-title text-dark text-center"><strong>Aadhaar No To Get Pan No Instant</strong></h3>
                            <a href="pan_details_verify" class="btn btn-dark w-100 mb-3">PAN Number To PAN Details Find Click Here</a>
                            <form method="POST">
                                <div class="form-group mb-3">
                                    <label for="aadhaar_no">Aadhaar Number <span class="text-danger">*</span></label>
                                    <input name="aadhaar_no" type="text" id="aadhaar_no" placeholder="Enter 12 Digits Aadhaar Number" class="form-control" required>
                                    <input type="hidden" name="check" value="aadhaar">
                                </div>
                                <div class="text-center">
                                    <button type="submit" class="btn btn-primary px-5">Verify Now</button>
                                </div>
                            </form>
                            <div class="text-center mt-3">
                                <div class="fee-container">
                                  <h5 class="text-warning">Application Fee: 
            <?php  
										$price = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT price FROM pricing WHERE service_name='Aadhaar_To_Pan_find'")); 
										echo "₹" .$price['price'];
										?>
        </h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

             <!-- Right Side: PAN Details -->
<div class="col-lg-6">
    <?php if (!empty($resdata) && $resdata['statusCode'] == 100): ?>
        <div class="card" style="background-color: #f8f9fa;" id="printSection">
            <div class="card-body">
                <h5 class="mb-3">PAN Details</h5>
                <table class="table table-bordered table-striped">
                    <tbody>
                        <?php if (!empty($aadhaar)): ?>
                            <tr><th>Aadhaar Number</th><td><?= htmlspecialchars($aadhaar); ?></td></tr>
                        <?php endif; ?>

                        <?php if (!empty($resdata['name'])): ?>
                            <tr><th>Name</th><td><?= htmlspecialchars($resdata['name']); ?></td></tr>
                        <?php endif; ?>

                        <?php if (!empty($resdata['pan_no'])): ?>
                            <tr><th>PAN Number</th><td><?= htmlspecialchars($resdata['pan_no']); ?></td></tr>
                        <?php endif; ?>

                        <?php if (!empty($resdata['dob'])): ?>
                            <tr><th>Date of Birth</th><td><?= htmlspecialchars($resdata['dob']); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <div class="text-end">
                    <button class="btn btn-primary" onclick="printBill()">🖨️ Print</button>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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

<!-- Styles -->
<style>
    .fee-container {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        padding: 10px 15px;
        max-width: 300px;
        margin: 10px auto;
    }
    .fee-container h5 {
        color: #ff9800;
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }
</style>

<!-- Scripts -->
<script>
    function printBill() {
        var printContents = document.getElementById('printSection').innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    }
</script>

		
		<!--end page wrapper -->
		<?php 
		include('footer.php');
		?>
	<!-- Bootstrap JS -->
	

	<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<!-- <script src="../template/ahkweb/assets/js/jquery.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>
	<!--app JS-->
	<script src="../template/ahkweb/assets/js/app.js"></script>
</body>

<script>
	$(document).ready(function() {
	
	$('#eid').inputmask();
	$('#date').inputmask();
	$('#timea').inputmask("hh:mm:ss", {
        placeholder: "00:00:00", 
        insertMode: false, 
        showMaskOnHover: false,
        hourFormat: 12
      });
	});
</script>
</html>