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

$fee = $udata['voter_mobile_link_a'];
checkServiceStatus($udata, 'voter_mobile_link_a_status');

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

$resdata = [];
$showOtpForm = false;
$mobileNumber = '';
$epic = '';
$otp = '';

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

    $mobileNumber = trim($_POST['mobileNumber'] ?? '');
    $epic = trim($_POST['epic'] ?? '');
    $otp  = trim($_POST['otp'] ?? '');

    /* ===================== SEND OTP ===================== */
    if ($mobileNumber && !$epic && !$otp) {

        $resdata = voter_link_otp_verification_api_run([
            'mob_number' => $mobileNumber
        ]);

        if (($resdata['sampleCode'] ?? '') === "200") {
            $showOtpForm = true;
            echo "<script>
                Swal.fire({
                    icon:'success',
                    title:'OTP Sent',
                    text:'OTP sent to $mobileNumber',
                    timer:2500
                });
            </script>";
        } else {
            echo "<script>
                Swal.fire('Error','".$resdata['error']."','error');
            </script>";
        }
    }

    /* ===================== VERIFY OTP ===================== */
    if ($epic && $otp) {

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

        $resdata = voter_mob_link_verification_api_run([
            'mob_number' => $mobileNumber,
            'epic'       => $epic,
            'otp'        => $otp
        ]);

        if (($resdata['sampleCode'] ?? '') !== "200") {
            echo "<script>
                Swal.fire('Failed','".$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 OTP"
        );

        // Wallet history
        mysqli_query($tng_conn,"
            INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES(
                '$appliedby',
                '$fee',
                '$debit_fee',
                'Voter Mobile Link 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_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;
    }
}
?>

<!-- ===================== HTML ===================== -->
<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 (OTP)</h4>

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

<div class="mb-3">
<label>Mobile Number</label>
<input type="text" name="mobileNumber" class="form-control"
       value="<?=htmlspecialchars($mobileNumber)?>" required>
</div>

<?php if($showOtpForm): ?>
<div class="mb-3">
<label>EPIC Number</label>
<input type="text" name="epic" class="form-control" required>
</div>

<div class="mb-3">
<label>OTP</label>
<input type="text" name="otp" class="form-control" required>
</div>
<?php endif; ?>

<div class="row align-items-center 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>

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

    Swal.fire({
        title:'Are you sure?',
        text:'Wallet will be charged on success',
        icon:'question',
        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'); ?>
