<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/otp.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';
$weeklyLimit = 100000.00;

// Function to generate unique deposit account number
function generateDepositAccountNumber($pdo, $userId)
{
    // Check if user already has a deposit account
    $stmt = $pdo->prepare("SELECT deposit_account_number FROM users WHERE user_id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    if ($user && !empty($user['deposit_account_number'])) {
        return $user['deposit_account_number'];
    }

    // Generate unique deposit account number (10 digits)
    // Format: 10 + user_id padded + random digits
    $prefix = '10';
    $userIdPadded = str_pad($userId, 4, '0', STR_PAD_LEFT);
    $random = rand(1000, 9999);
    $accountNumber = $prefix . $userIdPadded . $random;

    // Ensure it's unique
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE deposit_account_number = ?");
    $stmt->execute([$accountNumber]);
    if ($stmt->fetchColumn() == 0) {
        // Update user with deposit account number
        $updateStmt = $pdo->prepare("UPDATE users SET deposit_account_number = ? WHERE user_id = ?");
        $updateStmt->execute([$accountNumber, $userId]);
        return $accountNumber;
    } else {
        // Recursively generate a new one if duplicate
        return generateDepositAccountNumber($pdo, $userId);
    }
}

// Function to generate routing number (unique per user)
function generateRoutingNumber($pdo, $userId)
{
    // Check if user already has a routing number
    $stmt = $pdo->prepare("SELECT routing_number FROM users WHERE user_id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    if ($user && !empty($user['routing_number'])) {
        return $user['routing_number'];
    }

    // Generate routing number (9 digits)
    // Format: 12 + user_id padded + random
    $prefix = '12';
    $userIdPadded = str_pad($userId, 3, '0', STR_PAD_LEFT);
    $random = rand(1000, 9999);
    $routingNumber = $prefix . $userIdPadded . $random;

    // Update user with routing number
    $updateStmt = $pdo->prepare("UPDATE users SET routing_number = ? WHERE user_id = ?");
    $updateStmt->execute([$routingNumber, $userId]);

    return $routingNumber;
}

// Get user's account and balance
$stmt = $pdo->prepare("SELECT account_id, balance FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$account = $stmt->fetch();

if ($account) {
    $accountId = $account['account_id'];
    $balance = $account['balance'];

    // Generate or retrieve user's deposit account number and routing number
    $depositAccountNumber = generateDepositAccountNumber($pdo, $userId);
    $routingNumber = generateRoutingNumber($pdo, $userId);

    // Total deposited in last 7 days
    $stmt = $pdo->prepare("
        SELECT SUM(amount) FROM transactions 
        WHERE account_id = ? AND type = 'deposit' AND created_at >= NOW() - INTERVAL 7 DAY
    ");
    $stmt->execute([$accountId]);
    $weeklyDeposits = $stmt->fetchColumn() ?: 0;

    // Handle form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['amount'])) {
            $amount = filter_var($_POST['amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

            if ($amount < 100) {
                $error = "Minimum deposit amount is $100.";
            } elseif ($amount <= 0) {
                $error = "Amount must be greater than 0.";
            } elseif (($weeklyDeposits + $amount) > $weeklyLimit) {
                $remaining = $weeklyLimit - $weeklyDeposits;
                $error = "Weekly deposit limit exceeded. You can only deposit $" . number_format($remaining, 2) . " more this week.";
            } else {
                // Get user's email
                $stmt = $pdo->prepare("SELECT email FROM users WHERE user_id = ?");
                $stmt->execute([$userId]);
                $user = $stmt->fetch();
                $email = $user['email'];

                // Generate and send OTP
                if ($email && generateOTP($email)) {
                    $_SESSION['pending_deposit'] = [
                        'account_id' => $accountId,
                        'amount' => $amount
                    ];

                    header("Location: ../otp-verification.php?type=deposit");
                    exit();
                } else {
                    $error = "Failed to send OTP. Please try again later.";
                }
            }
        }
    }
} else {
    $error = "Account not found.";
    $balance = 0;
    $weeklyDeposits = 0;
    $depositAccountNumber = '';
    $routingNumber = '';
}

// Get user account information
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
    FROM users u 
    JOIN accounts a ON u.user_id = a.user_id 
    WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

// Check if the user has a profile picture
$stmt = $pdo->prepare("SELECT profile_picture FROM users WHERE user_id = ?");
$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';

// Get recent deposit transactions
$stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM transactions  
    WHERE type = 'deposit' 
      AND account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
");
$stmt->execute([$userId]);
$totalTransactions = $stmt->fetchColumn();

// Calculate pagination
$transactionsPerPage = 10;
$totalPages = ceil($totalTransactions / $transactionsPerPage);
$currentPage = isset($_GET['page']) ? max(1, min($totalPages, intval($_GET['page']))) : 1;
$offset = ($currentPage - 1) * $transactionsPerPage;

$stmt = $pdo->prepare("
    SELECT * 
    FROM transactions  
    WHERE type = 'deposit' 
      AND account_id = (SELECT account_id FROM accounts WHERE user_id = ?) 
    ORDER BY created_at DESC
    LIMIT ? OFFSET ?
");
$stmt->execute([$userId, $transactionsPerPage, $offset]);
$transactions = $stmt->fetchAll();

// Calculate total deposits for the current month
$stmt = $pdo->prepare("
    SELECT SUM(amount) FROM transactions 
    WHERE account_id = ? 
      AND type = 'deposit' 
      AND MONTH(created_at) = MONTH(CURRENT_DATE()) 
      AND YEAR(created_at) = YEAR(CURRENT_DATE())
");
$stmt->execute([$accountId]);
$monthlyTotal = $stmt->fetchColumn() ?: 0;

// Get the largest deposit
$stmt = $pdo->prepare("
    SELECT MAX(amount) FROM transactions 
    WHERE account_id = ? AND type = 'deposit'
");
$stmt->execute([$accountId]);
$largestDeposit = $stmt->fetchColumn() ?: 0;

// Calculate average weekly deposit (over last 4 weeks)
$stmt = $pdo->prepare("
    SELECT SUM(amount) / 4 FROM transactions 
    WHERE account_id = ? 
      AND type = 'deposit' 
      AND created_at >= NOW() - INTERVAL 28 DAY
");
$stmt->execute([$accountId]);
$averageWeeklyDeposit = $stmt->fetchColumn() ?: 0;
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Oakshire Finance - Deposit Funds</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-avatar i {
            font-size: 40px;
            color: white;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Deposit Card */
        .deposit-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 32px;
            margin-bottom: 32px;
        }

        .balance-card {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 32px;
            color: white;
        }

        .balance-card h3 {
            font-size: 14px;
            font-weight: 500;
            opacity: 0.8;
            margin-bottom: 8px;
        }

        .balance-amount {
            font-size: 36px;
            font-weight: 700;
        }

        /* Bank Details Card - Redesigned */
        .bank-details-card {
            background: linear-gradient(135deg, #0a2540 0%, #0f2e4a 100%);
            border-radius: 28px;
            padding: 28px;
            margin-bottom: 32px;
            color: white;
            position: relative;
            overflow: hidden;
            box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.2);
        }

        .bank-details-card::before {
            content: '';
            position: absolute;
            top: -30%;
            right: -10%;
            width: 250px;
            height: 250px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, transparent 70%);
            border-radius: 50%;
            pointer-events: none;
        }

        .bank-details-card::after {
            content: '';
            position: absolute;
            bottom: -20%;
            left: -5%;
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.05) 0%, transparent 70%);
            border-radius: 50%;
            pointer-events: none;
        }

        /* Header */
        .bank-details-header {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 28px;
            position: relative;
            z-index: 2;
        }

        .header-icon {
            width: 56px;
            height: 56px;
            background: rgba(255, 255, 255, 0.12);
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .header-icon i {
            font-size: 28px;
            color: #ffd966;
        }

        .header-text h3 {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 4px;
            letter-spacing: -0.3px;
        }

        .header-text p {
            font-size: 13px;
            opacity: 0.7;
            margin: 0;
        }

        /* Detail Groups */
        .bank-details-body {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin-bottom: 24px;
            position: relative;
            z-index: 2;
        }

        .detail-group {
            display: flex;
            align-items: flex-start;
            gap: 14px;
            padding: 12px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            transition: all 0.3s ease;
        }

        .detail-group:hover {
            border-bottom-color: rgba(255, 255, 255, 0.2);
            transform: translateX(4px);
        }

        .detail-group.highlight {
            background: rgba(255, 255, 255, 0.05);
            margin: 0 -12px;
            padding: 12px 12px;
            border-radius: 16px;
            border-bottom: none;
        }

        .detail-icon {
            width: 36px;
            height: 36px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .detail-icon i {
            font-size: 18px;
            color: #ffd966;
        }

        .detail-content {
            flex: 1;
        }

        .detail-label {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 500;
            opacity: 0.6;
            display: block;
            margin-bottom: 4px;
        }

        .detail-value {
            font-size: 15px;
            font-weight: 600;
            word-break: break-word;
        }

        .account-number,
        .routing-number {
            font-family: 'Courier New', monospace;
            font-size: 16px;
            letter-spacing: 1px;
            background: rgba(255, 255, 255, 0.1);
            padding: 4px 8px;
            border-radius: 8px;
            display: inline-block;
        }

        .value-with-copy {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }

        .copy-btn {
            background: rgba(255, 255, 255, 0.15);
            border: none;
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            backdrop-filter: blur(4px);
        }

        .copy-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.02);
        }

        .copy-btn:active {
            transform: scale(0.98);
        }

        /* Footer */
        .bank-details-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 20px;
            margin-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
            z-index: 2;
        }

        .info-badge {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            background: rgba(255, 255, 255, 0.08);
            padding: 8px 14px;
            border-radius: 40px;
            backdrop-filter: blur(4px);
        }

        .info-badge i {
            font-size: 14px;
            color: #ffd966;
        }

        .qr-placeholder {
            display: flex;
            align-items: center;
            gap: 8px;
            background: rgba(255, 255, 255, 0.1);
            padding: 8px 16px;
            border-radius: 40px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 13px;
            font-weight: 500;
        }

        .qr-placeholder:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .qr-placeholder i {
            font-size: 16px;
        }

        /* QR Modal (Optional) */
        .qr-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }

        .qr-modal.active {
            display: flex;
        }

        .qr-modal-content {
            background: white;
            border-radius: 24px;
            padding: 24px;
            max-width: 350px;
            width: 90%;
            text-align: center;
            position: relative;
        }

        .qr-modal-content h4 {
            color: #0a2540;
            margin-bottom: 16px;
        }

        .qr-code {
            background: #f8f9fc;
            padding: 20px;
            border-radius: 16px;
            margin: 16px 0;
        }

        .qr-close {
            position: absolute;
            top: 12px;
            right: 16px;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #6c757d;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .bank-details-card {
                padding: 20px;
            }

            .bank-details-header {
                gap: 12px;
                margin-bottom: 20px;
            }

            .header-icon {
                width: 48px;
                height: 48px;
            }

            .header-icon i {
                font-size: 24px;
            }

            .header-text h3 {
                font-size: 18px;
            }

            .header-text p {
                font-size: 11px;
            }

            .detail-group {
                gap: 12px;
                padding: 10px 0;
            }

            .detail-value {
                font-size: 13px;
            }

            .account-number,
            .routing-number {
                font-size: 14px;
            }

            .value-with-copy {
                flex-wrap: wrap;
            }

            .bank-details-footer {
                flex-direction: column;
                gap: 12px;
                align-items: flex-start;
            }

            .qr-placeholder {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .detail-group.highlight {
                margin: 0 -8px;
                padding: 10px 8px;
            }

            .copy-btn {
                padding: 4px 10px;
                font-size: 10px;
            }
        }

        /* Form */
        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input {
            width: 100%;
            padding: 14px 16px;
            font-size: 16px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .btn-primary {
            width: 100%;
            padding: 14px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        /* Summary Cards */
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 32px;
        }

        .summary-card {
            background: var(--white);
            border-radius: 16px;
            padding: 20px;
            border: 1px solid var(--gray-200);
        }

        .summary-card h4 {
            font-size: 12px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .summary-value {
            font-size: 20px;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Progress Bar */
        .progress-bar-container {
            background: var(--gray-200);
            border-radius: 10px;
            height: 8px;
            margin-top: 12px;
            overflow: hidden;
        }

        .progress-bar {
            background: var(--success-green);
            height: 100%;
            border-radius: 10px;
            transition: width 0.3s ease;
        }

        /* Chart Card */
        .chart-card {
            background: var(--white);
            border-radius: 20px;
            padding: 24px;
            border: 1px solid var(--gray-200);
            margin-bottom: 32px;
        }

        .chart-card h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 500px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 13px;
        }

        .badge-positive {
            color: var(--success-green);
            font-weight: 600;
        }

        .btn-download {
            background: none;
            border: none;
            color: var(--primary-blue);
            cursor: pointer;
            font-size: 12px;
        }

        .btn-download:hover {
            text-decoration: underline;
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            padding: 20px;
            flex-wrap: wrap;
        }

        .pagination a {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 36px;
            height: 36px;
            padding: 0 12px;
            border-radius: 8px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            color: var(--gray-700);
            text-decoration: none;
            font-size: 14px;
            transition: var(--transition);
        }

        .pagination a:hover {
            background: var(--gray-100);
        }

        .pagination a.active {
            background: var(--primary-navy);
            border-color: var(--primary-navy);
            color: white;
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .info-note {
            background: #e8f4f8;
            padding: 12px;
            border-radius: 10px;
            font-size: 12px;
            color: var(--primary-blue);
            margin-top: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .balance-amount {
                font-size: 28px;
            }

            .deposit-card {
                padding: 20px;
            }

            .bank-details-card {
                padding: 20px;
            }

            .bank-detail-value {
                font-size: 14px;
                word-break: break-all;
            }

            .summary-grid {
                grid-template-columns: 1fr 1fr;
                gap: 12px;
            }

            .summary-value {
                font-size: 16px;
            }

            .chart-card {
                padding: 16px;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }
        }

        @media (max-width: 480px) {
            .summary-grid {
                grid-template-columns: 1fr;
            }

            .balance-amount {
                font-size: 24px;
            }

            .bank-detail-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .copy-btn {
                margin-left: 0;
                margin-top: 4px;
            }

            .pagination a {
                min-width: 32px;
                height: 32px;
                font-size: 12px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <?php if ($user['profile_picture']): ?>
                        <img src="<?= $profilePic ?>" alt="Profile Picture">
                    <?php else: ?>
                        <i class="fas fa-user-circle"></i>
                    <?php endif; ?>
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="deposit.php" class="nav-link active">
                        <i class="fas fa-arrow-down"></i>
                        <span>Deposit</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="withdraw.php" class="nav-link">
                        <i class="fas fa-arrow-up"></i>
                        <span>Withdraw</span>
                    </a>
                </div>

                <div class="nav-item"><a href="cards.php" class="nav-link"><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item">
                    <a href="transactions.php" class="nav-link">
                        <i class="fas fa-receipt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="investment.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investment</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="profile.php" class="nav-link">
                        <i class="fas fa-user-circle"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Deposit Funds</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Balance Card -->
                <div class="balance-card">
                    <h3>Current Balance</h3>
                    <div class="balance-amount">$<?= number_format($balance, 2) ?></div>
                </div>

                <!-- Bank Details Card - Redesigned -->
                <div class="bank-details-card">
                    <div class="bank-details-header">
                        <div class="header-icon">
                            <i class="fas fa-credit-card"></i>
                        </div>
                        <div class="header-text">
                            <h3>Your Deposit Information</h3>
                            <p>Share these details to receive funds</p>
                        </div>
                    </div>

                    <div class="bank-details-body">
                        <!-- Beneficiary Name -->
                        <div class="detail-group">
                            <div class="detail-icon">
                                <i class="fas fa-user-circle"></i>
                            </div>
                            <div class="detail-content">
                                <span class="detail-label">Beneficiary Name</span>
                                <span class="detail-value"><?= htmlspecialchars($user['full_name']) ?></span>
                            </div>
                        </div>

                        <!-- Deposit Account Number -->
                        <div class="detail-group highlight">
                            <div class="detail-icon">
                                <i class="fas fa-hashtag"></i>
                            </div>
                            <div class="detail-content">
                                <span class="detail-label">Deposit Account Number</span>
                                <div class="value-with-copy">
                                    <span class="detail-value account-number"
                                        id="depositAccount"><?= $depositAccountNumber ?></span>
                                    <button class="copy-btn" onclick="copyToClipboard('depositAccount')">
                                        <i class="fas fa-copy"></i> Copy
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Routing Number -->
                        <div class="detail-group highlight">
                            <div class="detail-icon">
                                <i class="fas fa-route"></i>
                            </div>
                            <div class="detail-content">
                                <span class="detail-label">Routing Number </span>
                                <div class="value-with-copy">
                                    <span class="detail-value routing-number"
                                        id="routingNumber"><?= $routingNumber ?></span>
                                    <button class="copy-btn" onclick="copyToClipboard('routingNumber')">
                                        <i class="fas fa-copy"></i> Copy
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Bank Information -->
                        <div class="detail-group">
                            <div class="detail-icon">
                                <i class="fas fa-building-columns"></i>
                            </div>
                            <div class="detail-content">
                                <span class="detail-label">Bank Name</span>
                                <span class="detail-value">Oakshire Finance</span>
                            </div>
                        </div>



                        <!-- SWIFT/BIC Code -->
                        <div class="detail-group">
                            <div class="detail-icon">
                                <i class="fas fa-globe"></i>
                            </div>
                            <div class="detail-content">
                                <span class="detail-label">SWIFT / BIC Code</span>
                                <span class="detail-value">NXBS PH M1</span>
                            </div>
                        </div>
                    </div>

                    <div class="bank-details-footer">
                        <div class="info-badge">
                            <i class="fas fa-shield-alt"></i>
                            <span>Your unique deposit details - share with confidence</span>
                        </div>
                        <div class="qr-placeholder" id="qrCodeBtn">
                            <i class="fas fa-qrcode"></i>
                            <span>Show QR Code</span>
                        </div>
                    </div>
                </div>

                <!-- Summary Cards -->
                <div class="summary-grid">
                    <div class="summary-card">
                        <h4>This Month</h4>
                        <div class="summary-value">$<?= number_format($monthlyTotal, 2) ?></div>
                    </div>
                    <div class="summary-card">
                        <h4>Largest Deposit</h4>
                        <div class="summary-value">$<?= number_format($largestDeposit, 2) ?></div>
                    </div>
                    <div class="summary-card">
                        <h4>Weekly Average</h4>
                        <div class="summary-value">$<?= number_format($averageWeeklyDeposit, 2) ?></div>
                    </div>
                    <div class="summary-card">
                        <h4>Weekly Limit</h4>
                        <div class="summary-value">$<?= number_format($weeklyDeposits, 2) ?> / $100,000</div>
                        <div class="progress-bar-container">
                            <div class="progress-bar" style="width: <?= min(($weeklyDeposits / 100000) * 100, 100) ?>%">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Deposit Chart -->
                <div class="chart-card">
                    <h3><i class="fas fa-chart-bar"></i> Monthly Deposit History</h3>
                    <div id="monthlyDepositChart" style="height: 350px;"></div>
                </div>

                <!-- Recent Deposit History -->
                <div class="chart-card" style="padding: 0; overflow: hidden;">
                    <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                        <h3><i class="fas fa-history"></i> Recent Deposit History</h3>
                    </div>
                    <div class="table-container" style="margin: 0; border-radius: 0;">
                        <?php if (empty($transactions)): ?>
                            <div style="text-align: center; padding: 48px; color: var(--gray-500);">
                                <i class="fas fa-receipt" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                                <p>No deposit transactions found</p>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Transaction ID</th>
                                        <th>Amount</th>
                                        <th>Receipt</th>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $txn): ?>
                                        <tr>
                                            <td><?= date('M d, Y h:i A', strtotime($txn['created_at'])) ?>
                                            <td><code>#<?= $txn['transaction_id'] ?></code>
                                            <td class="badge-positive">+$<?= number_format($txn['amount'], 2) ?>
                                            <td>
                                                <button
                                                    onclick="window.open('generate_receipt.php?transaction_id=<?= $txn['transaction_id'] ?>', '_blank')"
                                                    class="btn-download">
                                                    <i class="fas fa-download"></i> Receipt
                                                </button>


                                            <?php endforeach; ?>
                                </tbody>

                            <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                        <div class="pagination">
                            <?php if ($currentPage > 1): ?>
                                <a href="?page=<?= $currentPage - 1 ?>">&laquo; Prev</a>
                            <?php endif; ?>
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <a href="?page=<?= $i ?>" class="<?= $i == $currentPage ? 'active' : '' ?>"><?= $i ?></a>
                            <?php endfor; ?>
                            <?php if ($currentPage < $totalPages): ?>
                                <a href="?page=<?= $currentPage + 1 ?>">Next &raquo;</a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Copy to clipboard function
        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            const text = element.innerText;

            navigator.clipboard.writeText(text).then(function () {
                // Show temporary success feedback
                const btn = event.target.closest('.copy-btn');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                setTimeout(() => {
                    btn.innerHTML = originalText;
                }, 2000);
            }).catch(function (err) {
                console.error('Could not copy text: ', err);
            });
        }

        // Monthly Deposit Chart
        document.addEventListener("DOMContentLoaded", () => {
            fetch('get_monthly_deposits.php')
                .then(res => res.json())
                .then(data => {
                    const depositMap = data.reduce((acc, { month, total_deposit }) => {
                        acc[month] = parseFloat(total_deposit);
                        return acc;
                    }, {});

                    const year = new Date().getFullYear();
                    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    const totals = monthNames.map((_, idx) => {
                        const key = `${year}-${String(idx + 1).padStart(2, '0')}`;
                        return depositMap[key] || 0;
                    });

                    const options = {
                        chart: {
                            type: 'bar',
                            height: 350,
                            toolbar: { show: true, tools: { download: true } },
                            fontFamily: 'Inter, sans-serif'
                        },
                        plotOptions: {
                            bar: {
                                borderRadius: 8,
                                columnWidth: '50%'
                            }
                        },
                        dataLabels: { enabled: false },
                        colors: ['#1a4d8c'],
                        series: [{ name: 'Deposits', data: totals }],
                        xaxis: {
                            categories: monthNames,
                            labels: { rotate: -45, style: { fontSize: '11px' } }
                        },
                        yaxis: {
                            title: { text: 'Amount ($)' },
                            labels: { formatter: val => '$' + val.toLocaleString() }
                        },
                        tooltip: {
                            y: { formatter: val => '$' + val.toLocaleString() }
                        },
                        responsive: [
                            {
                                breakpoint: 768,
                                options: {
                                    plotOptions: { bar: { columnWidth: '70%' } },
                                    xaxis: { labels: { rotate: -60, style: { fontSize: '10px' } } }
                                }
                            },
                            {
                                breakpoint: 480,
                                options: {
                                    plotOptions: { bar: { columnWidth: '90%' } },
                                    xaxis: { labels: { rotate: -90, style: { fontSize: '9px' } } }
                                }
                            }
                        ]
                    };

                    const chartEl = document.querySelector("#monthlyDepositChart");
                    if (chartEl) {
                        const chart = new ApexCharts(chartEl, options);
                        chart.render();
                    }
                })
                .catch(err => console.error('Error fetching deposit data:', err));
        });
    </script>
</body>

</html>