<?php
require_once 'session_config.php';
session_start();
$_SESSION['user_id'] = 1; // Temporary for localhost testing
error_log("dashboard.php: Session ID: " . session_id());
error_log("dashboard.php: user_id: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'not set'));

require_once 'config.php';

// Database connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die('Database connection failed: ' . $conn->connect_error);
}

// Fetch current financial data
$user_id = $_SESSION['user_id'];
$financial_data = $conn->query("SELECT savings, eth_holdings, external_savings, current_account FROM financial_data WHERE user_id = $user_id")->fetch_assoc();
$savings = $financial_data['savings'] ?? 0;
$eth_holdings = $financial_data['eth_holdings'] ?? 0;
$external_cash_savings = $financial_data['external_savings'] ?? 0;
$current_account = $financial_data['current_account'] ?? 0;

// Fetch current credit card debts
$credit_card_debts = [];
$credit_card_balances = ['NatWest' => 0, 'Tesco' => 0, 'Vanquis' => 0];
$result = $conn->query("SELECT card_name, amount FROM credit_card_debts WHERE user_id = $user_id");
$raw_debts = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $credit_card_debts[] = $row;
        $raw_debts[] = $row;
        $card_name = $row['card_name'];
        foreach (['NatWest', 'Tesco', 'Vanquis'] as $valid_name) {
            if (strcasecmp($card_name, $valid_name) === 0) {
                $credit_card_balances[$valid_name] = $row['amount'];
                break;
            }
        }
    }
} else {
    error_log("Failed to fetch credit card debts: " . $conn->error);
}
error_log("Raw Credit Card Debts: " . print_r($raw_debts, true));
error_log("Credit Card Balances: " . print_r($credit_card_balances, true));

// Handle form submission for updating financial data
$update_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_financials'])) {
    $natwest = isset($_POST['natwest']) && is_numeric($_POST['natwest']) ? floatval($_POST['natwest']) : $credit_card_balances['NatWest'];
    $tesco = isset($_POST['tesco']) && is_numeric($_POST['tesco']) ? floatval($_POST['tesco']) : $credit_card_balances['Tesco'];
    $vanquis = isset($_POST['vanquis']) && is_numeric($_POST['vanquis']) ? floatval($_POST['vanquis']) : $credit_card_balances['Vanquis'];
    $premium_bonds = isset($_POST['premium_bonds']) && is_numeric($_POST['premium_bonds']) ? floatval($_POST['premium_bonds']) : $savings;
    $current_account_input = isset($_POST['current_account']) && is_numeric($_POST['current_account']) ? floatval($_POST['current_account']) : $current_account;

    // Validate inputs
    if ($natwest < 0 || $tesco < 0 || $vanquis < 0 || $premium_bonds < 0 || $current_account_input < 0) {
        $update_message = '<p class="text-red-500 text-sm mt-2">All provided values must be non-negative.</p>';
    } else {
        // Update credit_card_debts
        $stmt = $conn->prepare("UPDATE credit_card_debts SET amount = ? WHERE user_id = ? AND card_name = ?");
        if (isset($_POST['natwest']) && is_numeric($_POST['natwest'])) {
            $stmt->bind_param("dis", $natwest, $user_id, $card_name);
            $card_name = 'NatWest';
            $stmt->execute();
        }
        if (isset($_POST['tesco']) && is_numeric($_POST['tesco'])) {
            $stmt->bind_param("dis", $tesco, $user_id, $card_name);
            $card_name = 'Tesco';
            $stmt->execute();
        }
        if (isset($_POST['vanquis']) && is_numeric($_POST['vanquis'])) {
            $stmt->bind_param("dis", $vanquis, $user_id, $card_name);
            $card_name = 'Vanquis';
            $stmt->execute();
        }
        $stmt->close();

        // Update premium_bonds (savings) if changed
        if (isset($_POST['premium_bonds']) && is_numeric($_POST['premium_bonds'])) {
            $stmt = $conn->prepare("UPDATE financial_data SET savings = ? WHERE user_id = ?");
            $stmt->bind_param("di", $premium_bonds, $user_id);
            $stmt->execute();
            $stmt->close();
        }

        // Update current_account if changed
        if (isset($_POST['current_account']) && is_numeric($_POST['current_account'])) {
            $stmt = $conn->prepare("UPDATE financial_data SET current_account = ? WHERE user_id = ?");
            $stmt->bind_param("di", $current_account_input, $user_id);
            $stmt->execute();
            $stmt->close();
        }

        $update_message = '<p class="text-green-500 text-sm mt-2">Financial data updated successfully!</p>';

        // Refresh credit card debts after update
        $credit_card_debts = [];
        $credit_card_balances = ['NatWest' => 0, 'Tesco' => 0, 'Vanquis' => 0];
        $result = $conn->query("SELECT card_name, amount FROM credit_card_debts WHERE user_id = $user_id");
        $raw_debts = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $credit_card_debts[] = $row;
                $raw_debts[] = $row;
                $card_name = $row['card_name'];
                foreach (['NatWest', 'Tesco', 'Vanquis'] as $valid_name) {
                    if (strcasecmp($card_name, $valid_name) === 0) {
                        $credit_card_balances[$valid_name] = $row['amount'];
                        break;
                    }
                }
            }
        } else {
            error_log("Failed to refresh credit card debts: " . $conn->error);
        }
        error_log("Raw Credit Card Debts (Post-Update): " . print_r($raw_debts, true));
        error_log("Credit Card Balances (Post-Update): " . print_r($credit_card_balances, true));

        // Refresh financial data
        $financial_data = $conn->query("SELECT savings, eth_holdings, external_savings, current_account FROM financial_data WHERE user_id = $user_id")->fetch_assoc();
        $savings = $financial_data['savings'] ?? 0;
        $current_account = $financial_data['current_account'] ?? 0;
    }
}

// Fetch money owed
$money_owed = [];
$result = $conn->query("SELECT amount FROM money_owed WHERE user_id = $user_id");
while ($row = $result->fetch_assoc()) {
    $money_owed[] = $row;
}

// Fetch payment plans
$payment_plans = [];
$result = $conn->query("SELECT description, total_amount, months FROM payment_plans WHERE user_id = $user_id");
while ($row = $result->fetch_assoc()) {
    $payment_plans[] = $row;
}

// Fetch Trading 212 portfolio with retry logic
function getPortfolio($retries = 3, $delay = 2) {
    $url = BASE_URL . '/api/v0/equity/portfolio';
    for ($attempt = 1; $attempt <= $retries; $attempt++) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . TRADING212_API_KEY
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        $verbose = fopen('php://temp', 'w+');
        curl_setopt($ch, CURLOPT_STDERR, $verbose);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $error = curl_error($ch);

        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);

        rewind($verbose);
        $verbose_log = stream_get_contents($verbose);
        fclose($verbose);
        error_log("Trading 212 Portfolio cURL verbose (Attempt $attempt): $verbose_log");
        error_log("Trading 212 Portfolio Request Headers: Authorization: " . TRADING212_API_KEY);
        error_log("Trading 212 Portfolio Response Headers: $headers");
        error_log("Trading 212 Portfolio Response Body: $body");

        curl_close($ch);

        if ($http_code === 429) {
            error_log("Trading 212 Portfolio API rate limit exceeded (HTTP 429). Retrying after $delay seconds...");
            if ($attempt < $retries) {
                sleep($delay);
                continue;
            }
            error_log("Trading 212 Portfolio API error: HTTP $http_code, Error: $error");
            return ['open' => ['items' => []], 'error' => "API Error: HTTP $http_code, $error"];
        }

        if ($http_code !== 200 || $error) {
            error_log("Trading 212 Portfolio API error: HTTP $http_code, Error: $error");
            return ['open' => ['items' => []], 'error' => "API Error: HTTP $http_code, $error"];
        }

        $data = json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("Trading 212 Portfolio JSON decode error: " . json_last_error_msg());
            return ['open' => ['items' => []], 'error' => 'Invalid API response'];
        }
        
        error_log("Trading 212 Portfolio Parsed Data Structure: " . print_r($data, true));
        error_log("Trading 212 Portfolio Top-Level Keys: " . implode(", ", array_keys($data)));
        
        return $data;
    }
}

// Fetch ETH price
function getEthPrice() {
    $url = 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=gbp';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($http_code !== 200 || $error) {
        error_log("CoinGecko API error: HTTP $http_code, Error: $error");
        return 0;
    }

    $data = json_decode($response, true);
    return $data['ethereum']['gbp'] ?? 0;
}

// Fetch USD to GBP exchange rate
function getUsdToGbpRate() {
    $url = 'https://api.exchangerate-api.com/v4/latest/USD';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($http_code !== 200 || $error) {
        error_log("ExchangeRate API error: HTTP $http_code, Error: $error");
        return 0.751;
    }

    $data = json_decode($response, true);
    return $data['rates']['GBP'] ?? 0.751;
}

// Fetch API data
$portfolio_data = getPortfolio();
$portfolio = [];
if (isset($portfolio_data['open']['items'])) {
    $portfolio = array_merge($portfolio, $portfolio_data['open']['items']);
}
if (isset($portfolio_data['open']['etfs'])) {
    $portfolio = array_merge($portfolio, $portfolio_data['open']['etfs']);
}
if (isset($portfolio_data['etfs'])) {
    $portfolio = array_merge($portfolio, $portfolio_data['etfs']);
}
if (isset($portfolio_data['holdings'])) {
    $portfolio = array_merge($portfolio, $portfolio_data['holdings']);
}
if (is_array($portfolio_data) && !isset($portfolio_data['error']) && empty($portfolio)) {
    $portfolio = $portfolio_data;
}
if (empty($portfolio)) {
    error_log("No portfolio items found in portfolio API response");
}

$portfolio_error = $portfolio_data['error'] ?? '';
$eth_price = getEthPrice();
$usd_to_gbp = getUsdToGbpRate();

// Calculate portfolio value and prepare top 5 positions
$portfolio_value = 0;
$debug_values = [];
$positions = [];

foreach ($portfolio as $item) {
    $raw_price = $item['currentPrice'] ?? $item['price'] ?? 0;
    $ticker = $item['ticker'] ?? $item['code'] ?? 'Unknown';
    $quantity = $item['quantity'] ?? 0;
    $currency = isset($item['currency']) ? $item['currency'] : (stripos($ticker, 'l_EQ') !== false ? 'GBP' : 'USD');
    $asset_type = $item['assetType'] ?? $item['instrumentType'] ?? 'Unknown';
    if (in_array($ticker, ['VUAA', 'VUAG', 'VUSA', 'VUAGl_EQ', 'VUSCd_EQ'])) {
        $currency = 'GBP';
        $price_in_pounds = $raw_price;
    } elseif ($ticker === 'VUAAl_EQ') {
        $currency = 'GBP';
        $price_in_pounds = $raw_price;
        $quantity = 1.586;
    } elseif ($currency === 'GBP' && stripos($ticker, 'l_EQ') !== false) {
        $price_in_pounds = $raw_price / 100;
    } elseif ($currency === 'USD') {
        $price_in_pounds = $raw_price * $usd_to_gbp;
    } else {
        $price_in_pounds = $raw_price;
        error_log("Unknown currency for portfolio item {$ticker}: $currency");
    }
    $value = $quantity * $price_in_pounds;
    $portfolio_value += $value;
    $positions[] = [
        'ticker' => $ticker,
        'quantity' => $quantity,
        'price_in_pounds' => $price_in_pounds,
        'value' => $value,
        'currency' => $currency,
        'asset_type' => $asset_type,
        'source' => 'portfolio'
    ];
    $debug_values[] = "Portfolio: {$ticker}: quantity=$quantity, currentPrice=$raw_price, currency=$currency, asset_type=$asset_type, price_in_pounds=$price_in_pounds, value=$value";
}

// Add Trading 212 cash balances if present (assume GBP)
$cash_sources = [
    ['data' => $portfolio_data, 'name' => 'Portfolio']
];
foreach ($cash_sources as $source) {
    $data = $source['data'];
    $name = $source['name'];
    if (isset($data['cash'])) {
        $portfolio_value += $data['cash'];
        $debug_values[] = "$name Cash balance: {$data['cash']} (GBP)";
    }
    if (isset($data['freeCash'])) {
        $portfolio_value += $data['freeCash'];
        $debug_values[] = "$name Free cash balance: {$data['freeCash']} (GBP)";
    }
    if (isset($data['accountBalance'])) {
        $portfolio_value += $data['accountBalance'];
        $debug_values[] = "$name Account balance: {$data['accountBalance']} (GBP)";
    }
    if (isset($data['uninvestedCash'])) {
        $portfolio_value += $data['uninvestedCash'];
        $debug_values[] = "$name Uninvested cash balance: {$data['uninvestedCash']} (GBP)";
    }
    if (isset($data['totalAccountValue'])) {
        $portfolio_value += $data['totalAccountValue'];
        $debug_values[] = "$name Total account value: {$data['totalAccountValue']} (GBP)";
    }
}

// Sort positions by value in descending order and take top 5
usort($positions, function($a, $b) {
    return $b['value'] <=> $a['value'];
});
$top_positions = array_slice($positions, 0, 5);

error_log("Portfolio Value Breakdown: " . implode("; ", $debug_values));
error_log("Total Portfolio Value Calculated: $portfolio_value");
error_log("All Positions: " . print_r($positions, true));
error_log("Top 5 Positions: " . print_r($top_positions, true));
error_log("USD to GBP Exchange Rate: $usd_to_gbp");
error_log("Full Portfolio Data: " . print_r($portfolio_data, true));
$eth_value = $eth_price * $eth_holdings;
$owed_total = array_sum(array_map(function($item) {
    return $item['amount'];
}, $money_owed));
$credit_card_debts_total = array_sum(array_map(function($item) {
    return $item['amount'];
}, $credit_card_debts));
$gross_wealth = $portfolio_value + $eth_value + $savings + $external_cash_savings + $current_account + $owed_total;
$total_wealth = $gross_wealth - $credit_card_debts_total;

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wealth Dashboard</title>
    <link href="styles.css" rel="stylesheet">
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#1E3A8A">
    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/service-worker.js?v=1.0.6')
                    .then(registration => {
                        console.log('Service Worker registered with scope:', registration.scope);
                    })
                    .catch(error => {
                        console.error('Service Worker registration failed:', error);
                    });
            });
        }
    </script>
</head>
<body>
    <!-- Header with Menu Toggle -->
    <header class="fixed top-0 left-0 right-0 z-50 bg-primary text-white p-4 flex justify-between items-center shadow-md">
        <h1 class="text-lg font-semibold">Wealth Dashboard</h1>
        <button id="menu-toggle" class="p-2 focus:outline-none">
            <svg class="w-6 h-6" 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>

    <!-- Sidebar -->
    <div id="sidebar" class="fixed top-0 left-0 w-64 h-full bg-white shadow-lg z-40 transform -translate-x-full transition-transform duration-300">
        <div class="p-4">
            <h2 class="text-xl font-bold text-gray-800">Menu</h2>
            <ul class="mt-4">
                <li>
                    <a href="dashboard.php" class="flex items-center py-2 px-4 text-gray-800 hover:bg-gray-100 rounded">
                        <svg class="w-4 h-4 mr-2" 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>
                        Wealth Dashboard
                    </a>
                </li>
                <li>
                    <a href="rm_guitar.php" class="flex items-center py-2 px-4 text-gray-800 hover:bg-gray-100 rounded">
                        <svg class="w-4 h-4 mr-2" 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="M9 19l-7 1 1-7 5-5 5 5 1 7-7-1zm0 0l7-1m-7 1V9m7 1l-1 7m-5-5l-1 1m1-1l1-1"></path>
                        </svg>
                        RM Guitar
                    </a>
                </li>
                <li>
                    <a href="logout.php" class="flex items-center py-2 px-4 text-red-500 hover:bg-gray-100 rounded">
                        <svg class="w-4 h-4 mr-2" 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>

    <!-- Sidebar Overlay -->
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden transition-opacity duration-300"></div>

    <!-- Main Content -->
    <main class="container pt-20 pb-8">
        <!-- Wealth Summary Card -->
        <section class="card mb-6">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800">Wealth Summary</h2>
                <div class="mt-4">
                    <p class="text-2xl font-bold text-gray-900">£<?php echo number_format($total_wealth, 2); ?></p>
                    <p class="text-sm text-gray-600">Total Wealth (Net)</p>
                    <p class="mt-2 text-lg text-gray-800">Gross Wealth: £<?php echo number_format($gross_wealth, 2); ?></p>
                </div>
            </div>
        </section>

        <!-- Holdings Breakdown -->
        <section class="card mb-6">
            <details>
                <summary class="flex justify-between items-center p-6">
                    <span class="text-lg font-semibold text-gray-800">Holdings Breakdown</span>
                    <svg class="w-5 h-5 transform transition-transform duration-200" 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>
                </summary>
                <div class="p-6 pt-0">
                    <ul class="space-y-2">
                        <li class="flex justify-between">
                            <span>Trading 212 Investments</span>
                            <span class="font-medium">£<?php echo number_format($portfolio_value, 2); ?></span>
                        </li>
                        <?php if ($portfolio_error): ?>
                            <li class="text-red-500 text-sm"><?php echo htmlspecialchars($portfolio_error); ?></li>
                        <?php endif; ?>
                        <?php if (!empty($top_positions)): ?>
                            <li>
                                <details class="mt-2">
                                    <summary class="text-sm font-medium text-gray-700 flex items-center">
                                        Top 5 Positions
                                        <svg class="w-4 h-4 ml-2 transform transition-transform duration-200" 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>
                                    </summary>
                                    <ul class="mt-2 space-y-1 text-sm">
                                        <?php foreach ($top_positions as $position): ?>
                                            <li class="flex justify-between">
                                                <span><?php echo htmlspecialchars($position['ticker']); ?></span>
                                                <span>£<?php echo number_format($position['value'], 2); ?></span>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </details>
                            </li>
                        <?php endif; ?>
                        <li class="flex justify-between">
                            <span>Ethereum Holdings</span>
                            <span class="font-medium">£<?php echo number_format($eth_value, 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>Premium Bonds</span>
                            <span class="font-medium">£<?php echo number_format($savings, 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>External Cash Savings</span>
                            <span class="font-medium">£<?php echo number_format($external_cash_savings, 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>Current Account</span>
                            <span class="font-medium">£<?php echo number_format($current_account, 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>Money Owed</span>
                            <span class="font-medium">£<?php echo number_format($owed_total, 2); ?></span>
                        </li>
                        <li class="flex justify-between font-semibold pt-2 border-t">
                            <span>Total Holdings</span>
                            <span>£<?php echo number_format($gross_wealth, 2); ?></span>
                        </li>
                    </ul>
                </div>
            </details>
        </section>

        <!-- Credit Card Debts -->
        <section class="card mb-6">
            <details>
                <summary class="flex justify-between items-center p-6">
                    <span class="text-lg font-semibold text-gray-800">Credit Card Debts</span>
                    <svg class="w-5 h-5 transform transition-transform duration-200" 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>
                </summary>
                <div class="p-6 pt-0">
                    <ul class="space-y-2">
                        <li class="flex justify-between">
                            <span>Natwest</span>
                            <span class="font-medium">£<?php echo number_format($credit_card_balances['NatWest'], 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>Tesco</span>
                            <span class="font-medium">£<?php echo number_format($credit_card_balances['Tesco'], 2); ?></span>
                        </li>
                        <li class="flex justify-between">
                            <span>Vanquis</span>
                            <span class="font-medium">£<?php echo number_format($credit_card_balances['Vanquis'], 2); ?></span>
                        </li>
                        <li class="flex justify-between font-semibold pt-2 border-t">
                            <span>Total Debt</span>
                            <span>£<?php echo number_format($credit_card_debts_total, 2); ?></span>
                        </li>
                    </ul>
                </div>
            </details>
        </section>

        <!-- Update Financials -->
        <section class="card mb-6">
            <details>
                <summary class="flex justify-between items-center p-6">
                    <span class="text-lg font-semibold text-gray-800">Update Financials</span>
                    <svg class="w-5 h-5 transform transition-transform duration-200" 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>
                </summary>
                <div class="p-6 pt-0">
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="update_financials" value="1">
                        <div>
                            <label for="natwest" class="block text-sm font-medium text-gray-700">Natwest (£)</label>
                            <input type="number" step="0.01" id="natwest" name="natwest" value="<?php echo htmlspecialchars($credit_card_balances['NatWest']); ?>" class="w-full p-3 border rounded-lg">
                        </div>
                        <div>
                            <label for="tesco" class="block text-sm font-medium text-gray-700">Tesco (£)</label>
                            <input type="number" step="0.01" id="tesco" name="tesco" value="<?php echo htmlspecialchars($credit_card_balances['Tesco']); ?>" class="w-full p-3 border rounded-lg">
                        </div>
                        <div>
                            <label for="vanquis" class="block text-sm font-medium text-gray-700">Vanquis (£)</label>
                            <input type="number" step="0.01" id="vanquis" name="vanquis" value="<?php echo htmlspecialchars($credit_card_balances['Vanquis']); ?>" class="w-full p-3 border rounded-lg">
                        </div>
                        <div>
                            <label for="premium_bonds" class="block text-sm font-medium text-gray-700">Premium Bonds (£)</label>
                            <input type="number" step="0.01" id="premium_bonds" name="premium_bonds" value="<?php echo htmlspecialchars($savings); ?>" class="w-full p-3 border rounded-lg">
                        </div>
                        <div>
                            <label for="current_account" class="block text-sm font-medium text-gray-700">Current Account (£)</label>
                            <input type="number" step="0.01" id="current_account" name="current_account" value="<?php echo htmlspecialchars($current_account); ?>" class="w-full p-3 border rounded-lg">
                        </div>
                        <button type="submit" class="w-full bg-primary text-white p-3 rounded-lg font-medium hover:bg-blue-700 transition">Update Financials</button>
                        <?php echo $update_message; ?>
                    </form>
                </div>
            </details>
        </section>
    </main>

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

        menuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });

        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('hidden');
        });

        // Rotate chevron on details toggle
        document.querySelectorAll('details').forEach(detail => {
            detail.addEventListener('toggle', () => {
                const svg = detail.querySelector('summary svg');
                if (svg) {
                    svg.classList.toggle('rotate-180', detail.open);
                }
            });
        });
    </script>
</body>
</html>