<?php
$pageName = "Payments";
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");

// ── Capture incoming values ─────────────────────────────────────────────
$selected_method = inputValidation($_POST['payment_method'] ?? '');
$selected_amount = inputValidation($_POST['amount'] ?? '');

// ── Fetch wallet address, network type AND crypto id from DB ────────────
$wallet_address = '';
$network_type   = '';
$crypto_id      = null;

if (!empty($selected_method)) {
    $stmt = $conn->prepare("SELECT id, wallet_address, network_type FROM crypto_currency WHERE crypto_name = :name LIMIT 1");
    $stmt->execute(['name' => strtolower($selected_method)]);
    $crypto = $stmt->fetch();

    if ($crypto) {
        $crypto_id      = $crypto['id'];
        $wallet_address = $crypto['wallet_address'];
        $network_type   = $crypto['network_type'];
    } else {
        toast_alert('danger', 'Payment method not found. Please go back and try again.');
    }
}

// ── Handle form submission ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount']) && !empty($_FILES['proof']['name'])) {

    $amount         = inputValidation($_POST['amount']);
    $payment_method = inputValidation($_POST['payment_method'] ?? '');
    $user_id        = userDetails('id');
    $pin            = inputValidation($_POST['pin'] ?? '');
    $oldPin         = inputValidation($row['acct_pin'] ?? '');

    if (empty($amount) || empty($payment_method)) {
        toast_alert('danger', 'Fill Required Form');

    } elseif (empty($_FILES['proof']['name'])) {
        toast_alert('danger', 'Upload Payment Screenshot');

    } elseif (empty($crypto_id)) {
        toast_alert('danger', 'Invalid payment method selected');

    } elseif (!empty($pin) && $pin !== $oldPin) {
        toast_alert('error', 'Incorrect Transaction PIN');

    } else {

        // ── File Upload ─────────────────────────────────────────────────
        $file        = $_FILES['proof'];
        $ext         = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed     = ['jpg', 'jpeg', 'png'];
        $folder      = $_SERVER['DOCUMENT_ROOT'] . "/assets/deposit/";
        $filename    = time() . '_' . basename($file['name']);
        $destination = $folder . $filename;

        if (!in_array($ext, $allowed)) {
            toast_alert('danger', 'Only JPG, JPEG, PNG files are allowed');

        } elseif (!move_uploaded_file($file['tmp_name'], $destination)) {
            toast_alert('danger', 'Failed to upload payment proof');

        } else {

            if ($acct_stat === 'hold') {
                toast_alert('error', 'Account on Hold. Contact Support.');

            } elseif ($amount <= 0) {
                toast_alert('error', 'Invalid amount entered');

            } else {
                // ── Insert Transaction ──────────────────────────────────
                $refrence_id      = uniqid();
                $trans_type       = "Crypto Deposit";
                $transaction_type = "credit";
                $trans_status     = "processing";
                $account_name     = "N/A";
                $account_number   = "N/A";

                $sql = "INSERT INTO transactions 
                            (amount, refrence_id, user_id, crypto_id, account_name, account_number, 
                             trans_type, transaction_type, trans_status, image)
                        VALUES 
                            (:amount, :refrence_id, :user_id, :crypto_id, :account_name, :account_number,
                             :trans_type, :transaction_type, :trans_status, :image)";

                $stmt = $conn->prepare($sql);
                $stmt->execute([
                    'amount'           => $amount,
                    'refrence_id'      => $refrence_id,
                    'user_id'          => $user_id,
                    'crypto_id'        => $crypto_id, // ← FIXED: now stores the numeric ID
                    'account_name'     => $account_name,
                    'account_number'   => $account_number,
                    'trans_type'       => $trans_type,
                    'transaction_type' => $transaction_type,
                    'trans_status'     => $trans_status,
                    'image'            => $filename,
                ]);

                // ── Send Email ──────────────────────────────────────────
                $full_name    = $row['firstname'] . " " . $row['lastname'];
                $user_email   = $row['acct_email'];
                $APP_NAME     = WEB_TITLE;
                $APP_URL      = WEB_URL;
                $SITE_ADDRESS = $page['url_address'];

                $message = $sendMail->DepositMsg(
                    $full_name, $amount, $trans_type,
                    $trans_status, $refrence_id,
                    $APP_NAME, $APP_URL, $SITE_ADDRESS
                );
                $email_message->send_mail($user_email, $message, "Deposit - $APP_NAME");

                toast_alert('success', 'Your deposit request is pending', 'Thanks!');
                echo "<script>setTimeout(function(){ window.location.href='/user/dashboard.php'; }, 2000);</script>";
                exit;
            }
        }
    }
}
// ── End form handling ───────────────────────────────────────────────────
?>
    <!-- Main Content Area -->
    <main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            
<div x-data="{ showProof: false }" class="space-y-6 pb-24">

    <style>
/* Ally Bank Design System — Danger Alert Animations */
@keyframes  progress {
    from { width: 100%; }
    to { width: 0%; }
}

@keyframes  shake {
    0%, 100% { transform: rotate(0deg); }
    25% { transform: rotate(-5deg); }
    75% { transform: rotate(5deg); }
}

.animate-shake {
    animation: shake 0.5s ease-in-out;
}

/* Hover lift utility (Ally Bank interaction pattern) */
.hover-lift {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.hover-lift:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}
</style>        <div>
    </div>

<style>
@keyframes  progress {
    from { width: 100%; }
    to { width: 0%; }
}
</style>
    <!-- Page Header -->
    <div class="bg-white border border-[#E0E5E5] rounded-xl p-6">
        <div class="flex items-center space-x-4">
            <div class="w-12 h-12 rounded-xl bg-primary-600 flex items-center justify-center">
                <i data-lucide="credit-card" class="w-6 h-6 text-white"></i>
            </div>
            <div>
                <h1 class="text-2xl font-semibold text-[#0D1B23]">
                    Make Deposit
                </h1>
                <p class="text-[#7A7A7A] text-sm">Secure payment processing for your account</p>
            </div>
        </div>
    </div>

    <div class="max-w-4xl mx-auto">
                    
            <!-- Payment Amount Card -->
            <div class="bg-white border border-[#E0E5E5] rounded-xl p-6 mb-6">
                <div class="text-center mb-6">
                    <p class="text-[#7A7A7A] text-sm mb-2">Payment Amount</p>
                    <h2 class="text-4xl font-semibold text-[#0D1B23] mb-4">
    <?= $currency ?><?= number_format((float)($_POST['amount'] ?? 0), 2) ?>
</h2>
                    <div class="inline-flex items-center space-x-2 px-3 py-1.5 rounded-full bg-[#DFE5E5] border border-[#C8D1D1]">
                        <i data-lucide="shield-check" class="w-4 h-4 text-primary-500"></i>
                        <span class="text-sm text-[#4A4A4A]">Secure Payment</span>
                    </div>
                </div>

                <!-- Payment Method Display -->
                <div class="bg-[#F9F9F9] rounded-xl p-6 border border-[#E0E5E5]">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 rounded-lg bg-[#DFE5E5] flex items-center justify-center">
                                <i data-lucide="banknote" class="w-5 h-5 text-primary-500"></i>
                            </div>
                            <div>
                                <p class="text-sm text-[#7A7A7A]">Payment Method</p>
                                <h3 class="text-xl font-bold text-[#0D1B23]"><?= htmlspecialchars($selected_method) ?></h3>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-center py-4">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=<?= urlencode($wallet_address) ?>" alt="QR Code" class="max-w-xs rounded-xl border border-[#E0E5E5]">
                    </div>
                </div>
            </div>

            <!-- Payment Instructions -->
            <div class="bg-white border border-[#E0E5E5] rounded-xl p-6 mb-6">
                <!-- Crypto Wallet Address -->
                <div class="space-y-4">
                    <div class="flex items-center space-x-2">
                        <i data-lucide="wallet" class="w-5 h-5 text-[#7A7A7A]"></i>
                        <h3 class="text-lg font-semibold text-[#0D1B23]"><?= htmlspecialchars($selected_method) ?> Address</h3>
                    </div>
                    
                    <div class="relative">
                        <input class="w-full px-4 py-4 pr-12 rounded-xl bg-[#F9F9F9] border-2 border-[#E0E5E5] text-[#0D1B23] font-mono text-sm transition-all outline-none" 
                               readonly 
                               type="text" 
                               id="myInput" 
                               value="<?= htmlspecialchars($wallet_address) ?>">
                        <button onclick="myFunction()" 
                                type="button"
                                class="absolute right-2 top-1/2 -translate-y-1/2 p-2 rounded-lg bg-[#DFE5E5] hover:bg-[#C8D1D1] border border-[#C8D1D1] transition-colors group">
                            <i data-lucide="copy" class="w-5 h-5 text-[#4A4A4A]"></i>
                        </button>
                    </div>

                    <div class="flex items-center space-x-2 text-sm text-[#7A7A7A]">
                        <i data-lucide="info" class="w-4 h-4"></i>
                        <span><strong class="text-[#4A4A4A]">Network Type:</strong> <?= htmlspecialchars($network_type) ?></span>
                    </div>
                </div>
            </div>

            <!-- Payment Proof Upload -->
            <div class="bg-white border border-[#E0E5E5] rounded-xl p-6">
                <form method="post" action="/user/payment.php" enctype="multipart/form-data" class="space-y-6">
                    <input type="hidden" name="_token" value="TiU6WOd08r1LmpvV778RMVDEmCinp8o4FRj3SbsF">
                    <div class="space-y-3">
                        <label class="flex items-center space-x-2 text-[#0D1B23] font-semibold">
                            <i data-lucide="upload" class="w-5 h-5 text-[#7A7A7A]"></i>
                            <span>Upload Payment Proof</span>
                        </label>
                        <div class="relative">
                            <input class="w-full px-4 py-4 rounded-xl bg-[#F9F9F9] border-2 border-dashed border-[#E0E5E5] focus:border-primary-500 text-[#0D1B23] transition-colors outline-none file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-[#DFE5E5] file:text-[#4A4A4A] hover:file:bg-[#C8D1D1]" 
                                   type="file" 
                                   name="proof" 
                                   required />
                        </div>
                        <p class="text-sm text-[#7A7A7A] flex items-center space-x-2">
                            <i data-lucide="info" class="w-4 h-4"></i>
                            <span>Please upload a screenshot or photo of your payment confirmation</span>
                        </p>
                    </div>

                    <input type="hidden" name="amount" value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">
                    <input type="hidden" name="payment_method" value="<?= htmlspecialchars($_POST['payment_method'] ?? '') ?>">

                    <button type="submit" 
                            class="w-full px-6 py-4 rounded-xl bg-primary-600 hover:bg-primary-500 text-white font-semibold transition-colors flex items-center justify-center space-x-2 group">
                        <span>Submit Payment</span>
                        <i data-lucide="arrow-right" class="w-5 h-5 group-hover:translate-x-1 transition-transform"></i>
                    </button>
                </form>
            </div>
        
        </div>

</div>


        </div>
    </main>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/footer.php");
?>