<?php
session_start();

if (
    isset($_SESSION['username'], $_SESSION['database'], $_SESSION['userid']) &&
    !empty($_SESSION['username']) && !empty($_SESSION['database']) && !empty($_SESSION['userid'])
) {
    try {
        require_once 'connection.php';
        $query = $pdo->prepare('SELECT USERID FROM USERS WHERE USERID = ? AND USERNAME = ? AND DATABASENAME = ?');
        $query->execute([$_SESSION['userid'], $_SESSION['username'], $_SESSION['database']]);
        if (!$query->fetch(PDO::FETCH_ASSOC)) {
            echo "❌ Invalid session data. Redirecting...";
            header("Refresh:2; url=login.html");
            exit();
        }
    } catch (PDOException $e) {
        echo "❌ Database connection failed: " . $e->getMessage();
        exit();
    }

echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Finance Dashboard</title>
    <link rel="shortcut icon" href="data/favicon.ico" type="image/x-icon">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <link rel="stylesheet" href="main.css">
    <script src="plugins.js"></script>
    <script src="chartMaker.js"></script>

    <style>
        /* ── KPI summary cards ── */
        .kpi-summary {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 6px;
            height: 100%;
        }
        .kpi-block { text-align: center; margin-bottom: 8px; }
        .kpi-block .label {
            font-size: 12px;
            opacity: .65;
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: .5px;
        }
        .kpi-block .value {
            font-size: 26px;
            font-weight: 600;
            letter-spacing: -.5px;
        }
        .kpi-block.revenue .value { color: #afdefc; }
        .kpi-block.expense .value { color: #f98a8a; }
        .kpi-block.profit  .value { color: #84e0b6; }
        .kpi-divider {
            width: 60%;
            border: none;
            border-top: 1px solid rgba(255,255,255,.1);
            margin: 4px 0;
        }

        /* ── Section heading ── */
        .section-heading {
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: .45;
            padding: 18px 4px 6px;
            border-top: 1px solid rgba(255,255,255,.07);
            margin: 0 4px;
        }
        .section-heading:first-of-type {
            border-top: none;
            padding-top: 6px;
        }

        /* ══════════════════════════════════════════
           HEADER — two-row layout
           Row 1: ☰ (left) · Title (center) · empty (right mirror)
           Row 2: ⟳ + all filter dropdowns centered
        ══════════════════════════════════════════ */
        .main2php .header {
            display: flex;
            flex-direction: column;
            align-items: stretch;
            gap: 0;
            width: 100%;
            position: sticky;
            top: 0;
            z-index: 50;
            background-color: #0f2c47;
            padding: 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.5);
        }

        /* ── Row 1: nav button left · title center · spacer right ── */
        .header-row1 {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            padding: 0.6rem 1.2rem 0.4rem;
            border-bottom: 1px solid rgba(255,255,255,0.07);
        }

        .header-row1 .nav-slot {
            flex: 0 0 auto;
            display: flex;
            align-items: center;
        }

        /* mirror spacer keeps title perfectly centered */
        .header-row1 .spacer {
            flex: 0 0 auto;
            /* same width as nav button so title lands in the middle */
            width: 36px;
        }

        .header-row1 h1 {
            flex: 1;
            text-align: center;
            margin: 0;
            font-size: clamp(16px, 1.8vmax, 26px);
            font-weight: 700;
            white-space: nowrap;
            letter-spacing: 0.5px;
            text-shadow: 0 0 20px rgba(0,0,0,0.5);
        }

        /* ── Row 2: all filters centered ── */
        .header-row2 {
            display: flex;
            flex-direction: row;
            flex-wrap: nowrap;
            align-items: center;
            justify-content: center;
            gap: 2px;
            padding: 0.2rem 0.5rem;
            overflow-x: auto;
            scrollbar-width: none;
        }
        .header-row2::-webkit-scrollbar { display: none; }

        .header-row2 .payment {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 4px;
            flex-shrink: 0;
            white-space: nowrap;
        }

        .header-row2 .payment p {
            font-size: clamp(10px, 0.8vmax, 10px);
            margin: 0;
            font-weight: 600;
            letter-spacing: 0.4px;
            opacity: 0.85;
        }

        .header-row2 select,
        .header-row2 .update {
            padding: 0.5rem 0.9rem;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            background-color: #1d3a5f;
            color: white;
            font-size: clamp(12px, 1vmax, 15px);
            white-space: nowrap;
        }

        .header-row2 .update {
            font-size: 1.1rem;
            padding: 0.5rem 0.75rem;
            flex-shrink: 0;
        }

        .header-row2 select:hover,
        .header-row2 select:focus {
            box-shadow: 0 0 4px 2px rgba(255,255,255,0.8);
            outline: none;
        }

        .header-row2 .update:hover {
            animation: toggle_shadow 2s infinite ease-in-out;
        }

        /* ── Menu (☰) button ── */
        .header-row1 .menu {
            padding: 0.4rem 0.7rem;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            background-color: #1d3a5f;
            color: white;
            font-size: 1rem;
        }
        .header-row1 .menu:hover {
            animation: toggle_shadow 2s infinite ease-in-out;
        }
    </style>

    <script>
        function hideNavigation() {
            if (!document.getElementById("navigation").classList.contains("navigation-hide")) {
                toggleNavigation();
            }
        }
        function toggleNavigation() {
            document.getElementById("navigation").classList.toggle("navigation-hide");
        }
        document.addEventListener("DOMContentLoaded", () => {
            updateData();
        });
        document.addEventListener("keydown", (event) => {
            if (event.key === "Escape") {
                closeModal();
                hideNavigation();
            }
        });
    </script>
</head>

<body class="main2php darkmode" onclick="hideNavigation()">';

    include "modal.html";

echo '
    <!-- ══════════════════════════════════════════
         HEADER
         Row 1 → ☰ (left) | Finance Dashboard (center) | spacer (right)
         Row 2 → ⟳ FY | Quarter | Month | Category | License | Rev.Type  (all centered)
    ══════════════════════════════════════════ -->
    <div class="header">

        <!-- ROW 1 -->
        <div class="header-row1">
            <!-- Left: menu button + nav panel -->
            <div class="nav-slot">
                <button class="menu" id="menu" title="Menu"
                    onclick="event.stopPropagation(); toggleNavigation()">☰</button>';
                include "navigation.html";
echo '
            </div>

            <!-- Centre: dashboard title -->
            <h1>Finance Dashboard</h1>

            <!-- Right: mirror spacer so title stays truly centered -->
            <div class="spacer"></div>
        </div><!-- /header-row1 -->

        <!-- ROW 2 -->
        <div class="header-row2">
            <button class="update" id="update" title="Refresh" onclick="updateData()">⟳</button>

            <div class="payment">
                <p>FY</p>
                <select name="fyFilter" id="fyFilter" onchange="updateData()">
                    <option value="">All Years</option>
                </select>
            </div>

            <div class="payment">
                <p>Quarter</p>
                <select name="quarterFilter" id="quarterFilter" onchange="updateData()">
                    <option value="">All Quarters</option>
                </select>
            </div>

            <div class="payment">
                <p>Month</p>
                <select name="monthFilter" id="monthFilter" onchange="updateData()">
                    <option value="">All Months</option>
                </select>
            </div>

            <div class="payment">
                <p>Category</p>
                <select name="categoryFilter" id="categoryFilter" onchange="updateData()">
                    <option value="">All Categories</option>
                </select>
            </div>

            <div class="payment">
                <p>License</p>
                <select name="licenseFilter" id="licenseFilter" onchange="updateData()">
                    <option value="">All License Types</option>
                </select>
            </div>

            <div class="payment">
                <p>Rev. Type</p>
                <select name="revenueTypeFilter" id="revenueTypeFilter" onchange="updateData()">
                    <option value="">All Revenue Types</option>
                </select>
            </div>
        </div><!-- /header-row2 -->

    </div><!-- /header -->


    <!-- ══════════════════════════════════════════
         SECTION 1 — Period Overview
    ══════════════════════════════════════════ -->
    <div class="section-heading">Period Overview (FY / Quarter / Month)</div>
    <div class="dashboard">

        <div align="center" class="card">
            <h3>Revenue by Period (in L)</h3>
            <canvas class="bar" id="revenueByPeriod"></canvas>
        </div>

        <div align="center" class="card">
            <h3>Revenue vs Expense by Period (in L)</h3>
            <canvas class="bar" id="revenueVsExpense"></canvas>
        </div>

        <div align="center" class="card">
            <div class="kpi-summary">
                <div class="kpi-block revenue">
                    <div class="label">Total Revenue</div>
                    <div class="value" id="kpiRevenue">₹ —</div>
                </div>
                <hr class="kpi-divider">
                <div class="kpi-block expense">
                    <div class="label">Total Expenses</div>
                    <div class="value" id="kpiExpense">₹ —</div>
                </div>
                <hr class="kpi-divider">
                <div class="kpi-block profit">
                    <div class="label" id="profitLabel">Net Profit</div>
                    <div class="value" id="kpiProfit">₹ —</div>
                </div>
                <hr class="kpi-divider">
                <div class="kpi-block" style="color:#f5d080">
                    <div class="label">Profit Margin</div>
                    <div class="value" id="kpiMargin">—%</div>
                </div>
            </div>
        </div>

    </div><!-- /dashboard period -->


    <!-- ══════════════════════════════════════════
         SECTION 2 — Category Analysis
    ══════════════════════════════════════════ -->
    <div class="section-heading">Category Analysis</div>
    <div class="dashboard">

        <div align="center" class="card">
            <h3>Revenue by Category (in L)</h3>
            <canvas class="bar" id="revenueByCategory"></canvas>
        </div>

        <div align="center" class="card">
            <h3>Clients by Category</h3>
            <canvas class="bar" id="clientsByCategory"></canvas>
        </div>

        <div align="center" class="card">
            <h3>Revenue by Sub Category</h3>
            <canvas class="pie" id="revenueBySubCat"></canvas>
        </div>

        <div align="center" class="card full-span special" id="special2">
            <h3>Category Revenue by Period (in L)</h3>
            <canvas class="chart" id="categoryByPeriod"></canvas>
        </div>

    </div><!-- /dashboard category -->


    <!-- ══════════════════════════════════════════
         SECTION 3 — Expense Breakdown
    ══════════════════════════════════════════ -->
    <div class="section-heading">Expense Breakdown</div>
    <div class="dashboard">

        <div align="center" class="card half-span half-span-screen">
            <h3>Expense by Type &amp; Period (in L)</h3>
            <canvas class="chart" id="expenseByType"></canvas>
        </div>

        <div align="center" class="card">
            <h3>Clients Acquired by Period</h3>
            <canvas class="bar" id="clientsByPeriod"></canvas>
        </div>

    </div><!-- /dashboard expense -->


    <!-- ══════════════════════════════════════════
         SECTION 4 — License Type & Revenue Mix
    ══════════════════════════════════════════ -->
    <div class="section-heading">License Type &amp; Revenue Mix</div>
    <div class="dashboard">

        <div align="center" class="card half-span">
            <h3>Revenue by License Type &amp; Period (in L)</h3>
            <canvas class="chart" id="licenseByPeriod"></canvas>
        </div>

        <div align="center" class="card half-span">
            <h3>Revenue by RevenueType (in L)</h3>
            <canvas class="chart" id="revTypeByPeriod"></canvas>
        </div>

    </div><!-- /dashboard license -->


    <!-- ══════════════════════════════════════════
         SECTION 5 — Top Projects
    ══════════════════════════════════════════ -->
    <div class="section-heading">Top Projects</div>
    <div class="dashboard">

        <div align="center" class="card full-span special" id="special">
            <h3>Top 5 Projects by Revenue (in L)</h3>
            <canvas class="chart" id="topProjects"></canvas>
        </div>

    </div><!-- /dashboard top-projects -->

    <script src="main2.js"></script>
</body>
</html>';

} else {
    echo "❌ Session data incomplete. Redirecting to login...";
    header("Refresh:2; url=login.html");
    exit();
}