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

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

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

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['voter_flow'])) {
    $_SESSION['voter_flow'] = [];
}
$flow = &$_SESSION['voter_flow'];

$step = $flow['step'] ?? 1;
$mobileNumber = $flow['mobile'] ?? '';
$epic = $flow['epic'] ?? '';
$tokenA = $flow['tokenA'] ?? '';
$aadhar = $flow['aadhar'] ?? '';
$aadharName = $flow['aadhar_name'] ?? '';
$tokenB = $flow['tokenB'] ?? '';

function sweetAlert($type, $title, $text, $redirect = null) {
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
        Swal.fire({
            icon: '$type',
            title: '$title',
            text: '" . addslashes($text) . "',
            timer: 2500,
            showConfirmButton: false
        })" . ($redirect ? ".then(() => { window.location = '$redirect'; });" : "") . "
    </script>";
    if ($redirect) exit;
}

function showError($msg) {
    sweetAlert('error', 'Error', $msg);
}

function resetFlow() {
    
    unset($_SESSION['voter_flow']);
    echo "<script>window.location='".$_SERVER['PHP_SELF']."';</script>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

   
    if ($action === 'send_voter_otp') {
        $mobile = trim($_POST['mobileNumber'] ?? '');
        if (!$mobile) showError('Mobile number required');

        $res = voter_link_otp_verification_api_run(['mob_number' => $mobile]);
        if (($res['sampleCode'] ?? '') === '200') {
            $flow['step'] = 2;
            $flow['mobile'] = $mobile;
            sweetAlert('success', 'OTP Sent', "OTP sent to $mobile", $_SERVER['PHP_SELF']);
        } else {
            showError($res['error'] ?? 'Failed to send OTP');
        }
    }

   
    if ($action === 'verify_voter_otp') {
        $epicInput = trim($_POST['epic'] ?? '');
        $otp = trim($_POST['otp'] ?? '');
        if (!$epicInput || !$otp) showError('EPIC and OTP required');

        $res = voter_mob_link_verification_api_run([
            'mob_number' => $flow['mobile'],
            'epic' => $epicInput,
            'otp' => $otp
        ]);
        if (($res['sampleCode'] ?? '') === '200') {
            $tokenA_val = $res['token'] ?? $res['data']['token'] ?? '';
            if (!$tokenA_val) showError('Token A not received');

            $flow['step'] = 3;
            $flow['epic'] = $epicInput;
            $flow['tokenA'] = $tokenA_val;
            sweetAlert('success', 'Verified', 'Voter OTP verified. Token A received.', $_SERVER['PHP_SELF']);
        } else {
            showError($res['error'] ?? 'Verification failed');
        }
    }

    
    if ($action === 'send_aadhar_otp') {
        $aadharNum = trim($_POST['aadhar'] ?? '');
        $nameOnAadhar = trim($_POST['aadhar_name'] ?? '');
        if (!$aadharNum || !$nameOnAadhar) showError('Aadhaar number and name required');

        $res = aadhar_esign_otp_send_api_run([
            'aadhar' => $aadharNum,
            'aadhar_name' => $nameOnAadhar,
            'token' => $flow['tokenA']
        ]);
        if (($res['sampleCode'] ?? '') === '200') {
            $tokenB_val = $res['token'] ?? $res['data']['token'] ?? '';
            if (!$tokenB_val) showError('Token B not received');

            $flow['step'] = 4;
            $flow['aadhar'] = $aadharNum;
            $flow['aadhar_name'] = $nameOnAadhar;
            $flow['tokenB'] = $tokenB_val;
            sweetAlert('success', 'OTP Sent', 'Aadhaar eSign OTP sent.', $_SERVER['PHP_SELF']);
        } else {
            showError($res['error'] ?? 'Failed to send Aadhaar OTP');
        }
    }

    
    if ($action === 'verify_aadhar_otp') {
        $otpAadhar = trim($_POST['otp_aadhar'] ?? '');
        if (!$otpAadhar) showError('Aadhaar OTP required');

        if ($balance < $fee) {
            showError('Wallet low. Please recharge.');
            resetFlow();
        }

        $res = aadhar_esign_otp_verify_api_run([
            'otp' => $otpAadhar,
            'token' => $flow['tokenB']
        ]);
        if (($res['sampleCode'] ?? '') === '200') {
            $newBalance = $balance - $fee;

           
            $stmt = $tng_conn->prepare("UPDATE users SET balance = ? WHERE phone = ?");
            $stmt->bind_param("ds", $newBalance, $appliedby);
            $stmt->execute();

            
            addCommission($tng_conn, $appliedby, $fee, $udata['parent'] ?? null, "Voter + Aadhaar eSign Link");

           
            $stmt2 = $tng_conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, 'Voter + Aadhaar eSign', '1', 'Debit')");
            $stmt2->bind_param("sds", $appliedby, $fee, $newBalance);
            $stmt2->execute();

            
            $base64Json = base64_encode(json_encode($res, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            $fullName = $res['fullname'];
            $contact = $flow['mobile'];
            $stmt3 = $tng_conn->prepare("INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) VALUES ('VOTER_AADHAAR_ESIGN', ?, ?, ?, ?, NOW())");
            $stmt3->bind_param("ssss", $fullName, $appliedby, $contact, $base64Json);
            $stmt3->execute();

            
            unset($_SESSION['voter_flow']);
            sweetAlert('success', 'Success!', 'Voter linked with Aadhaar eSign successfully.', 'all_history.php');
        } else {
            showError($res['error'] ?? 'Aadhaar OTP verification failed');
        }
    }

   
    if ($action === 'reset') {
        resetFlow();
    }
}
?>

<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-6">
<div class="card p-4 shadow">
    <a href="javascript:history.back()" class="fw-bold mb-3"><i class="bi bi-arrow-left-circle"></i> Go Back</a>
    <h4 class="text-center mt-3">🗳️ Voter → Mobile Link + Aadhaar eSign</h4>
    <p class="text-center text-muted">Complete voter linking with Aadhaar eSign (Multi-Step)</p>

    <form method="POST" id="voterForm">
        <?php if ($step == 1): ?>
            <div class="mb-3">
                <label>Mobile Number (Registered with Voter ID)</label>
                <input type="text" name="mobileNumber" class="form-control" placeholder="10 digit mobile" required>
            </div>
            <input type="hidden" name="action" value="send_voter_otp">
            <button type="submit" class="btn btn-primary w-100">Send Voter OTP</button>

        <?php elseif ($step == 2): ?>
            <div class="mb-3">
                <label>EPIC Number (Voter ID)</label>
                <input type="text" name="epic" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>OTP received on <?= htmlspecialchars($mobileNumber) ?></label>
                <input type="text" name="otp" class="form-control" required>
            </div>
            <input type="hidden" name="action" value="verify_voter_otp">
            <button type="submit" class="btn btn-success w-100">Verify Voter OTP & Get Token A</button>

        <?php elseif ($step == 3): ?>
            <div class="mb-3">
                <label>Aadhaar Number (12 digits)</label>
                <input type="text" name="aadhar" maxlength="12" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Name as per Aadhaar (Exactly as on card)</label>
                <input type="text" name="aadhar_name" class="form-control" required>
            </div>
            <input type="hidden" name="action" value="send_aadhar_otp">
            <button type="submit" class="btn btn-info w-100">Send Aadhaar eSign OTP</button>

        <?php elseif ($step == 4): ?>
            <div class="mb-3">
                <label>Enter OTP sent to Aadhaar registered mobile</label>
                <input type="text" name="otp_aadhar" class="form-control" required>
            </div>
            <div class="alert alert-warning">
                <strong>Fee: ₹<?= htmlspecialchars($fee) ?></strong> will be deducted from wallet on success.
            </div>
            <input type="hidden" name="action" value="verify_aadhar_otp">
            <button type="submit" class="btn btn-danger w-100">Verify Aadhaar OTP & Complete</button>
        <?php endif; ?>
    </form>

    <?php if ($step > 1): ?>
        <form method="POST" class="mt-2">
            <input type="hidden" name="action" value="reset">
            <button type="submit" class="btn btn-link btn-sm">Start Over</button>
        </form>
    <?php endif; ?>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
// SweetAlert confirmation before each step
document.getElementById('voterForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    let action = this.querySelector('input[name="action"]').value;
    let title = '', text = '';
    if (action === 'send_voter_otp') {
        title = 'Send OTP?';
        text = 'We will send a verification OTP to this mobile number.';
    } else if (action === 'verify_voter_otp') {
        title = 'Verify Voter OTP?';
        text = 'Your wallet will NOT be charged at this step.';
    } else if (action === 'send_aadhar_otp') {
        title = 'Send Aadhaar eSign OTP?';
        text = 'This will send an OTP to your Aadhaar registered mobile.';
    } else if (action === 'verify_aadhar_otp') {
        title = 'Complete Verification?';
        text = `Your wallet will be charged ₹<?= $fee ?> on success.`;
    }
    Swal.fire({
        title: title,
        text: text,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, proceed',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            this.submit();
        }
    });
});
</script>

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