<?php
$user_id = 1; // Temporary for testing
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#1E40AF">
    <title>Financial Details</title>
    <link rel="manifest" href="/manifest.json">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        body {
            background: linear-gradient(to bottom, #050244 0px, #050244 270px, #E6F0FA 320px, #E6F0FA 100%);
            color: #1F2937;
            min-height: 100vh;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
        }
        header {
            background-color: #1E40AF;
            color: white;
            padding: 1rem;
            position: sticky;
            top: 0;
            z-index: 50;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        header h1 {
            font-size: 1.25rem;
            font-weight: 600;
        }
        #menu-toggle {
            background: none;
            border: none;
            cursor: pointer;
            padding: 0.5rem;
        }
        #menu-toggle svg {
            width: 1.5rem;
            height: 1.5rem;
        }
        #sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 75%;
            max-width: 280px;
            height: 100%;
            background: white;
            z-index: 60;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            box-shadow: 2px 0 8px rgba(0, 0, 0, 0.2);
        }
        #sidebar.open {
            transform: translateX(0);
        }
        #sidebar .p-4 {
            padding: 1rem;
        }
        #sidebar h2 {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1F2937;
            margin-bottom: 1rem;
        }
        #sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            color: #1F2937;
            text-decoration: none;
            border-radius: 0.375rem;
            margin-bottom: 0.25rem;
        }
        #sidebar ul li a:hover {
            background-color: #F3F4F6;
        }
        #sidebar ul li a svg {
            width: 1rem;
            height: 1rem;
            margin-right: 0.5rem;
        }
        #sidebar-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 55;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        #sidebar-overlay.active {
            opacity: 1;
            pointer-events: auto;
        }
        main {
            flex: 1;
            padding: 1rem;
            padding-bottom: 4rem; /* Add padding to avoid overlap with bottom toolbar */
        }
        section {
            background: white;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }
        .content {
            padding: 1rem;
        }
        .content p {
            margin-bottom: 0.5rem;
            font-size: 0.95rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .content p strong {
            font-weight: 600;
            flex: 1;
            text-align: left;
        }
        .content p span {
            flex: 0 0 auto;
            text-align: right;
        }
        .section-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 1.125rem;
            font-weight: 600;
            color: #1F2937;
            padding: 1rem;
            cursor: pointer;
        }
        .section-title svg {
            width: 1rem;
            height: 1rem;
            transition: transform 0.3s ease;
        }
        .section-title.open svg {
            transform: rotate(180deg);
        }
        .section-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }
        .section-content.open {
            max-height: 500px; /* Adjust based on content size */
        }
        .section-content ul {
            list-style: none;
            padding: 0;
        }
        .section-content ul li {
            padding: 0.5rem 0;
            font-size: 0.95rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .bottom-toolbar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 0.5rem 0;
            z-index: 50;
        }
        .toolbar-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #1F2937;
            padding: 0.25rem;
        }
        .toolbar-item svg {
            width: 1.5rem;
            height: 1.5rem;
            margin-bottom: 0.25rem;
        }
        .toolbar-item span {
            font-size: 0.75rem;
            font-weight: 500;
        }
        .text-red-500 {
            color: #EF4444;
        }
        .text-green-500 {
            color: #10B981;
        }
        @media (min-width: 640px) {
            main {
                max-width: 24rem;
                margin-left: auto;
                margin-right: auto;
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>Financial Details</h1>
        <button id="menu-toggle">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path>
            </svg>
        </button>
    </header>

    <div id="sidebar">
        <div class="p-4">
            <h2>Menu</h2>
            <ul>
                <li>
                    <a href="dashboard.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                        </svg>
                        Accounts Dashboard
                    </a>
                </li>
                <li>
                    <a href="personal.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                        </svg>
                        Financial Details
                    </a>
                </li>
                <li>
                    <a href="rm_guitar.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.75 10.5l-3.25-3.25m0 0l-3.25 3.25M12 7.25v10.5m7.5-10.5h-3m-9 0H3.75m12 7.5h-3m-9 0H3.75"></path>
                        </svg>
                        RM Guitar
                    </a>
                </li>
                <li>
                    <a href="update_financials.php" class="flex items-center">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15.828a2 2 0 01-2.828 0l-1.414-1.414a2 2 0 010-2.828L15.172 4z"></path>
                        </svg>
                        Update Financials
                    </a>
                </li>
                <li>
                    <a href="/logout.php" class="flex items-center text-red-500">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                        </svg>
                        Logout
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <div id="sidebar-overlay"></div>

    <main>
        <section>
            <h2 class="section-title">Financial Overview</h2>
            <div class="content">
                <p><strong>Portfolio Value:</strong> <span id="portfolio-value">Loading...</span></p>
                <p><strong>Ethereum Value:</strong> <span id="eth-value">Loading...</span></p>
                <p><strong>Current Account:</strong> <span id="current-account">Loading...</span></p>
                <p><strong>Savings:</strong> <span id="savings">Loading...</span></p>
                <p><strong>External Savings:</strong> <span id="external-savings">Loading...</span></p>
                <p><strong>Money Owed:</strong> <span id="owed-total">Loading...</span></p>
                <p><strong>Portfolio Error:</strong> <span id="portfolio-error">None</span></p>
            </div>
        </section>

        <section>
            <div class="section-title" data-toggle="portfolio-breakdown">
                Portfolio Breakdown
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
            </div>
            <div class="section-content" id="portfolio-breakdown">
                <div class="content">
                    <ul id="top-positions">
                        <!-- Top positions will be populated here -->
                    </ul>
                </div>
            </div>
        </section>

        <section>
            <div class="section-title" data-toggle="credit-card-debts">
                Credit Card Debts
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
            </div>
            <div class="section-content" id="credit-card-debts">
                <div class="content">
                    <p><strong>NatWest:</strong> <span id="natwest-debt">Loading...</span></p>
                    <p><strong>Tesco:</strong> <span id="tesco-debt">Loading...</span></p>
                    <p><strong>Vanquis:</strong> <span id="vanquis-debt">Loading...</span></p>
                    <p><strong>Total:</strong> <span id="credit-card-debts-total">Loading...</span></p>
                </div>
            </div>
        </section>

        <section>
            <div class="section-title" data-toggle="money-owed">
                Money Owed
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
            </div>
            <div class="section-content" id="money-owed">
                <div class="content">
                    <ul id="money-owed-list">
                        <!-- Money owed items will be populated here -->
                    </ul>
                </div>
            </div>
        </section>
    </main>

    <div class="bottom-toolbar">
        <a href="dashboard.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
            </svg>
            <span>Accounts</span>
        </a>
        <a href="personal.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
            </svg>
            <span>Financials</span>
        </a>
        <a href="rm_guitar.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.75 10.5l-3.25-3.25m0 0l-3.25 3.25M12 7.25v10.5m7.5-10.5h-3m-9 0H3.75m12 7.5h-3m-9 0H3.75"></path>
            </svg>
            <span>RM Guitar</span>
        </a>
        <a href="update_financials.php" class="toolbar-item">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15.828a2 2 0 01-2.828 0l-1.414-1.414a2 2 0 010-2.828L15.172 4z"></path>
            </svg>
            <span>Update</span>
        </a>
    </div>

    <script>
        // Sidebar toggle
        const menuToggle = document.getElementById('menu-toggle');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');

        menuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
            sidebarOverlay.classList.toggle('active');
        });

        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.remove('open');
            sidebarOverlay.classList.remove('active');
        });

        // Toggle sections with slide-down animation
        document.querySelectorAll('.section-title').forEach(title => {
            title.addEventListener('click', () => {
                const targetId = title.getAttribute('data-toggle');
                const content = document.getElementById(targetId);
                const isOpen = content.classList.contains('open');
                
                // Toggle the open class
                content.classList.toggle('open');
                title.classList.toggle('open');

                // Smoothly adjust max-height for animation
                if (isOpen) {
                    content.style.maxHeight = 0;
                } else {
                    content.style.maxHeight = content.scrollHeight + 'px';
                }
            });
        });

        // Fetch financial data to populate the overview
        async function fetchFinancialData() {
            try {
                const response = await fetch('https://deviouscreative.co.uk/api.php', {
                    method: 'GET',
                    headers: { 'Accept': 'application/json' }
                });
                console.log('fetchFinancialData - Response status:', response.status);
                const text = await response.text();
                console.log('fetchFinancialData - Raw response body:', text);
                if (!response.ok) {
                    throw new Error(`API error: ${response.status} - ${text}`);
                }
                let data;
                try {
                    data = JSON.parse(text);
                } catch (parseError) {
                    throw new Error(`Failed to parse JSON response: ${parseError.message} - Response: ${text}`);
                }
                if (!data || typeof data !== 'object') {
                    throw new Error('Invalid response data: Expected a JSON object');
                }
                console.log('fetchFinancialData - Parsed data:', JSON.stringify(data, null, 2));

                // Populate overview with current values
                document.getElementById('portfolio-value').textContent = `£${(Number(data.portfolio_value) || 0).toFixed(2)}`;
                document.getElementById('eth-value').textContent = `£${(Number(data.eth_value) || 0).toFixed(2)}`;
                document.getElementById('current-account').textContent = `£${(Number(data.current_account) || 0).toFixed(2)}`;
                document.getElementById('savings').textContent = `£${(Number(data.savings) || 0).toFixed(2)}`;
                document.getElementById('external-savings').textContent = `£${(Number(data.external_savings) || 0).toFixed(2)}`;
                document.getElementById('natwest-debt').textContent = `£${(Number(data.credit_card_balances?.NatWest) || 0).toFixed(2)}`;
                document.getElementById('tesco-debt').textContent = `£${(Number(data.credit_card_balances?.Tesco) || 0).toFixed(2)}`;
                document.getElementById('vanquis-debt').textContent = `£${(Number(data.credit_card_balances?.Vanquis) || 0).toFixed(2)}`;
                document.getElementById('credit-card-debts-total').textContent = `£${(Number(data.credit_card_debts_total) || 0).toFixed(2)}`;
                document.getElementById('owed-total').textContent = `£${(Number(data.owed_total) || 0).toFixed(2)}`;
                document.getElementById('portfolio-error').textContent = data.portfolio_error || 'None';

                // Populate portfolio breakdown (top positions)
                const topPositionsList = document.getElementById('top-positions');
                topPositionsList.innerHTML = '';
                if (data.top_positions && Array.isArray(data.top_positions)) {
                    data.top_positions.forEach(position => {
                        const li = document.createElement('li');
                        li.textContent = `${position.ticker}: £${(Number(position.value) || 0).toFixed(2)}`;
                        topPositionsList.appendChild(li);
                    });
                } else {
                    const li = document.createElement('li');
                    li.textContent = 'No top positions available';
                    topPositionsList.appendChild(li);
                }

                // Populate money owed
                const moneyOwedList = document.getElementById('money-owed-list');
                moneyOwedList.innerHTML = '';
                if (data.money_owed && Array.isArray(data.money_owed)) {
                    data.money_owed.forEach(item => {
                        const li = document.createElement('li');
                        li.textContent = `Amount: £${(Number(item.amount) || 0).toFixed(2)}`;
                        moneyOwedList.appendChild(li);
                    });
                } else {
                    const li = document.createElement('li');
                    li.textContent = 'No money owed';
                    moneyOwedList.appendChild(li);
                }
            } catch (error) {
                console.error('Error fetching financial data:', error);
                // Set default values if fetch fails
                document.getElementById('portfolio-value').textContent = '£0.00';
                document.getElementById('eth-value').textContent = '£0.00';
                document.getElementById('current-account').textContent = '£0.00';
                document.getElementById('savings').textContent = '£0.00';
                document.getElementById('external-savings').textContent = '£0.00';
                document.getElementById('natwest-debt').textContent = '£0.00';
                document.getElementById('tesco-debt').textContent = '£0.00';
                document.getElementById('vanquis-debt').textContent = '£0.00';
                document.getElementById('credit-card-debts-total').textContent = '£0.00';
                document.getElementById('owed-total').textContent = '£0.00';
                document.getElementById('portfolio-error').textContent = 'Error fetching portfolio data';

                // Populate fallback for sections
                document.getElementById('top-positions').innerHTML = '<li>No top positions available</li>';
                document.getElementById('money-owed-list').innerHTML = '<li>No money owed</li>';
            }
        }

        // Fetch financial data on page load
        fetchFinancialData();

        // Register the service worker for PWA functionality
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('https://deviouscreative.co.uk/sw.js')
                    .then(registration => {
                        console.log('Service Worker registered with scope:', registration.scope);
                    })
                    .catch(error => {
                        console.error('Service Worker registration failed:', error);
                    });
            });
        }
    </script>
</body>
</html>