<?php require("header.php"); ?>

<?php
// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form input values securely
    $signal_fee = $_POST['signal_fee'] ?? '';
    $signal_pin = $_POST['signal_pin'] ?? '';
    $hidden_pin = $_POST['hidden_pin'] ?? '';
    $deposit    = $_POST['deposit'] ?? '';
    $id         = $_POST['id'] ?? '';

    if (empty($id)) {
        die("<div class='alert alert-danger'>User ID is missing! Debugging: " . var_export($_POST, true) . "</div>");
    }

    try {
        $stmt = $pdo->prepare("SELECT userbill FROM logins WHERE signal_fee = :signal_fee AND signal_pin = :signal_pin");
        $stmt->execute([
            ':signal_fee' => $signal_fee,
            ':signal_pin' => $signal_pin
        ]);
        
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            $userbill = $user['userbill'];
            $upgfee = $userbill + $deposit;

            $updateStmt = $pdo->prepare("UPDATE logins SET signal_pin = :hidden_pin, userbill = :upgfee, signal_status = 0 WHERE id = :id");
            $updateStmt->execute([
                ':hidden_pin' => $hidden_pin,
                ':upgfee'     => $upgfee,
                ':id'         => $id
            ]);

            $success = "<div class='alert alert-success' style='margin-bottom:20px;'>
                            Signal Pin Granted Successfully...
                            <meta http-equiv='refresh' content='10; url=withdraw.php' />
                        </div>";
        } else {
            $error5 = "<div class='alert alert-danger' align='center'>Incorrect signal Pin!!!</div>";
        }
    } catch (PDOException $e) {
        $error5 = "<div class='alert alert-danger' align='center'>Database Error: " . $e->getMessage() . "</div>";
    }
}
?>

<div class="main-panel">
    <div class="content-wrapper bg-dark">
        <div class="row">
            <div class="col-md-12 grid-margin">
                <div class="d-flex justify-content-between flex-wrap">
                    <div class="align-items-end flex-wrap">
                        <div class="no-deposit">
                            <h4 class="card-title" style="font-family: 'Roboto'!important;">Signal FEE</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Pass PHP variables to JS for pre-filling
$deposit_js     = json_encode($deposit ?? '');
$signal_fee_js  = json_encode($signal_fee ?? '');
$hidden_pin_js  = json_encode($signal_pin ?? '');
$id_js          = json_encode($id ?? '');
$currency_js    = json_encode($currency ?? '');
?>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    Swal.fire({
        title: 'Enter Signal PIN',
        html: `
            <form id="signalForm" method="POST">
                <input type="hidden" name="id" value=<?php echo $id_js; ?>>
                <input type="hidden" name="hidden_pin" value=<?php echo $hidden_pin_js; ?>>
                <input type="hidden" name="deposit" value=<?php echo $deposit_js; ?>>

                <div class="form-group">
                    <label>Signal Fee (<?php echo $currency_js; ?>)</label>
                    <input type="text" class="swal2-input" value="<?php echo $deposit*$signal_fee ?>" readonly>
                </div>
                <div class="form-group">
                    <label>Signal Percent (%)</label>
                    <input type="text" class="swal2-input" name="signal_fee" value=<?php echo $signal_fee_js; ?> readonly>
                </div>
                <div class="form-group">
                    <label>Signal PIN</label>
                    <input type="password" class="swal2-input" name="signal_pin" placeholder="Enter PIN" required>
                </div>
            </form>
        `,
        showCancelButton: true,
        showDenyButton: true,
        confirmButtonText: 'Submit',
        denyButtonText: 'Contact Support',
        cancelButtonText: 'Cancel',
        focusConfirm: false,
        preConfirm: () => {
            const form = Swal.getPopup().querySelector('#signalForm');
            const formData = new FormData(form);
            fetch('', { method: 'POST', body: formData })
                .then(() => location.reload())
                .catch(err => Swal.showValidationMessage(`Request failed: ${err}`));
        }
    }).then((result) => {
        if (result.isDenied) {
            window.location.href = 'support.php';
        }
    });
});
</script>
