<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: login.php');
    exit();
}

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

$database = new Database();
$conn = $database->getConnection();

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Check if user exists, if not redirect to login
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Get recent transactions
$stmt = $conn->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$user_id]);
$recent_transactions = $stmt->fetchAll();

// Get pending transactions
$stmt = $conn->prepare("SELECT SUM(amount) as pending_amount FROM transactions WHERE user_id = ? AND status = 'Pending'");
$stmt->execute([$user_id]);
$pending_data = $stmt->fetch();
$pending_amount = $pending_data['pending_amount'] ?? 0;

// Get transaction volume (total of all transactions)
$stmt = $conn->prepare("SELECT SUM(amount) as total_volume FROM transactions WHERE user_id = ? AND status = 'Completed'");
$stmt->execute([$user_id]);
$volume_data = $stmt->fetch();
$transaction_volume = $volume_data['total_volume'] ?? 0;

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?php echo htmlspecialchars($siteName); ?> Credit</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Google Translator -->
    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({
                pageLanguage: 'en',
                includedLanguages: 'en,es,fr,de,it,pt,ru,ja,ko,zh-CN,zh-TW,ar,hi',
                layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                autoDisplay: false
            }, 'google_translate_element');
        }
    </script>
    <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    
    <style>
        /* Google Translator Styles - Fixed Position Bottom */
        .translator-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 50px;
            padding: 10px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
        }
        
        .translator-container:hover {
            background: rgba(255, 255, 255, 1);
            box-shadow: 0 12px 35px rgba(0, 0, 0, 0.2);
            transform: scale(1.05);
        }
        
        .goog-te-gadget {
            font-family: 'Inter', sans-serif !important;
        }
        
        .goog-te-gadget-simple {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            border: none !important;
            border-radius: 25px !important;
            padding: 12px 20px !important;
            font-size: 0.9rem !important;
            color: white !important;
            cursor: pointer !important;
            transition: all 0.3s ease !important;
            font-weight: 600 !important;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
        }
        
        .goog-te-gadget-simple:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%) !important;
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
            transform: translateY(-2px) !important;
        }
        
        .goog-te-gadget-simple .goog-te-menu-value span:first-child {
            color: white !important;
        }
        
        .goog-te-gadget-simple .goog-te-menu-value span:first-child:after {
            content: " 🌐" !important;
        }
        
        .goog-te-banner-frame {
            display: none !important;
        }
        
        .goog-te-menu2 {
            background: white !important;
            border: 1px solid #ddd !important;
            border-radius: 12px !important;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2) !important;
            margin-top: 10px !important;
            overflow: hidden !important;
        }
        
        .goog-te-menu2-item {
            padding: 12px 20px !important;
            border-bottom: 1px solid #f0f0f0 !important;
            transition: all 0.3s ease !important;
        }
        
        .goog-te-menu2-item:hover {
            background: #f8f9fa !important;
            padding-left: 25px !important;
        }
        
        .goog-te-menu2-item:last-child {
            border-bottom: none !important;
        }
        
        @media (max-width: 768px) {
            .translator-container {
                bottom: 15px;
                right: 15px;
                padding: 8px;
            }
            
            .goog-te-gadget-simple {
                padding: 10px 16px !important;
                font-size: 0.8rem !important;
            }
        }
        
        @media (max-width: 480px) {
            .translator-container {
                bottom: 10px;
                right: 10px;
                padding: 6px;
            }
            
            .goog-te-gadget-simple {
                padding: 8px 12px !important;
                font-size: 0.75rem !important;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Left Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
                            <div class="user-profile-sidebar">
                    <div class="user-avatar-sidebar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn btn-profile">Profile</a>
                    <a href="logout.php" class="btn btn-logout">Logout</a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>MAIN MENU</h3>
                    <ul>
                        <li class="active">
                            <a href="dashboard.php">
                                <i class="fas fa-home"></i>
                                <span>Dashboard</span>
                            </a>
                        </li>
                        <li>
                            <a href="transactions.php">
                                <i class="fas fa-exchange-alt"></i>
                                <span>Transactions</span>
                            </a>
                        </li>
                        <li>
                            <a href="cards.php">
                                <i class="fas fa-credit-card"></i>
                                <span>Cards</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>TRANSFERS</h3>
                    <ul>
                        <li>
                            <a href="transfer.php">
                                <i class="fas fa-paper-plane"></i>
                                <span>Transfer Funds</span>
                            </a>
                        </li>
                        <li>
                            <a href="deposit.php">
                                <i class="fas fa-arrow-down"></i>
                                <span>Deposit</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>SERVICES</h3>
                    <ul>
                        <li>
                            <a href="loan-request.php">
                                <i class="fas fa-hand-holding-usd"></i>
                                <span>Loan Request</span>
                            </a>
                        </li>
                        <li>
                            <a href="irs-refund.php">
                                <i class="fas fa-file-invoice-dollar"></i>
                                <span>IRS Tax Refund</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>ACCOUNT</h3>
                    <ul>
                        <li>
                            <a href="loan-history.php">
                                <i class="fas fa-history"></i>
                                <span>Loan History</span>
                            </a>
                        </li>
                        <li>
                            <a href="settings.php">
                                <i class="fas fa-cog"></i>
                                <span>Settings</span>
                            </a>
                        </li>
                        <li>
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="secure-banking">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure Banking</span>
                </div>
                <div class="version">v1.2.0</div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="dashboard-main">
            <!-- Financial Overview Cards -->
            <div class="overview-cards">
                <div class="overview-card">
                    <div class="card-icon">
                        <i class="fas fa-wallet"></i>
                    </div>
                    <div class="card-content">
                        <h3>Current Balance</h3>
                        <div class="card-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon income">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                    <div class="card-content">
                        <h3>Monthly Income</h3>
                        <div class="card-amount"><?php echo formatCurrency(0, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon outgoing">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                    <div class="card-content">
                        <h3>Monthly Outgoing</h3>
                        <div class="card-amount"><?php echo formatCurrency(0, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon limit">
                        <i class="fas fa-sync-alt"></i>
                    </div>
                    <div class="card-content">
                        <h3>Transaction Limit</h3>
                        <div class="card-amount"><?php echo formatCurrency(500000, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
            </div>

            <!-- Available Balance Card -->
            <div class="balance-card">
                <div class="balance-header">
                    <div class="greeting"><?php echo $greeting; ?> <?php echo htmlspecialchars($user['firstname']); ?></div>
                    <div class="datetime">
                        <div class="time"><?php echo $current_time; ?></div>
                        <div class="date"><?php echo $current_date; ?></div>
                    </div>
                </div>
                
                <div class="balance-main">
                    <div class="balance-label">Available Balance</div>
                    <div class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></div>
                </div>
                
                <div class="account-info">
                    <div class="account-number">
                        <span class="label">Your Account Number</span>
                        <span class="number"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="status-badge">Active</span>
                    </div>
                </div>
                
                <div class="quick-actions">
                    <a href="transactions.php" class="btn btn-transactions">
                        <i class="fas fa-chart-bar"></i>
                        Transactions
                    </a>
                    <a href="deposit.php" class="btn btn-topup">
                        <i class="fas fa-box"></i>
                        Top up
                    </a>
                </div>
            </div>

            <!-- Quick Actions Section -->
            <section class="quick-actions-section">
                <h2>What would you like to do today?</h2>
                <div class="quick-actions-grid">
                    <a href="account-info.php" class="quick-action-card">
                        <div class="action-icon">
                            <i class="fas fa-file-alt"></i>
                        </div>
                        <h3>Account Info</h3>
                    </a>
                    
                    <a href="deposit.php" class="quick-action-card">
                        <div class="action-icon">
                            <i class="fas fa-plus"></i>
                        </div>
                        <h3>Deposit</h3>
                    </a>
                    
                    <a href="transactions.php" class="quick-action-card">
                        <div class="action-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h3>History</h3>
                    </a>
                </div>
            </section>

            <!-- Your Cards Section -->
            <section class="cards-section">
                <div class="section-header">
                    <h2>Your Cards</h2>
                    <a href="cards.php" class="view-all">View all ></a>
                </div>
                <div class="cards-container">
                    <div class="no-cards">
                        <i class="fas fa-credit-card"></i>
                        <p>No cards available</p>
                        <a href="apply-card.php" class="btn btn-primary">Apply for a Card</a>
                    </div>
                </div>
            </section>
        </main>

        <!-- Right Sidebar -->
        <aside class="dashboard-right-sidebar">
            <!-- Account Statistics -->
            <div class="stats-section">
                <h3>Account Statistics</h3>
                
                <div class="stat-item">
                    <div class="stat-icon">
                        <i class="fas fa-file-alt"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">Transaction Limit</div>
                        <div class="stat-value"><?php echo formatCurrency(500000, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="stat-item">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">Pending Transactions</div>
                        <div class="stat-value"><?php echo formatCurrency($pending_amount, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="stat-item">
                    <div class="stat-icon">
                        <i class="fas fa-chart-bar"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">Transaction Volume</div>
                        <div class="stat-value"><?php echo formatCurrency($transaction_volume, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="stat-item">
                    <div class="stat-icon">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">Safe Banking</div>
                        <div class="stat-value">Active</div>
                    </div>
                </div>
            </div>

            <!-- Quick Transfer -->
            <div class="quick-transfer-section">
                <h3>Quick Transfer</h3>
                
                <div class="transfer-option">
                    <div class="transfer-icon">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="transfer-content">
                        <div class="transfer-label">0% Handling charges</div>
                        <a href="transfer.php" class="transfer-link">
                            <i class="fas fa-arrow-right"></i>
                        </a>
                    </div>
                </div>
                
                <div class="transfer-option">
                    <div class="transfer-icon">
                        <i class="fas fa-globe"></i>
                    </div>
                    <div class="transfer-content">
                        <div class="transfer-label">International Transfer</div>
                        <div class="transfer-subtitle">Global reach, 0% fee</div>
                        <a href="international-transfer.php" class="transfer-link">
                            <i class="fas fa-arrow-right"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Recent Transactions -->
            <div class="recent-transactions-section">
                <h3>Recent Transactions</h3>
                <?php if (empty($recent_transactions)): ?>
                    <div class="no-transactions">
                        <p>No recent transactions</p>
                    </div>
                <?php else: ?>
                    <div class="transactions-list">
                        <?php foreach ($recent_transactions as $transaction): ?>
                            <div class="transaction-item">
                                <div class="transaction-icon">
                                    <i class="fas fa-<?php echo $transaction['transaction_type'] === 'Credit' ? 'arrow-down' : 'arrow-up'; ?>"></i>
                                </div>
                                <div class="transaction-content">
                                    <div class="transaction-title"><?php echo htmlspecialchars($transaction['description']); ?></div>
                                    <div class="transaction-date"><?php echo date('M j, Y', strtotime($transaction['created_at'])); ?></div>
                                </div>
                                <div class="transaction-amount <?php echo $transaction['transaction_type'] === 'Credit' ? 'credit' : 'debit'; ?>">
                                    <?php echo $transaction['transaction_type'] === 'Credit' ? '+' : '-'; ?><?php echo formatCurrency($transaction['amount'], $_SESSION['currency'] ?? '$'); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <a href="transactions.php" class="view-all-transactions">View all transactions ></a>
                <?php endif; ?>
            </div>
        </aside>
    </div>

    <!-- Footer -->
    <footer class="dashboard-footer">
        <div class="footer-content">
            <p><?php echo htmlspecialchars($siteName); ?> Credit © 2025 <?php echo htmlspecialchars($siteName); ?> Credit. All rights reserved.</p>
            <div class="footer-links">
                <a href="#">Privacy Policy</a>
                <a href="#">Terms of Service</a>
                <a href="#">Contact Support</a>
            </div>
        </div>
    </footer>

    <!-- Fixed Google Translator -->
    <div id="google_translate_element" class="translator-container"></div>

    <script src="assets/js/dashboard.js"></script>
    <script src="assets/js/logout-confirmation.js"></script>
    
    <!-- Fallback JavaScript for sidebar toggle -->
    <script>
        // Fallback sidebar toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Wait a bit to ensure the main script has loaded
            setTimeout(function() {
                // Check if sidebar toggle is working, if not, initialize fallback
                const sidebar = document.querySelector('.dashboard-sidebar');
                const toggleBtn = document.getElementById('mobileMenuToggle');
                const overlay = document.getElementById('sidebarOverlay');
                
                if (sidebar && toggleBtn) {
                    // Test if the main script initialized the toggle
                    const hasToggleListener = toggleBtn.onclick !== null;
                    
                    if (!hasToggleListener) {
                        console.log('Initializing fallback sidebar toggle...');
                        
                        // Fallback toggle functionality
                        function toggleSidebar() {
                            sidebar.classList.toggle('active');
                            if (overlay) {
                                overlay.classList.toggle('active');
                            }
                            
                            // Prevent body scroll when sidebar is open
                            if (sidebar.classList.contains('active')) {
                                document.body.style.overflow = 'hidden';
                            } else {
                                document.body.style.overflow = '';
                            }
                        }
                        
                        function closeSidebar() {
                            sidebar.classList.remove('active');
                            if (overlay) {
                                overlay.classList.remove('active');
                            }
                            document.body.style.overflow = '';
                        }
                        
                        // Toggle button click event
                        toggleBtn.addEventListener('click', function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            toggleSidebar();
                        });
                        
                        // Overlay click event
                        if (overlay) {
                            overlay.addEventListener('click', function() {
                                closeSidebar();
                            });
                        }
                        
                        // Close sidebar when clicking outside (on mobile)
                        document.addEventListener('click', function(event) {
                            if (window.innerWidth <= 768 && 
                                sidebar.classList.contains('active') && 
                                !sidebar.contains(event.target) && 
                                !toggleBtn.contains(event.target)) {
                                closeSidebar();
                            }
                        });
                        
                        // Close sidebar on escape key
                        document.addEventListener('keydown', function(event) {
                            if (event.key === 'Escape' && sidebar.classList.contains('active')) {
                                closeSidebar();
                            }
                        });
                        
                        console.log('Fallback sidebar toggle initialized');
                    }
                }
            }, 1000);
        });
    </script>
</body>
</html>
