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

$fee = $udata['voter_to_mobile_link_without_otp_a'];
checkServiceStatus($udata, 'voter_to_mobile_link_without_otp_a_status');

$appliedby = $udata['phone'];
$balance   = $udata['balance'];
$debit_fee = $balance - $fee;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $epic_number = trim($_POST['epic_number'] ?? '');
    $mob_number  = trim($_POST['mob_number'] ?? '');

    if ($epic_number && $mob_number) {

        if ($balance < $fee) {
            echo "<script>
                Swal.fire('Wallet Low','Please Recharge','error')
                .then(()=>window.location='wallet.php');
            </script>";
            exit;
        }

        $resdata = voter_mob_link_without_otp_verification_api_run([
            'mob_number'   => $mob_number,
            'epic_number' => $epic_number
        ]);

        if (($resdata['sampleCode'] ?? '') !== "200") {
            echo "<script>
                Swal.fire('Error','".$resdata['error']."','error');
            </script>";
            exit;
        }

        /* ===== SUCCESS ===== */

        // Wallet debit
        mysqli_query($tng_conn,
            "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'"
        );

        // Commission
        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $udata['parent'] ?? null,
            "Voter 2 Mobile Link Without OTP"
        );

        // Wallet history
        mysqli_query($tng_conn,"
            INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES(
                '$appliedby',
                '$fee',
                '$debit_fee',
                'Voter Mobile Link Without No OTP',
                '1',
                'Debit'
            )
        ");

        // Base64 store
        $base64Json = base64_encode(
            json_encode($resdata, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)
        );

        mysqli_query($tng_conn,"
            INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES(
                'VOTER_MOBILE_LINK_NO_OTP',
                '".mysqli_real_escape_string($tng_conn,$resdata['mob_number'])."',
                '$appliedby',
                '".mysqli_real_escape_string($tng_conn,$resdata['fullname'])."',
                '".mysqli_real_escape_string($tng_conn,$base64Json)."',
                NOW()
            )
        ");

        echo "<script>
            Swal.fire({
                icon:'success',
                title:'VOTER MOBILE LINK',
                text:'Mobile linked successfully',
                timer:2200,
                showConfirmButton:false
            }).then(()=>window.location='all_history.php');
        </script>";
        exit;
    }
}
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="page-wrapper">
<div class="page-content">
<div class="container">
<div class="row justify-content-center" style="min-height:80vh">

<div class="col-lg-5">
<div class="card p-4 shadow">

<a href="javascript:history.back()" class="fw-bold">
<i class="bi bi-arrow-left-circle"></i> Go Back
</a>

<h4 class="text-center mt-3">🗳️ Voter → Mobile Link (No OTP)</h4>

<form method="POST" id="confirmForm">

<div class="mb-3">
<label>Voter Number (EPIC)</label>
<input type="text" name="epic_number" class="form-control" required>
</div>

<div class="mb-3">
<label>Mobile Number</label>
<input type="text" name="mob_number" class="form-control" required>
</div>

<div class="row mt-3">
<div class="col-6">
<input class="form-control fw-bold text-success"
       value="Fee ₹ <?=$fee?>" readonly>
</div>
<div class="col-6 text-end">
<button class="btn btn-success" id="submitBtn">
Submit
</button>
</div>
</div>

</form>

</div>
</div>
</div>
</div>
</div>
</div>

<script>
let locked=false;
document.getElementById('confirmForm').addEventListener('submit',function(e){
    e.preventDefault();
    if(locked) return;

    Swal.fire({
        title:'Are you sure?',
        text:'Wallet will be charged on success',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'Yes, Proceed'
    }).then((r)=>{
        if(r.isConfirmed){
            locked=true;
            document.getElementById('submitBtn').disabled=true;
            this.submit();
        }
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>
