<?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();  
}

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

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

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


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");

            mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'");
            mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES
            (
                'aadhaar_otp_pdf',
                '".mysqli_real_escape_string($tng_conn,$resdata['eid'])."',
                '$appliedby',
                '".mysqli_real_escape_string($tng_conn,$resdata['aadhar'])."',
                '".mysqli_real_escape_string($tng_conn,$resdata['Aadhaar_Pdf'])."',
                '$timestamp'
            )"
        );
            mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('$appliedby', '$fee', '".($udata['balance'] - $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 Generated Successfully. Redirecting...', timer: 2000 });
                setTimeout(() => { window.location = 'aadhar_otp_pdflist.php'; }, 1200);
            </script>";
        } else {
            $errorMsg = $resdata['error'] ?? 'Verification failed';
            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>";
    }
}
?>

<!-- HTML FORM - exactly same as before -->
<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']) && ($otpData['sampleCode'] ?? '') === '200'): ?>
                                                <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 $otpData['otpTxnId'] ?? ''; ?>">
                                                </div>
                                                <button class="btn btn-success mt-2" name="verifyotp">Verify & Download PDF</button>
                                            <?php elseif (isset($_POST['sendotp'])): ?>
                                                <div class="alert alert-warning mt-3">Failed to send OTP. Please try again.</div>
                                            <?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>
    </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>