<?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");
           $database = mysqli_query($tng_conn, "INSERT INTO `voter_pdf`(`name`, `username`, `aadhar`, `pdf`, `date`) VALUES ('{$resdata['fullname']}','{$udata['phone']}','{$resdata['epic_number']}','{$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: 'Pdf Generate Sucessfull Redirecting To List!', timer: 2000 });
            setTimeout(() => { window.location = 'voter_otp_pdf_list.php'; }, 1200);
        </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 } ?>

                                <!-- PDF download section -->
                                <?php if (!empty($resdata['sampleCode']) && $resdata['sampleCode'] === '200') { ?>
                                    <div class="card mt-3" style="background-color: #FCF3CF;" id="printSection">
                                        <div class="card-body">
                                            <h5 class="mb-3">Voter Details</h5>
                                            <table class="table table-bordered table-striped">
                                                <tbody>
                                                    <tr>
                                                        <th>Voter Number</th>
                                                        <td><?php echo htmlspecialchars($resdata['epic_number'] ?? ''); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Name</th>
                                                        <td><?php echo htmlspecialchars($resdata['fullname'] ?? ''); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>VIEW PDF</th>
                                                        <td>
                                                            <a href="<?php echo htmlspecialchars($resdata['Voter_pdf'] ?? ''); ?>" 
                                                               download="<?php echo htmlspecialchars($resdata['epic_number'] ?? ''); ?>.pdf" 
                                                               class="btn btn-sm btn-success">
                                                                Download PDF
                                                            </a>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </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>
