<?PHP
session_start();
if (
    empty($_SESSION['username']) ||
    empty($_SESSION['database']) ||
    empty($_SESSION['userid'])
) {
    echo "❌ Session data incomplete. Redirecting to login...";
    header("Refresh:2; url=login.html");
    exit();
}
?>

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>IT Sales Dashboard</title>
    <link rel="shortcut icon" href="data/IT SALES.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="shortcut icon" href="data/IT_SALES.png" type="image/x-icon">
    <link rel="stylesheet" href="main.css">
    <script src="preloader.js"></script>
    <script src="chartMaker.js"></script>
    <script src="plugins.js"></script>
    <script>
        function hideNavigation() {
            if (!document.getElementById("navigation").classList.contains("navigation-hide")) {
                toggleNavigation();
            }
        }

        function toggleNavigation() {
            document.getElementById("navigation").classList.toggle("navigation-hide");
        }

        document.addEventListener("keydown", (event) => {
            if (event.key === "Escape") {
                closeModal();
                hideNavigation();
            }
        });
    </script>
</head>

<body onload="getData()" class="sales_dashboard darkmode" onclick="hideNavigation()">
    <?php include "preloader.html" ?>
    <?php include "navigation.html" ?>
    <div class="dashboard">
        <div class="header">
            <h1>IT SALES</h1>
            <div class="filters">
                <button onclick="getChurnData()">Churn Data</button>
                <select onchange="getData()" id="currentYear" name="currentYear">
                    <?php
                    require "connection.php";
                    $query = "SELECT DISTINCT financial_year AS year FROM it_sales ORDER BY year DESC";
                    $currentYear = date("Y");
                    try {
                        $stmt = $pdo->query($query);
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            $year = htmlspecialchars($row['year']);
                            $selected = ($year == $currentYear) ? "selected" : "";
                            echo "<option value='".$row['year']."' >{$row['year']}</option>";
                        }
                    } catch (PDOException $e) {
                        echo "<option value=''>Error: " . htmlspecialchars($e->getMessage()) . "</option>";
                    }
                    ?>
                </select>

                <div class="quarterSelect" id="quarterSelect">
                    <button onclick="getData()" id="Quarter1" value="2">Quarter 1</button>
                    <button onclick="getData()" id="Quarter2" value="3">Quarter 2</button>
                    <button onclick="getData()" id="Quarter3" value="4">Quarter 3</button>
                    <button onclick="getData()" id="Quarter4" value="1">Quarter 4</button>
                </div>
                <input type="date" name="date" id="dateToday">
            </div>
            <button class="menu" id="menu" title="Menu" onclick="event.stopPropagation(); toggleNavigation()">☰</button>
        </div>

        <!-- FIRST WITH CALCULATED FIELDS ONLY -->
        <div class="card half-span">
            <div class="miniGrid">
                <div class="miniCard span3">
                    <h3>Current Opportunities</h3>
                    <h2 id="current_opportunities"></h2>
                </div>
                <div class="miniCard span3">
                    <h3>Current Purchase Value</h3>
                    <h2 id="current_purchase_value">₹ </h2>
                </div>
                <div class="miniCard span3">
                    <h3>Avg. Purchase Value</h3>
                    <h2 id="average_purchase_value">₹ </h2>
                </div>
                <div class="miniCard span3">
                    <h3>Win Rate %</h3>
                    <h2 id="win_rate">%</h2>
                </div>
                <div class="miniCard span2">
                    <h3>Lost Opportunities</h3>
                    <h2 id="lost_opportunities"></h2>
                </div>
                <div class="miniCard span2">
                    <h3>Lost Purchase</h3>
                    <h2 id="lost_purchases">₹ </h2>
                </div>
                <div class="miniCard span2">
                    <h3>Churn Rate %</h3>
                    <h2 id="churn_rate">%</h2>
                </div>
            </div>
        </div>
        <!-- CHURN REASONS -->
        <div class="card" id="churnReason">
            <p>Churn Reasons</p>
            <canvas class="bar" id="churnReasons"></canvas>
        </div>

        <!-- NUMBER OF OPPORTUNITIES AND AVERAGE PURCHASE VALUE BY PACKAGE -->
        <div class="card half-span">
            <p>Number of Opportunities and Average Purchase Value by Package</p>
            <canvas class="bar" id="mainChart"></canvas>
        </div>

        <!-- PREVIOUS YEAR SALES AND PROFIT BY MARKET -->
        <div class="card full-span" id="specialCase1" style="overflow: hidden;">
            <p>Sales by Market YOY</p>
            <canvas class="line" id="prevSalesAndProfitByMarket"></canvas>
        </div>


        <!-- SALES AND PROFIT BY MARKET -->
        <div class="card full-span" id="specialCase2" style="overflow: hidden;">
            <p>Profit by Market YOY</p>
            <canvas class="line" id="salesAndProfitByMarket"></canvas>
        </div>


        <!-- TABLE TO DISPLAY MULTIPLE COLUMNS OF THE DATASET -->
        <div class="card full-span">
            <table class="mainTable">
                <thead>
                    <tr>
                        <th>Stage</th>
                        <th>Opportunity_Name</th>
                        <th>Sum of Opportunity_id</th>
                        <th>Comment</th>
                        <th>Package</th>
                    </tr>
                </thead>
                <tbody id="dataBody">

                </tbody>
            </table>
        </div>
    </div>


    <?php include "modal.html" ?>

    <script src="it_sales.js"></script>
</body>

</html>