<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');
?>

<!-- Page Wrapper -->
<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb with Action Buttons -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">Services</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted" aria-current="page">Voter Mobile Link Withot Otp</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
                <a href="vote_mob_link_list" class="btn btn-success">
                    <i class="bi bi-list-ul me-1"></i>Voter Mobile Link List
                </a>
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
        <!-- End Breadcrumb -->

        <head>
            <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
            <style>
                .hidden {
                    display: none;
                }
            </style>
        </head>

        <body>
            <?php
            $price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='v_mobile_link' "));
            $fee = $price['price'];
            $balance = $udata['balance'];
            $mobile = $udata['phone'];
            $debit_fee = $balance - $fee;

            if ($balance > $fee) {
                if (isset($_POST['submit_mobile']) && !empty($_POST['new_mobile']) && !empty($_POST['epic'])) {
                    $newMobileNumber = $_POST['new_mobile'];
                    $epic = $_POST['epic'];

                    // Prepare API URL (OTP Removed)
                    $apiUrl = "https://" . htmlspecialchars($flexsecureapiurl) . "/panel/serviceapi/voter/voter_mob_link_without_otp.php?apikey=$api_key&epic=$epic&mobile=$newMobileNumber&type=otpv&cid=123";

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $apiUrl);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    curl_close($ch);

                    if ($response === false) {
                        echo '<div class="alert alert-danger" role="alert">cURL request failed</div>';
                    } else {
                        $data = json_decode($response, true);
                        $status = $data['status'] ?? 'unknown';
                        $message = ($data['message'] ?? '') . ($data['msg'] ?? '');
                        $refId = $data['refId'] ?? null;
                        $rerror = $data['error'] ?? null;
                        $alertType = $status == "Success" ? 'success' : 'error';

                        if (!empty($refId)) {
                            mysqli_query($ahk_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$mobile'");
                            $new_balance = $balance - $fee;
                            date_default_timezone_set("Asia/Kolkata");
                            $timestamp = date('d/m/Y g:i:s');
                            mysqli_query($ahk_conn, "INSERT INTO m_link(epic_no, mobile_no, response, userid, date) VALUES ('$epic','$newMobileNumber','$message','$mobile','$timestamp')");
                            mysqli_query($ahk_conn, "INSERT INTO wallethistory(userid, amount, balance, purpose, status, type) VALUES ('$mobile','$fee','$debit_fee','$epic Voter Mobile Link Without OTP','1','Debit')");
                        }

                        echo "<script>
                Swal.fire({
                    title: '$rerror',
                    text: 'Mobile Number Link $status. Ref No: $refId. Message: $message',
                    icon: '$alertType',
                    confirmButtonText: 'OK'
                });
                setTimeout(function () {
                    window.location = 'vote_mob_link_list';
                }, 5000);
            </script>";
                    }
                }
            } else {
                echo "<script>
        Swal.fire({
            title:'Balance Low! Recharge Now',
            text:'Insufficient Balance',
            icon:'warning',
            confirmButtonText:'OK'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location = 'wallet.php';
            }
        });
    </script>";
            }
            ?>


            <div class="container-fluid pt-4 px-4">
                <div class="row">
                    <!-- Left Side: Form Section -->
                    <div class="col-lg-5 mb-4">
                        <div class="card">
                            <div class="card-body">
                                <h3 class="card-title text-dark text-center"><strong>Voter Mobile No Link Without Otp
                                        Instant</strong></h3>
                            </div>
                            <div class="card-body">
                                <a href="vot_org_instant" class="btn btn-dark w-100 mb-3">Voter Oringnal PDF Download
                                    Here</a>

                                <form method="POST">
                                    <div class="form-group mb-3">
                                        <label for="epic">Enter EPIC Number <span class="text-danger">*</span></label>
                                        <input type="text" name="epic" id="epic" class="form-control border-success"
                                            placeholder="EPIC Number" required>
                                    </div>

                                    <div class="form-group mb-3">
                                        <label for="new_mobile">Enter New Mobile Number <span
                                                class="text-danger">*</span></label>
                                        <input type="text" name="new_mobile" id="new_mobile"
                                            class="form-control border-success" placeholder="10-digit mobile number"
                                            pattern="\d{10}" maxlength="10" minlength="10"
                                            title="Please enter exactly 10 digits" required />

                                    </div>

                                    <button type="submit" name="submit_mobile" class="btn btn-primary w-100">
                                        <i class="fa fa-check-circle"></i> Submit
                                    </button>

                                    <div class="text-center mt-3">
                                        <div class="fee-container text-center">
                                            <h5 class="text-warning">Application Fee: ₹<?php echo $fee; ?></h5>
                                        </div>
                                    </div>
                                </form>

                                <style>
                                    .fee-container {
                                        background-color: #fff;
                                        border-radius: 8px;
                                        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                                        padding: 10px 15px;
                                        max-width: 300px;
                                        margin: 10px auto;
                                    }

                                    .fee-container h5 {
                                        color: #ff9800;
                                        font-size: 18px;
                                        font-weight: 600;
                                    }
                                </style>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            </form>


            <!-- Form 2: Displayed upon successful first API response -->
            <form id="additional_fields_form" class="user <?php echo ($epicNumber) ? '' : 'hidden'; ?>" method="POST">
                <div class="form-group mb-3">
                    <label for="">Full Name<span class="text-danger">*</span></label>
                    <input id="" name="" class="form-control" type="" readonly value="<?php echo $applicantFullName; ?>"
                        required>
                </div>
                <div class="form-group mb-3">
                    <label for="new_mobile">New Mobile Number<span class="text-danger">*</span></label>
                    <input id="epic" name="epic" class="form-control" type="hidden" value="<?php echo $epicNumber; ?>"
                        required>
                    <input id="new_mobile" name="new_mobile" class="form-control border-primary" type="number"
                        placeholder="ENTER NEW MOBILE NUMBER" value="<?php echo $mobileNumber; ?>" required>

                </div>
                <div class="form-group mb-3">
                    <label for="otp">OTP<span class="text-danger">*</span></label>
                    <input id="otp" name="otp" class="form-control border-primary" type="number"
                        placeholder="ENTER 6 DIGIT OTP" value="" required>
                </div>
                <!--<div class="form-group">-->
                <!--<label for="place">Ca<span class="text-danger">*</span></label>-->
                <!--    <img src="data:application/image;base64,<?php echo $captcha_img; ?>"  class="border-primary mt-2" alt="captchaa" />-->
                <!--</div>-->
                <div class="form-group mb-3">
                    <!--<label for="captcha">Enter Captcha<span class="text-danger">*</span></label>-->

                </div>
                <br>
                <button type="submit" name="submit_mobile" class="btn btn-primary w-100"><i
                        class="fa fa-check-circle"></i>Submit</button>
            </form>
    </div>
</div>
</div>
<script>
    document.getElementById('getOTPButton').addEventListener('click', function () {
        var newMobile = document.getElementById('new_mobile').value;
        // Make API call with API key
        fetch(`https://" . htmlspecialchars($flexsecureapiurl) . "/panel/serviceapi/voter/voter_mob_link.php?nmobile=${newMobile}`)
            .then(response => {
                return response.json();
            })
            .then(data => {
                console.log('API response:', data);
                if (data.error) {
                    // Display error message in alert
                    alert(data.error);
                } else if (data.message) {
                    // Display message from API in alert
                    alert(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while sending OTP. Please try again later.');
            });
    });
</script>
<!-- Add your footer content here -->

<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>
<script>
    // Hide the success and error alerts after 3 seconds
    setTimeout(function () {
        document.getElementById('success-alert').style.display = 'none';
        // document.getElementById('error-alert').style.display = 'none';
    }, 3000);
</script>

</body>

</html>
