<?php
include('inc/session.php'); // This should define $conn, $email, $username, $user_ip, $data, and potentially $status

// Define these variables to be accessible in the HTML/JS part if a deposit is made
$deposit_recorded = false;
$recorded_amount = 0;
$recorded_payment_option = '';
$error_message = ''; // For displaying errors related to deposit

if (isset($_POST['submit'])) {
    $amount_str = $_POST['amount'] ?? '';
    $payment_option = $_POST['payment_option'] ?? '';
    $date = date('Y-m-d H:i:s'); // Using DATETIME for created_at might be better

    // --- Validation ---
    $min_deposit = 100; // Minimum deposit amount
    $allowed_payment_options = ['btc', 'eth', 'ltc', 'usdt', 'bank'];
    $errors = [];

    if (empty($email)) { // Check if $email is set from session.php
        $errors[] = "User session not found. Please log in again.";
    }

    if (!is_numeric($amount_str)) {
        $errors[] = "Amount must be a number.";
    } else {
        $amount_float = floatval($amount_str);
        if ($amount_float <= 0) {
            $errors[] = "Invalid amount entered. Amount must be positive.";
        } elseif ($amount_float < $min_deposit) {
            $errors[] = "Minimum deposit amount is " . number_format($min_deposit, 2) . " USD.";
        }
    }

    if (empty($payment_option) || !in_array($payment_option, $allowed_payment_options)) {
        $errors[] = "Please select a valid payment option.";
    }

    if (empty($errors)) {
        // Ensure $conn is a valid mysqli object
        if (!$conn || $conn->connect_error) {
            error_log("Database connection error before prepare: " . ($conn ? $conn->connect_error : "Connection object null"));
            $error_message = "Database connection error. Please try again later.";
        } else {
            $sql = "INSERT INTO deposit (email, amount, payment_option, created_at) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);

            if ($stmt === false) {
                // THIS IS LIKELY WHERE YOUR ERROR "An error occurred while preparing your deposit" COMES FROM
                $db_error = $conn->error;
                error_log("Prepare failed: " . $db_error); // Log detailed error for admin
                // Provide more specific feedback if possible, or a general one
                $error_message = "An error occurred while preparing your deposit. Details: " . htmlspecialchars($db_error) . ". Please check server logs or contact support.";
            } else {
                // If 'amount' column in DB is numeric (DECIMAL, FLOAT), 'd' (for double) is better for $amount_float.
                // For now, using "ssss" as per your original code, assuming 'amount' might be VARCHAR.
                $stmt->bind_param("ssss", $email, $amount_str, $payment_option, $date);

                if ($stmt->execute()) {
                    $deposit_recorded = true;
                    $recorded_amount = $amount_float; // Use the validated float amount
                    $recorded_payment_option = $payment_option;
                } else {
                    $exec_error = $stmt->error;
                    error_log("Execute failed: " . $exec_error); // Log detailed error
                    $error_message = "Error recording your deposit. Details: " . htmlspecialchars($exec_error) . ". Please contact support.";
                }
                $stmt->close();
            }
        }
    } else {
        $error_message = implode("<br>", array_map('htmlspecialchars', $errors));
    }
    // $conn is NOT closed here; it's needed for the deposit history table below.
}

// For retaining form values on failed submission
$form_amount = isset($_POST['amount']) ? htmlspecialchars($_POST['amount']) : '';
$form_payment_option = $_POST['payment_option'] ?? 'btc'; // Default to 'btc'

// Assume $user_ip, $data, $status are set in inc/session.php
// $email and $username should also be reliably set in inc/session.php
$user_ip = $user_ip ?? 'N/A';
$user_country = $data['country'] ?? 'N/A';
$account_status = $status ?? 'N/A'; 

// Placeholder for balance - this should be fetched dynamically in session.php or here
$current_balance_display = "447,583.00"; // Example: replace with dynamic value like number_format($account_balance, 2)
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Account Dashboard - Deposit Fund</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.3.2/css/ionic.min.css">
    <link rel="shortcut icon" href="logo1.png" />
   <style>
  /* --- Basic Reset & Defaults --- */
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html { scroll-behavior: smooth; height: 100%; }
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #000; color: #333; line-height: 1.6;
        overflow-x: hidden; min-height: 100%; position: relative;
    }
    a { text-decoration: none; color: inherit; }
    ul { list-style: none; }

    /* --- Sidebar Variables --- */
    :root {
        --primary-color: #3d85c6;
        --card-bg: linear-gradient(145deg, #1e2334, #161925);
        --card-shadow: 0 4px 15px rgba(0,0,0,0.3);
        --text-muted: #8e9aaf;
        --text-light: #ffffff;
        --accent-green: #00ff88;
        --accent-blue: #00d2ff;
        --accent-red: #ff6384;
        --accent-gold: #f1c40f; 
    }

    /* --- Layout & Sidebar CSS --- */
    .dashboard-container { display: flex; min-height: 100vh; position: relative; }
    
    .sidebar {
        width: 250px; background-color: #2c3e50; color: #ecf0f1;
        display: flex; flex-direction: column; transition: transform 0.3s ease;
        position: sticky; top: 0; height: 100vh; z-index: 1000; flex-shrink: 0;
    }
    
    .sidebar-header { 
        padding: 20px 10px; text-align: center; border-bottom: 1px solid #34495e; 
        flex-shrink: 0; position: relative; 
    }
    
    .brand-logo {
        width: 50px; height: 50px;
        background: linear-gradient(135deg, #f1c40f, #f39c12);
        color: #fff; font-size: 24px; line-height: 50px; text-align: center;
        border-radius: 50%; margin: 0 auto 10px auto;
        box-shadow: 0 0 15px rgba(241, 196, 15, 0.5); display: block;
    }

    .sidebar-header h2 { 
        font-size: 1.1em; font-weight: 600; white-space: nowrap; 
        overflow: hidden; opacity: 1; margin: 0; color: #ecf0f1;
    }
    
    .mobile-close-btn {
        display: none; position: absolute; right: 15px; top: 15px; font-size: 1.5em; cursor: pointer; color: #fff;
    }

    .sidebar-nav { flex-grow: 1; overflow-y: auto; overflow-x: hidden; }
    .sidebar-nav ul { padding-top: 20px; }
    .sidebar-nav li { margin-bottom: 5px; position: relative; }
    .sidebar-nav a { display: flex; align-items: center; padding: 12px 20px; color: #bdc3c7; transition: 0.3s; white-space: nowrap; overflow: hidden; position: relative; }
    .sidebar-nav a i:first-child { margin-right: 15px; font-size: 1.3em; width: 20px; text-align: center; flex-shrink: 0; }
    .sidebar-nav a:hover, .sidebar-nav a.active { background-color: #34495e; color: #ffffff; }
    
    /* --- DROPDOWN / SUBMENU CSS (FIX) --- */
    .has-submenu > a .submenu-indicator {
        margin-left: auto; /* Push to right */
        font-size: 0.8em;
        transition: transform 0.3s ease;
    }
    
    /* Hide submenu by default */
    .submenu {
        background-color: #233040; /* Darker background for contrast */
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease-out;
    }
    
    .submenu a {
        padding-left: 55px; /* Indent child links */
        font-size: 0.9em;
    }
    
    /* Open State */
    .has-submenu.open > .submenu {
        max-height: 300px; /* Arbitrary height larger than content */
    }
    
    .has-submenu.open > a .submenu-indicator {
        transform: rotate(180deg);
    }

    /* --- Main Content --- */
    .main-content {
        flex-grow: 1; display: flex; flex-direction: column; position: relative;
        height: 100vh; overflow-y: auto; background-color: #02101c;
        width: 100%;
    }
    .main-header {
        background-color: #02101c; padding: 15px 30px; display: flex; justify-content: space-between;
        align-items: center; border-bottom: 1px solid #1f293a; position: sticky; top: 0; z-index: 900;
    }
    
    .menu-toggle { 
        color: #fff; font-size: 2em; display: none; cursor: pointer; 
        background: none; border: none; padding: 0; line-height: 1;
    }


    /* --- Page Content --- */
    .page-content {
        padding: 30px;
        flex-grow: 1; /* Allows content below header to fill remaining space */
        /* Background is set directly on main-content now */
    }

    /* Generic H2 */
    h2 { font-size: 1.6em; margin-bottom: 20px; color: #2c3e50; font-weight: 600; }


    /* === NEW STYLES for Account Statement & Deposit Fund === */

    .content-split-wrapper {
        display: flex;
        gap: 30px; /* Space between the two columns */
        flex-wrap: wrap; /* Stack on smaller screens */
    }

    .account-statement-section,
    .deposit-fund-section {
        background-color: #ffffff;
        padding: 25px 30px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.07);
        flex-grow: 1; /* Allow sections to grow */
    }

    /* Specific width control (adjust as needed) */
    .account-statement-section {
        flex-basis: 35%; /* Approx width for statement */
        min-width: 300px; /* Prevent shrinking too much */
    }

    .deposit-fund-section {
        flex-basis: 55%; /* Approx width for deposit */
        min-width: 350px; /* Prevent shrinking too much */
    }

    /* Account Statement Specific Styles */
    .account-statement-section h2 {
        font-size: 1.3em;
        margin-bottom: 25px;
        border-bottom: 1px solid #eee;
        padding-bottom: 15px;
        color: #34495e;
    }

    .statement-item {
        display: flex;
        justify-content: space-between;
        padding: 12px 0;
        border-bottom: 1px dashed #eee;
    }
    .statement-item:last-child { border-bottom: none; }
    .statement-label { color: #7f8c8d; font-weight: 500; }
    .statement-value { color: #2c3e50; font-weight: 600; }
    .statement-value.balance { color: #27ae60; font-size: 1.1em; }

    /* Deposit Fund Specific Styles */
    .deposit-fund-section h2 {
        font-size: 1.3em;
        margin-bottom: 25px;
        border-bottom: 1px solid #eee;
        padding-bottom: 15px;
        color: #34495e;
    }

    .form-group { margin-bottom: 20px; }
    .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #555; }
    .form-control {
        width: 100%; padding: 12px 15px; border: 1px solid #dcdde1; border-radius: 5px;
        font-size: 1em; transition: border-color 0.3s ease;
    }
    .form-control:focus { outline: none; border-color: #3498db; }

    .payment-options {
        display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: 10px; margin-top: 10px;
    }
    .payment-option-item { position: relative; }
    .payment-option-item input[type="radio"] { position: absolute; opacity: 0; }
    .payment-option-label {
        display: flex; flex-direction: column; align-items: center; justify-content: center;
        padding: 15px 10px; border: 2px solid #f1f2f6; border-radius: 8px; cursor: pointer;
        transition: all 0.3s ease; text-align: center; background-color: #fafafa;
    }
    .payment-option-label i { font-size: 1.8em; margin-bottom: 8px; color: #7f8c8d; }
    .payment-option-label span { font-size: 0.85em; font-weight: 600; color: #7f8c8d; text-transform: uppercase; }

    .payment-option-item input[type="radio"]:checked + .payment-option-label {
        border-color: #3498db; background-color: #ebf5fb;
    }
    .payment-option-item input[type="radio"]:checked + .payment-option-label i,
    .payment-option-item input[type="radio"]:checked + .payment-option-label span {
        color: #3498db;
    }

    .btn-deposit {
        width: 100%; padding: 14px; background-color: #3498db; color: #fff;
        border: none; border-radius: 5px; font-size: 1.1em; font-weight: 600;
        cursor: pointer; transition: background-color 0.3s ease; margin-top: 10px;
    }
    .btn-deposit:hover { background-color: #2980b9; }

    /* Deposit History Table */
    .history-section { margin-top: 40px; }
    .history-section h2 { font-size: 1.4em; margin-bottom: 20px; color: #2c3e50; }
    .table-container { background-color: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.07); overflow: hidden; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 15px 20px; text-align: left; border-bottom: 1px solid #f1f2f6; }
    th { background-color: #02101c; color: #fff; font-weight: 600; text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.5px; }
    
    .status { padding: 5px 10px; border-radius: 20px; font-size: 0.8em; font-weight: 600; text-transform: uppercase; }
    .status.pending { background-color: #fef9e7; color: #f39c12; }
    .status.completed { background-color: #eafaf1; color: #27ae60; }
    .status.failed { background-color: #fdedec; color: #e74c3c; }

    /* --- MODAL STYLES --- */
    .modal {
        display: none; /* Hidden by default */
        position: fixed;
        z-index: 2000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
    }

    .modal-content {
        background-color: #fefefe;
        margin: 5% auto;
        padding: 0;
        border: none;
        width: 500px;
        max-width: 95%;
        border-radius: 8px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        animation: modalFadeIn 0.3s;
    }

    @keyframes modalFadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .modal-header {
        padding: 15px 20px;
        background-color: #2c3e50;
        color: white;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-header h2 {
        margin: 0;
        font-size: 1.4em;
        color: white; /* Ensure h2 color is white */
    }

    .modal-close-button {
        color: white;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        padding: 0 5px;
        line-height: 1;
    }
    .modal-close-button:hover,
    .modal-close-button:focus {
        color: #eee;
        text-decoration: none;
    }

    .modal-body {
        padding: 20px;
        line-height: 1.7;
    }
    .modal-body p {
        margin-bottom: 10px;
    }
    .modal-body strong {
        color: #2c3e50;
    }
    .modal-body ul {
        list-style: disc;
        padding-left: 20px;
        margin-bottom: 10px;
    }
     .modal-body ul li {
        margin-bottom: 5px;
    }
    .modal-body img.qr-code-image { /* Specific class for QR codes */
        max-width: 150px;
        height: auto;
        display: block;
        margin: 10px auto;
        border: 1px solid #ddd;
        padding: 5px;
        border-radius: 4px;
    }

    .modal-footer {
        padding: 15px 20px;
        background-color: #f9f9f9;
        border-bottom-left-radius: 7px;
        border-bottom-right-radius: 7px;
        text-align: right;
        border-top: 1px solid #e5e5e5;
    }
    .modal-footer .btn { /* Style buttons in footer */
        margin-left: 10px;
    }
    /* --- END MODAL STYLES --- */

    /* --- NEW SELECTABLE & COPY STYLES --- */
    .copy-wrapper {
        display: flex;
        align-items: center;
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 8px 12px;
        margin: 10px 0;
        gap: 10px;
    }
    .copyable-text {
        font-family: monospace;
        font-size: 1.1em;
        color: #2c3e50;
        word-break: break-all;
        user-select: all; /* Allows easy highlighting */
        flex-grow: 1;
    }
    .copy-btn {
        background: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 4px 10px;
        cursor: pointer;
        font-size: 0.85em;
        white-space: nowrap;
        transition: background 0.2s;
    }
    .copy-btn:hover { background: #2980b9; }
    .copy-btn.copied { background: #27ae60; }
    /* --- END SELECTABLE & COPY STYLES --- */


    /* --- Responsive Design --- */
    @media (max-width: 768px) {
        .sidebar {
            position: fixed; left: -250px; top: 0; height: 100vh; width: 250px;
            transition: left 0.3s ease;
            box-shadow: 2px 0 5px rgba(0,0,0,0.2);
            overflow: hidden; /* Hide tooltips on mobile */
        }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar {
            left: 0;
            width: 250px; /* Ensure width is restored */
        }
        /* Restore text and icons visibility for mobile when sidebar is open */
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-header h2 { opacity: 1; visibility: visible; }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-header .logo { max-width: 80px; } /* Adjusted from 80% to a fixed px or keep as % if preferred */
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-nav a span { opacity: 1; width: auto; pointer-events: auto; visibility: visible; transition: opacity 0.2s ease 0.1s, visibility 0s linear 0s, width 0s linear 0s; }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-nav a i:first-child { margin-right: 15px; }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-nav a { justify-content: flex-start; padding: 12px 20px; overflow: hidden; }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .has-submenu > a .submenu-indicator { display: block; }
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .submenu { display: block; /* Ensure submenu is block to allow max-height transition */ }


        /* Prevent ALL desktop hover/tooltip effects on mobile */
        .sidebar .has-submenu:hover > .submenu,
        #sidebar-toggle:checked ~ .dashboard-container .sidebar .sidebar-nav a:hover::after {
            display: none !important; /* Hides the element */
            opacity: 0 !important;
            visibility: hidden !important;
            max-height: 0 !important; /* Collapses submenu */
        }
        /* Reset submenu indicator on hover for non-open items */
        .sidebar .has-submenu:not(.open):hover > a .submenu-indicator {
             transform: translateY(-50%) rotate(0deg) !important;
        }
        /* Ensure open submenus remain open on hover (for touch persistence or accidental hovers) */
        .sidebar .has-submenu.open:hover > .submenu {
            max-height: var(--submenu-scroll-height, 500px) !important; /* Use a variable or sufficiently large value */
             display: block !important;
             opacity: 1 !important;
             visibility: visible !important;
        }
         .sidebar .has-submenu.open:hover > a .submenu-indicator {
            transform: translateY(-50%) rotate(180deg) !important; /* Keep open rotation */
        }

        .main-content { } /* No specific change needed here unless content overflows in new ways */
        .sidebar-toggler-wrapper { display: none; } /* Hide desktop toggler */
        .menu-toggle { display: block; } /* Show mobile toggler */
        .header-left h1 { font-size: 1.2em; margin-left: 10px; }
        .main-header { padding: 10px 15px; }
        .page-content { padding: 15px; }

        /* Responsive adjustments for split content */
        .content-split-wrapper {
            flex-direction: column; /* Stack columns */
            gap: 15px; /* Reduce gap */
        }
        .account-statement-section,
        .deposit-fund-section {
            flex-basis: auto; /* Reset basis */
            min-width: 0; /* Reset min-width */
            padding: 20px 15px; /* Adjust padding */
        }
         .account-statement-section h2,
         .deposit-fund-section h2 {
            font-size: 1.2em; /* Slightly smaller headings on mobile */
            margin-bottom: 15px;
         }

        /* Adjust table styles if needed on mobile */
         .table-container { box-shadow: none; background: none; margin-top: 15px; border-radius: 0; overflow-x: visible;}
         table { border: none; border-collapse: separate; border-spacing: 0 10px; margin-top: 0; background-color: transparent;}
         table, thead, tbody, th, td, tr { display: block; }
         thead { display: none; } /* Hide table header on mobile */
         tr {
            border: 1px solid #e0e0e0; margin-bottom: 15px; border-radius: 8px;
            background-color: #ffffff; /* White background for each card-like row */
            box-shadow: 0 1px 3px rgba(0,0,0,0.08);
            padding: 15px;
         }
         td {
            border: none; border-bottom: 1px solid #f0f0f0;
            position: relative; padding: 10px 0 10px 40%; /* Increased padding-left for label */
            text-align: right; white-space: normal; /* Allow text to wrap */
            display: flex; justify-content: space-between; align-items: center;
            min-height: 30px;
         }
         td:last-child { border-bottom: none; }
         td::before {
            content: attr(data-label); position: absolute; left: 0; width: 38%; /* Adjusted width */
            padding-right: 10px; white-space: nowrap; font-weight: bold;
            text-align: left; color: #555; font-size: 0.9em;
         }
         /* Specific handling for action buttons if they exist */
         td[data-label="Actions"] { padding-left: 0; text-align: left; display: block; padding-top: 10px; }
         td[data-label="Actions"]::before { display: none; }
         td[data-label="Actions"] button { margin: 0 5px 5px 0; }

         /* Responsive Pagination (if you add it later) */
         .pagination { flex-direction: column; align-items: stretch; background: none; box-shadow: none; padding: 10px 0; }
         .pagination span { margin-bottom: 10px; text-align: center; margin-right: 0; }
         .pagination button { width: 100%; margin-left: 0; margin-bottom: 5px; }
         .controls { flex-direction: column; align-items: stretch; }
         .controls > * { width: 100%; margin-bottom: 10px; max-width: none; }
         .controls button { margin-right: 0; }

         /* Modal Responsive */
        .modal-content {
            width: 90%;
            margin: 10% auto;
        }
    } /* End Media Query */

    /* Error message styling */
    .error-container {
        background-color: #f8d7da;
        color: #721c24;
        padding: 10px 15px;
        border: 1px solid #f5c6cb;
        border-radius: 4px;
        margin-bottom: 20px;
        word-break: break-word; /* To wrap long error messages */
    }

    /* INSTRUCTION BOX STYLE */
    .instruction-container {
        background-color: #d1ecf1;
        color: #0c5460;
        padding: 15px;
        border: 1px solid #bee5eb;
        border-radius: 4px;
        margin-bottom: 25px; /* Spacing below the box */
        font-size: 0.95em;
    }
    .instruction-container h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #0c5460;
        font-weight: 600;
    }
    .instruction-container ul {
        margin: 0;
        padding-left: 20px;
        list-style: disc;
    }
    .instruction-container li {
        margin-bottom: 5px;
    }

    </style>
</head>
<body>

    
    <div class="dashboard-container">
        <!-- Sidebar -->
          <!-- Sidebar -->
      <?php 
include('inc/sidebar.php');
?> 

        <!-- Main Content -->
        <main class="main-content">
            <header class="main-header">
                <div class="header-left">
                    <label for="sidebar-toggle" class="menu-toggle"><i class="ion-navicon"></i></label>
                    <h2 style="color:white;">Deposit Fund</h2>
                </div>
                <div class="header-right">
                    <div class="admin-info">
                        <span>Welcome, <strong><?php echo htmlspecialchars($username ?? 'User'); ?></strong></span>
                        <img src="https://via.placeholder.com/40" alt="Avatar" class="avatar">
                    </div>
                </div>
            </header>

            <div class="page-content">
                
                <?php if (!empty($error_message)): ?>
                    <div class="error-container">
                        <?php echo $error_message; ?>
                    </div>
                <?php endif; ?>

                <div class="instruction-container">
                    <h4>How to Deposit Funds</h4>
                    <ul>
                        <li>Enter the amount you wish to deposit (Minimum $100.00).</li>
                        <li>Select your preferred payment method.</li>
                        <li>Click "Proceed to Deposit" to record your request.</li>
                        <li>A popup will appear with the specific wallet address . Complete the transfer externally.</li>
                        <li>Once the transfer is confirmed on the network   your balance will be updated.</li>
                    </ul>
                </div>

                <div class="content-split-wrapper">
                    <!-- Left Side: Account Statement -->
                    <section class="account-statement-section">
                        <h2>Account Statement</h2>
                        <div class="statement-item">
                            <span class="statement-label">Account Name:</span>
                            <span class="statement-value"><?php echo htmlspecialchars($username ?? 'N/A'); ?></span>
                        </div>
                        <div class="statement-item">
                            <span class="statement-label">Account Email:</span>
                            <span class="statement-value"><?php echo htmlspecialchars($email ?? 'N/A'); ?></span>
                        </div>
                        <div class="statement-item">
                            <span class="statement-label">Account Status:</span>
                            <span class="statement-value"><?php echo htmlspecialchars($account_status); ?></span>
                        </div>
                        <div class="statement-item">
                            <span class="statement-label">Country:</span>
                            <span class="statement-value"><?php echo htmlspecialchars($user_country); ?></span>
                        </div>
                        <div class="statement-item">
                            <span class="statement-label">IP Address:</span>
                            <span class="statement-value"><?php echo htmlspecialchars($user_ip); ?></span>
                        </div>
                        <div class="statement-item" style="margin-top: 15px; border-top: 2px solid #eee; padding-top: 15px;">
                            <span class="statement-label">Current Balance:</span>
                            <span class="statement-value balance">$<?php echo htmlspecialchars($earnings); ?></span>
                        </div>
                    </section>

                    <!-- Right Side: Deposit Form -->
                    <section class="deposit-fund-section">
                        <h2>New Deposit Request</h2>
                        <form action="" method="POST">
                            <div class="form-group">
                                <label for="amount">Deposit Amount (USD)</label>
                                <input type="number" name="amount" id="amount" class="form-control" placeholder="0.00" step="0.01" min="100" value="<?php echo $form_amount; ?>" required>
                            </div>

                            <div class="form-group">
                                <label>Select Payment Method</label>
                                <div class="payment-options">
                                    <div class="payment-option-item">
                                        <input type="radio" name="payment_option" id="pay_btc" value="btc" <?php echo ($form_payment_option == 'btc') ? 'checked' : ''; ?>>
                                        <label for="pay_btc" class="payment-option-label">
                                            <i class="ion-social-bitcoin"></i>
                                            <span>BTC</span>
                                        </label>
                                    </div>
                                  <!--  <div class="payment-option-item">
                                        <input type="radio" name="payment_option" id="pay_eth" value="eth" <?php echo ($form_payment_option == 'eth') ? 'checked' : ''; ?>>
                                        <label for="pay_eth" class="payment-option-label">
                                            <i class="ion-social-usd-outline"></i>
                                            <span>ETH</span>
                                        </label>
                                    </div> -->
                                    <div class="payment-option-item">
                                        <input type="radio" name="payment_option" id="pay_ltc" value="ltc" <?php echo ($form_payment_option == 'ltc') ? 'checked' : ''; ?>>
                                        <label for="pay_ltc" class="payment-option-label">
                                            <i class="ion-social-usd"></i>
                                            <span>LTC</span>
                                        </label>
                                    </div>
                                    <div class="payment-option-item">
                                        <input type="radio" name="payment_option" id="pay_usdt" value="usdt" <?php echo ($form_payment_option == 'usdt') ? 'checked' : ''; ?>>
                                        <label for="pay_usdt" class="payment-option-label">
                                            <i class="ion-social-tux"></i>
                                            <span>USDT</span>
                                        </label>
                                    </div>
                                   
                                </div>
                            </div>

                            <button type="submit" name="submit" class="btn-deposit">Proceed to Deposit</button>
                        </form>
                    </section>
                </div>

                <!-- Deposit History Section -->
                <div class="history-section">
                   <h2>Recent Deposit History</h2>
                   <div class="table-container">
                       <table>
                           <thead>
                               <tr>
                                   <th>Date</th>
                                   <th>User</th>
                                   <th>Type</th>
                                   <th>Amount (USD)</th>
                                   <th>Status</th>
                               </tr>
                           </thead>
                           <tbody>
                               <?php
                               if (isset($conn) && !empty($email)) {
                                   $history_sql = "SELECT amount, payment_option, created_at, email, status FROM deposit WHERE email = ? ORDER BY created_at DESC LIMIT 10";
                                   $history_stmt = $conn->prepare($history_sql);

                                   if ($history_stmt) {
                                       $history_stmt->bind_param("s", $email);
                                       $history_stmt->execute();
                                       $result = $history_stmt->get_result();

                                       if ($result->num_rows > 0) {
                                           while ($row = $result->fetch_assoc()) {
                                               $deposit_status = !empty($row['status']) ? $row['status'] : 'Pending'; // Default to Pending if status column is empty
                                               $status_class = strtolower(htmlspecialchars($deposit_status)); // For CSS class e.g., 'pending', 'completed'
                                               echo "<tr style=\"background-color: #02101c;color: #fff;\">";
                                               echo "<td data-label=\"Date\">" . htmlspecialchars(date("Y-m-d H:i", strtotime($row['created_at']))) . "</td>"; // Format date
                                               echo "<td data-label=\"User\">" . htmlspecialchars($row['email']) . "</td>";
                                               echo "<td data-label=\"Type\">" . htmlspecialchars(strtoupper($row['payment_option'])) . "</td>";
                                               echo "<td data-label=\"Amount (USD)\">" . htmlspecialchars(number_format(floatval($row['amount']), 2)) . "</td>";
                                               echo "<td data-label=\"Status\"><span class=\"status " . $status_class . "\">" . htmlspecialchars($deposit_status) . "</span></td>";
                                               echo "</tr>";
                                           }
                                       } else {
                                           echo "<tr style=\"background-color: #02101c;color: #fff;\"><td colspan=\"5\" style=\"text-align:center;\">No deposit history found.</td></tr>";
                                       }
                                       $history_stmt->close();
                                   } else {
                                       echo "<tr style=\"background-color: #02101c;color: #fff;\"><td colspan=\"5\" style=\"text-align:center;\">Error fetching deposit history: " . htmlspecialchars($conn->error) . "</td></tr>";
                                       error_log("History query prepare failed: " . $conn->error);
                                   }
                               } else {
                                    echo "<tr style=\"background-color: #02101c;color: #fff;\"><td colspan=\"5\" style=\"text-align:center;\">Cannot display history. DB connection or user session issue.</td></tr>";
                               }
                               ?>
                           </tbody>
                       </table>
                   </div>
                </div>
            </div>
        </main>
    </div>

    <div id="paymentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal-title">Payment Information</h2>
                <span class="modal-close-button">×</span>
            </div>
            <div class="modal-body" id="modal-payment-details">
                <p>Loading payment details...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="modal-close-btn-footer">Close</button>
            </div>
        </div>
    </div>

    <script>
        // Global copy function
        function copyToClipboard(text, btn) {
            navigator.clipboard.writeText(text).then(() => {
                const originalText = btn.innerText;
                btn.innerText = 'Copied!';
                btn.classList.add('copied');
                setTimeout(() => {
                    btn.innerText = originalText;
                    btn.classList.remove('copied');
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            const sidebarToggleCheckbox = document.getElementById('sidebar-toggle');
            const sidebar = document.getElementById('sidebar');
            const sidebarNav = sidebar?.querySelector('.sidebar-nav');

            if (sidebarNav && sidebarToggleCheckbox) {
                sidebarNav.addEventListener('click', (event) => {
                    const link = event.target.closest('a');
                    if (link && link.getAttribute('href') && link.getAttribute('href') !== '#') {
                        if (window.innerWidth <= 768 && sidebarToggleCheckbox.checked) {
                           sidebarToggleCheckbox.checked = false;
                        }
                    }
                });
            }

            if (sidebar && sidebarToggleCheckbox) {
                sidebar.addEventListener('click', function(event) {
                    const parentLink = event.target.closest('.has-submenu > a.nav-link');
                    if (parentLink && window.innerWidth <= 768 && sidebarToggleCheckbox.checked && parentLink.getAttribute('href') === '#') {
                        event.preventDefault();
                        const parentLi = parentLink.closest('.has-submenu');
                        const submenu = parentLi?.querySelector('.submenu');

                        if (parentLi && submenu) {
                            const isOpen = parentLi.classList.contains('open');
                            sidebar.querySelectorAll('.has-submenu.open').forEach(otherLi => {
                                if (otherLi !== parentLi) {
                                    otherLi.classList.remove('open');
                                    const otherSubmenu = otherLi.querySelector('.submenu');
                                    if (otherSubmenu) otherSubmenu.style.maxHeight = null;
                                }
                            });

                            if (isOpen) {
                                submenu.style.maxHeight = null;
                                parentLi.classList.remove('open');
                            } else {
                                parentLi.classList.add('open');
                                submenu.style.maxHeight = submenu.scrollHeight + "px";
                                submenu.style.setProperty('--submenu-scroll-height', submenu.scrollHeight + "px");
                            }
                        }
                    }
                });
             }

            const mobileMediaQuery = window.matchMedia('(max-width: 768px)');
            function handleMobileSidebarClass() {
                if(!sidebar || !sidebarToggleCheckbox) return;
                if (mobileMediaQuery.matches && sidebarToggleCheckbox.checked) {
                    sidebar.classList.add('mobile-forced-open');
                } else {
                    sidebar.classList.remove('mobile-forced-open');
                }
                 if (mobileMediaQuery.matches && !sidebarToggleCheckbox.checked) {
                    sidebar.querySelectorAll('.has-submenu.open').forEach(li => {
                        li.classList.remove('open');
                        const submenu = li.querySelector('.submenu');
                        if(submenu) submenu.style.maxHeight = null;
                    });
                 }
            }
            if (sidebarToggleCheckbox) {
                handleMobileSidebarClass();
                sidebarToggleCheckbox.addEventListener('change', handleMobileSidebarClass);
            }
            mobileMediaQuery.addEventListener('change', handleMobileSidebarClass);
        });
    </script>

    <?php if ($deposit_recorded): ?>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const paymentModal = document.getElementById('paymentModal');
        const closeModalSpan = paymentModal?.querySelector('.modal-close-button');
        const modalCloseBtnFooter = document.getElementById('modal-close-btn-footer');
        const modalTitleEl = document.getElementById('modal-title');
        const modalPaymentDetailsEl = document.getElementById('modal-payment-details');

        const amountToDeposit = <?php echo json_encode($recorded_amount); ?>;
        const selectedPaymentValue = <?php echo json_encode($recorded_payment_option); ?>;
        // $username should be defined in session.php and passed from PHP
        const usernameForReference = <?php echo json_encode($username ?? 'YourUsername'); ?>;


        if (!paymentModal || !closeModalSpan || !modalCloseBtnFooter || !modalTitleEl || !modalPaymentDetailsEl) {
            console.error("Modal elements not found. Cannot display payment instructions.");
            return;
        }

        let title = "Payment Instructions";
        let detailsHtml = "";
        // !!! REPLACE WITH YOUR ACTUAL WALLET ADDRESSES AND BANK DETAILS !!!
        const btcAddress = "1MLLzGYaQ49hKqQesM9VtjsS6dgrqKiLtG";
        const ethAddress = " "; // (Ensure ERC-20)
        const usdtTrc20Address = "TELy6fsDeoBxCJUJZ2B5ULDMxyzo1nvuji"; // (Tron Network)
        const usdtErc20Address = "0xdb18b94a0d65bd8d51dda1c983088fd85cf2c339"; // Placeholder
        const ltcAddress = "LaKkkQ2q4VbC7mTQfBkkdrLA2Mme22k6xJ"; // Placeholder
        
        const bankName = "Global Finance Bank";
        const accountName = "Finance Solutions Ltd";
        const accountNumber = "1234567890";
        const swiftBic = "GFBXX44";
        const bankAddress = "123 Finance St, London, UK";

        function getQrCodeImg(data) {
            return `<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(data)}" alt="QR Code" class="qr-code-image">`;
        }

        function createCopyableField(label, value) {
            return `
                <p><strong>${label}:</strong></p>
                <div class="copy-wrapper">
                    <span class="copyable-text">${value}</span>
                    <button class="copy-btn" onclick="copyToClipboard('${value}', this)">Copy</button>
                </div>
            `;
        }

        // Example exchange rates for QR code generation (illustrative, not live)
        const btcRate = 60000; const ethRate = 3000; const ltcRate = 100;

        switch (selectedPaymentValue) {
            case 'btc':
                title = "Bitcoin (BTC) Deposit";
                detailsHtml = `
                    <p>Your deposit request for <strong>${amountToDeposit.toFixed(2)} USD</strong> via Bitcoin has been recorded.</p>
                    <p>Please send the BTC equivalent to the following address:</p>
                    ${createCopyableField('BTC Address', btcAddress)}
                    ${getQrCodeImg(`bitcoin:${btcAddress}${amountToDeposit > 0 && btcRate > 0 ? '?amount=' + (amountToDeposit / btcRate).toFixed(8) : ''}`)}
                    <p><small>Ensure you send only Bitcoin (BTC). The exact BTC amount should be based on the exchange rate at the time of your transaction.</small></p>`;
                break;
            case 'eth':
                title = " Tether (USDTerc20) Deposit";
                detailsHtml = `
                    <p>Your deposit request for <strong>${amountToDeposit.toFixed(2)} USD</strong> via Ethereum has been recorded.</p>
                    <p>Please send the USDT equivalent (ERC-20 Network) to:</p>
                    ${createCopyableField('USDTerc20 Address',usdtAddress)}
                    ${getQrCodeImg(`ethereum:${ethAddress}${amountToDeposit > 0 && ethRate > 0 ? '?value=' + (amountToDeposit / ethRate).toFixed(8) : ''}`)}
                    <p><small>Ensure you send only ETH on the ERC-20 network. The exact ETH amount should be based on the exchange rate at the time of your transaction.</small></p>`;
                break;
            case 'ltc':
                title = "Litecoin (LTC) Deposit";
                detailsHtml = `
                    <p>Your deposit request for <strong>${amountToDeposit.toFixed(2)} USD</strong> via Litecoin has been recorded.</p>
                    <p>Please send the LTC equivalent to:</p>
                    ${createCopyableField('LTC Address', ltcAddress)}
                    ${getQrCodeImg(`litecoin:${ltcAddress}${amountToDeposit > 0 && ltcRate > 0 ? '?amount=' + (amountToDeposit / ltcRate).toFixed(8) : ''}`)}
                    <p><small>Ensure you send only Litecoin (LTC). The exact LTC amount should be based on the exchange rate at the time of your transaction.</small></p>`;
                break;
            case 'usdt':
                title = "Tether (USDTtron) Deposit";
                detailsHtml = `
                    <p>Your deposit request for <strong>${amountToDeposit.toFixed(2)} USD</strong> via Tether (USDT) has been recorded.</p>
                    <p>Please send <strong>${amountToDeposit.toFixed(2)} USDT</strong> to your chosen network address:</p>
                    <hr style="margin: 10px 0;">
                    <p><strong>USDT (TRC-20 Network - Tron):</strong></p>
                    ${createCopyableField('TRC-20 Address', usdtTrc20Address)}
                    ${getQrCodeImg(`${usdtTrc20Address}`)}
                    <hr style="margin: 15px 0;">
                    <p><strong>USDT (ERC-20 Network - Ethereum):</strong></p>
                    ${createCopyableField('ERC-20 Address', usdtErc20Address)}
                    ${getQrCodeImg(`${usdtErc20Address}`)}
                    <hr style="margin: 10px 0;">
                    <p><small><strong>Crucial:</strong> Select the correct network. Sending to the wrong network or a different coin will result in permanent loss.</small></p>`;
                break;
            case 'bank':
                title = "Bank Transfer Deposit";
                const reference = `Deposit_${usernameForReference}_${new Date().getTime()}`;
                detailsHtml = `
                    <p>Your deposit request for <strong>${amountToDeposit.toFixed(2)} USD</strong> via Bank Transfer has been recorded.</p>
                    <p>Please use the following details for your transfer of <strong>${amountToDeposit.toFixed(2)} USD</strong>:</p>
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;">
                        ${createCopyableField('Bank Name', bankName)}
                        ${createCopyableField('Account Name', accountName)}
                        ${createCopyableField('Account Number', accountNumber)}
                        ${createCopyableField('SWIFT/BIC', swiftBic)}
                        ${createCopyableField('Reference/Memo', reference)}
                    </div>
                    <p><small>Include the exact reference. Deposits may take 1-3 business days. Contact support with questions.</small></p>`;
                break;
            default:
                detailsHtml = "<p>Selected payment option details are not available. Please contact support.</p>";
        }

        modalTitleEl.textContent = title;
        modalPaymentDetailsEl.innerHTML = detailsHtml;
        paymentModal.style.display = "block";
        document.body.style.overflow = 'hidden';

        function closeModal() {
            paymentModal.style.display = "none";
            document.body.style.overflow = '';
        }

        closeModalSpan.addEventListener('click', closeModal);
        modalCloseBtnFooter.addEventListener('click', closeModal);
        window.addEventListener('click', (event) => {
            if (event.target === paymentModal) closeModal();
        });
    });
    </script>
    <?php endif; ?>

<?php
// Close the database connection at the very end of the script
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>