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

if (isset($_POST['sendotp'])) {
    $epic = $_POST['epic'];
    $request = [
            'epic_number' => $epic,
        ];

        $responseData = voter_otp_verification_api_run($request);
    if ($responseData['sampleCode'] != '200') {
        echo "
        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'error', title: 'Error', text: '{$responseData['error']}', timer: 5000 });
            setTimeout(() => { window.location = ''; }, 5000);
        </script>";
    }
}

if (isset($_POST['verifyotp'])) {
    $epic = $_POST['epic'];
    $otp = $_POST['otp'];
    $stateCd = $_POST['stateCd'];
   

    if ($udata['balance'] >= $fee) {
        $request = [
            'epic_number' => $epic,
            'otp' => $otp,
            'stateCd' => $stateCd,
        ];

        $resdata = voter_pdf_verification_api_run($request);
        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, "Voter Original PDF Downloa Verification");
           mysqli_query(
    $tng_conn,
    "INSERT INTO all_pdf_records
     (service_name, name, username, number, pdf, date)
     VALUES
     (
        'voter_pdf_otp',
        '".mysqli_real_escape_string($tng_conn, $resdata['fullname'])."',
        '".$udata['phone']."',
        '".mysqli_real_escape_string($tng_conn, $resdata['epic_number'])."',
        '".mysqli_real_escape_string($tng_conn, $resdata['Voter_pdf'])."',
        '$timestamp'
     )"
);

               mysqli_query($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
            mysqli_query($tng_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$appliedby','$fee','$debit_fee','Voter Original PDF Download','1','Debit')");
echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
<script>
Swal.fire({
    icon:'success',
    title:'Success',
    text:'Voter PDF Generated Successfully',
    timer:1500,
    showConfirmButton:false
}).then(()=>{
    window.location='all_history.php';
});
</script>";

          
        } else {
            echo "
            <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({ icon: 'error', title: 'Error', text: '{$resdata['error']}', timer: 5000 });
            </script>";
        }
    } else {
        echo "
        <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'error', title: 'Wallet Balance is 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-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">
                                        <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">️ Voter Original PDF (All State)........</a>
                                                    </div>
                             
                                <form action="" method="POST" class="row g-3">
                                    
                                  <div class="card-body">
                                                            <div class="col-md-12">
                                                                <div class="form-group">
                                        <label>Enter Voter Number (EPIC)</label>
                                        <input name="epic" type="text" class="form-control" placeholder="Enter Voter Number" required value="<?php echo $_POST['epic'] ?? ''; ?>">
                                    </div>
      <hr>
                                    <!-- Send OTP button -->
                                    <?php if (!isset($_POST['sendotp']) || ($responseData['sampleCode'] ?? '') != '200') { ?>
                                        <div class="col-md-6 d-flex align-items-end">
                                            <button class="btn btn-primary" name="sendotp"><i class="fa fa-paper-plane"></i> Send OTP</button>
                                        </div>
                                          
                                                                <hr>
                                    <?php } ?>

                                    <!-- OTP verification input -->
                                    <?php if (($responseData['sampleCode'] ?? '') == '200') { ?>
                                      <div class="card-body">
                                                            <div class="col-md-12">
                                                                <div class="form-group">
                                            <label>Enter OTP</label>
                                            <input name="otp" type="text" class="form-control" placeholder="Enter OTP" required>
                                            <input type="hidden" name="stateCd" value="<?php echo htmlspecialchars($responseData['stateCd'] ?? ''); ?>">
                                        </div>
                                              <hr>
                                        <div class="col-md-6 d-flex align-items-end">
                                            <button class="btn btn-success" name="verifyotp"><i class="fa fa-check-circle"></i> Verify & Download PDF</button>
                                        </div>
                                    <?php } ?>

                                    <!-- Fee display -->
                                      <div class="row mt-3">
                                                                  <div class="col-md-6">
                                        <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                    </div>
                                </form>

                                <!-- Info / messages -->
                                <?php if (!empty($responseData['message'])) { ?>
                                    <div class="alert alert-info mt-3">
                                        <?php echo htmlspecialchars($responseData['message']); ?>
                                    </div>
                                <?php } ?>

                               

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