<?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='aadhaar_otp_pdf_fee' "));
$fee = $price['price'];
$appliedby = $udata['phone'];
$debit_fee = $udata['balance'] - $fee;

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


if (!isset($_POST['sendotp']) && !isset($_POST['verifyotp'])) {
    $captchaUrl = "$tng_apiurl/aadhar_captcha_verification";
    $curl = curl_init($captchaUrl);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    $responseData = json_decode($response, true);
}

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

    $otpUrl = "$tng_apiurl/aadhar_otp_pdf_verification?aadhar={$aadhar}&captchaSID={$captchaSID}&captcha={$captcha}&action=send&apikey=$tng_apikey";

    $curl = curl_init($otpUrl);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($curl);
    curl_close($curl);

    $otpData = json_decode($response, true);

    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) {
        $verifyUrl = "$tng_apiurl/aadhar_otp_pdf_verification?aadhar={$aadhar}&type={$type}&otpTxnId={$otpTxnId}&otp={$otp}&action=verify&apikey=$tng_apikey";

        $curl = curl_init($verifyUrl);
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        $resdata = json_decode($response, true);

        if (($resdata['sampleCode'] ?? '') === "200") {
          
          date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
                $parentPhone = $udata['parent'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Aadhar Otp Pdf Verification");
           $debit = mysqli_query($ahk_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $database = mysqli_query($ahk_conn, "INSERT INTO `aadhar_otp_pdf`(`name`, `username`, `aadhar`, `pdf`, `date`) VALUES ('{$resdata['eid']}','{$udata['phone']}','{$resdata['aadhar']}','{$resdata['Aadhaar_Pdf']}','$timestamp')");
             mysqli_query($ahk_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="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/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>
