<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$fee    = $udata['aadhaar_otp_pdf_fee'] ?? 10;
checkServiceStatus($udata, 'aadhaar_otp_pdf_fee_status');
$appliedby = $udata['phone'];
$debit_fee = $udata['balance'] - $fee;

$responseData = [];
$otpData = []; 


if (!isset($_POST['sendotp']) && !isset($_POST['verifyotp'])) {
    $responseData = fetchAadharCaptcha();
}

// SEND OTP
if (isset($_POST['sendotp'])) {
    $aadhar = $_POST['aadhar'];
    $captcha = $_POST['captcha'];
    $captchaSID = $_POST['captchaSID'];

   $otpData = sendAadharOtp($aadhar, $captcha, $captchaSID);

    if (($otpData['sampleCode'] ?? '') != '200') {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'error', title: 'Error', text: '{$otpData['error']}', timer: 5000 });
        </script>";
    } else {
        $responseData = $otpData; // Save for form
    }
}


if (isset($_POST['verifyotp'])) {
    $aadhar = $_POST['aadhar'];
    $otp = $_POST['otp'];
    $otpTxnId = $_POST['otpTxnId'];
    $type = ($_POST['type'] === 'true') ? 'true' : 'false'; 

    if ($udata['balance'] >= $fee) {
       $resdata = verifyAadharOtpPdf($aadhar, $otp, $otpTxnId, $type);

        if (($resdata['sampleCode'] ?? '') === "200") {
          
          date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
                $parentPhone = $udata['parent'] ?? null;
        addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Aadhar Otp Pdf Verification");
           $debit = mysqli_query($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $database = mysqli_query($tng_conn, "INSERT INTO `aadhar_otp_pdf`(`name`, `username`, `aadhar`, `pdf`, `date`) VALUES ('{$resdata['eid']}','{$udata['phone']}','{$resdata['aadhar']}','{$resdata['Aadhaar_Pdf']}','$timestamp')");
             mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$appliedby','$fee','$debit_fee','Aadhaar OTP PDF Download','1','Debit')");

       echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'success', title: 'Success!', text: 'Pdf Generate Sucessfull Redirecting To List!', timer: 2000 });
            setTimeout(() => { window.location = 'aadhar_otp_pdflist.php'; }, 1200);
        </script>";

        } else {
            $errorMsg = $resdata['error'] ?? 'Unknown error';
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({ icon: 'error', title: 'Error', text: '{$errorMsg}', timer: 5000 });
            </script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'error', title: 'Wallet Balance Low!', text: 'Please Recharge Now!', timer: 2000 });
            setTimeout(() => { window.location = 'wallet.php'; }, 1200);
        </script>";
    }
}
?>

<div class="content-wrap">
    <div class="main">
        <div class="col-md-12">
            <div class="main-content">
                <div class="page-wrapper">
                    <div class="page-content">
                        <div class="mobile-menu-overlay"></div>
                        <div class="main-container">
                            <div class="col-lg-4 col-md-6 col-sm-6">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="mb-4">
        <a href="javascript:history.back()" class="back-btn">
            <i class="bi bi-arrow-left-circle"></i> Go Back
        </a>
    </div>
                                        <div class="alert alert-danger" role="alert">
                                            <a href="#" class="alert-link">Aadhaar Original PDF (All State)</a>
                                        </div>
                                        <form action="" method="POST" class="row g-3">
                                            <div class="form-group">
                                                <label>Enter Aadhaar Number</label>
                                                <input name="aadhar" type="text" class="form-control" placeholder="Enter Aadhaar Number" required value="<?php echo $_POST['aadhar'] ?? ''; ?>">
                                            </div>
                                            <hr>

                                          
                                            <?php if (!isset($_POST['sendotp']) && !isset($_POST['verifyotp'])): ?>
                                                <div class="form-group">
                                                    <label>Captcha</label><br>
                                                    <?php if (!empty($responseData['captcha'])): ?>
                                                        <img src="<?php echo $responseData['captcha']; ?>" alt="Captcha">
                                                    <?php endif; ?>
                                                    <input name="captcha" type="text" class="form-control mt-2" placeholder="Enter Captcha" required>
                                                    <input type="hidden" name="captchaSID" value="<?php echo $responseData['captchaTxnId'] ?? ''; ?>">
                                                </div>
                                                <button class="btn btn-primary mt-2" name="sendotp">Send OTP</button>
                                            <?php endif; ?>

                                           
                                            <?php if (isset($_POST['sendotp'])): ?>
                                                <div class="form-group mt-3">
                                                    <label>Select Aadhaar Type</label>
                                                    <select name="type" class="form-control" required>
                                                        <option value="true">Mask</option>
                                                        <option value="false">Non-Mask</option>
                                                    </select>
                                                </div>

                                                <div class="form-group mt-3">
                                                    <label>Enter OTP</label>
                                                    <input name="otp" type="text" class="form-control" placeholder="Enter OTP" required>
                                                    <input type="hidden" name="otpTxnId" value="<?php echo $responseData['otpTxnId'] ?? ''; ?>">
                                                </div>
                                                <button class="btn btn-success mt-2" name="verifyotp">Verify & Download PDF</button>
                                            <?php endif; ?>

                                          
                                            <div class="mt-3">
                                                <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
<?php include('../template/tngweb/footer.php'); ?>
<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
