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

$serviceName = 'voter_to_mobile_link_without_otp_apply';
$fee = $udata[$serviceName] ?? 0;
checkServiceStatus($udata, $serviceName . '_status');

$appliedby = $udata['phone'];
$balance   = (float) $udata['balance'];


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 src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>Swal.fire('Wallet Low','Please Recharge','error').then(()=>window.location='wallet.php');</script>";
            exit;
        }

        // Call API function from config
        $res = voter_mobile_link_manual_submit_api_run($epic_number, $mob_number);

        if (($res['sampleCode'] ?? '') === '200' && ($res['status'] ?? '') === 'Pending') {
            // Deduct wallet
            $newBalance = $balance - $fee;
            $stmt = $tng_conn->prepare("UPDATE users SET balance = ? WHERE phone = ?");
            $stmt->bind_param("ds", $newBalance, $appliedby);
            $stmt->execute();

            // Add commission
            addCommission($tng_conn, $appliedby, $fee, $udata['parent'] ?? null, "Voter Mobile Link Manual");

            // Wallet history
            $stmt2 = $tng_conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, 'Voter Mobile Link Manual', '1', 'Debit')");
            $stmt2->bind_param("sds", $appliedby, $fee, $newBalance);
            $stmt2->execute();

            // Save request in DB (including fee)
            $application_no = $res['application_no'];
            $fullname = $res['fullname'] ?? '';
            $state = $res['state'] ?? '';
            $stmt3 = $tng_conn->prepare("INSERT INTO voter_mobile_link_requests (application_no, epic_number, mob_number, fullname, state, fee, username, status, date) VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending', NOW())");
            $stmt3->bind_param("sssssds", $application_no, $epic_number, $mob_number, $fullname, $state, $fee, $appliedby);
            $stmt3->execute();

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({ icon:'success', title:'Request Submitted', text:'Your request is pending. Track status in history.', timer:3000 })
                .then(() => window.location='voter_mobile_link_manual_history.php');
            </script>";
            exit;
        } else {
            $error = $res['error'] ?? $res['Message'] ?? 'Submission failed';
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>Swal.fire('Error','".addslashes($error)."','error');</script>";
        }
    }
}
?>

<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 (Manual, No OTP)</h4>
<p class="text-muted text-center">Submit EPIC and mobile. Wallet deducted immediately. Status will be updated later.</p>

<form method="POST">
<div class="mb-3">
<label>EPIC Number (Voter ID)</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 Request</button>
</div>
</div>
</form>
<div class="mt-3 text-center">
<a href="voter_mobile_link_manual_history.php" class="btn btn-sm btn-info">View My Requests</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
let locked = false;
document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault();
    if (locked) return;
    Swal.fire({
        title: 'Confirm Submission?',
        text: 'Your wallet will be charged ₹<?= $fee ?> immediately.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Submit'
    }).then((r) => {
        if (r.isConfirmed) {
            locked = true;
            document.getElementById('submitBtn').disabled = true;
            this.submit();
        }
    });
});
</script>

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