<?php
include "auth.php";
checkPermission(['admin','manager','staff']); // allow all roles here
?>

<?php


require_once "db.php"; // expects $conn (mysqli)

$queryErrors = [];

/**
 * Run a SUM query and return float total. On failure returns 0.00 and records error.
 * Expects the query to return a column named `total`.
 */
function fetch_sum($conn, $sql, &$queryErrors) {
    $res = $conn->query($sql);
    if ($res === false) {
        $queryErrors[] = $conn->error . " — SQL: " . $sql;
        return 0.00;
    }
    $row = $res->fetch_assoc();
    return isset($row['total']) ? (float)$row['total'] : 0.00;
}

// Dates
$today = date('Y-m-d');
$month = date('Y-m');   // YYYY-MM
$year  = date('Y');     // YYYY

// Today's Sales (sales.sale_date)
$todays_sales = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM sales WHERE sale_date = '{$today}'", $queryErrors);

// Today's Purchases (purchases.purchase_date)
$todays_purchase = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM purchases WHERE purchase_date = '{$today}'", $queryErrors);

// Monthly aggregates (use sale_date / purchase_date; expenses use created_at)
$monthly_sales = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM sales WHERE DATE_FORMAT(sale_date, '%Y-%m') = '{$month}'", $queryErrors);
$monthly_purchases = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM purchases WHERE DATE_FORMAT(purchase_date, '%Y-%m') = '{$month}'", $queryErrors);
$monthly_expenses = fetch_sum($conn, "SELECT IFNULL(SUM(amount),0) AS total FROM expenses WHERE DATE_FORMAT(created_at, '%Y-%m') = '{$month}'", $queryErrors);

// Monthly customers / suppliers due
$monthly_customers_due = fetch_sum($conn, "SELECT IFNULL(SUM(due),0) AS total FROM sales WHERE DATE_FORMAT(sale_date, '%Y-%m') = '{$month}'", $queryErrors);
$monthly_suppliers_due = fetch_sum($conn, "SELECT IFNULL(SUM(due),0) AS total FROM purchases WHERE DATE_FORMAT(purchase_date, '%Y-%m') = '{$month}'", $queryErrors);

// Monthly profit = sales - (purchases + expenses)
$monthly_profit = $monthly_sales - ($monthly_purchases + $monthly_expenses);

// Yearly aggregates
$yearly_sales = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM sales WHERE DATE_FORMAT(sale_date, '%Y') = '{$year}'", $queryErrors);
$yearly_purchases = fetch_sum($conn, "SELECT IFNULL(SUM(total),0) AS total FROM purchases WHERE DATE_FORMAT(purchase_date, '%Y') = '{$year}'", $queryErrors);
$yearly_expenses = fetch_sum($conn, "SELECT IFNULL(SUM(amount),0) AS total FROM expenses WHERE DATE_FORMAT(created_at, '%Y') = '{$year}'", $queryErrors);
$yearly_profit = $yearly_sales - ($yearly_purchases + $yearly_expenses);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>POS Dashboard</title>
    <link rel="stylesheet" href="css/style.css" />
    <style>

      .big { font-size:20px; font-weight:700; color:#111827; margin-top:6px; }
      .debug { margin-top:12px; padding:10px; background:#fff7ed; border:1px solid #ffd7a8; border-radius:6px; color:#92400e; font-size:13px; }
    </style>
</head>
<body class="dashboard-page">
    <?php include("global/header.php"); ?>

    <main class="main">
        <div class="overlay">
            <header class="topbar">
            <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>
            <div style="margin-left: 8px; font-weight: 600;">Dashboard <span class="topbar-menu-space"> > </span> Home</div>
            <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->
             
            <div class="profile">
                <button class="profile-btn" id="profileBtn" aria-expanded="false">
                    <span>Welcome <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                    <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                </button>
                <nav class="dropdown" id="profileDropdown">
                    <a href="profile.php">Profile Settings</a>
                    <a href="users.php">Users Settings</a>
                    <a href="logout.php">Logout</a>
                </nav>
            </div>
        </header>

        <section class="content">
            <div class="cards">
                <div class="card">
                    <h4>Today's Sales</h4>
                    <div class="big">৳ <?php echo number_format($todays_sales, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Today's Purchase</h4>
                    <div class="big">৳ <?php echo number_format($todays_purchase, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Monthly Profit (<?php echo date('F Y'); ?>)</h4>
                    <div class="big">৳ <?php echo number_format($monthly_profit, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Monthly Customers Total Due</h4>
                    <div class="big">৳ <?php echo number_format($monthly_customers_due, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Monthly Suppliers Total Due</h4>
                    <div class="big">৳ <?php echo number_format($monthly_suppliers_due, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Monthly Total Expense</h4>
                    <div class="big">৳ <?php echo number_format($monthly_expenses, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Yearly Total Profit (<?php echo $year; ?>)</h4>
                    <div class="big">৳ <?php echo number_format($yearly_profit, 2); ?></div>
                </div>

                <div class="card">
                    <h4>Yearly Total Sales Amount (<?php echo $year; ?>)</h4>
                    <div class="big">৳ <?php echo number_format($yearly_sales, 2); ?></div>
                </div>
            </div>

            <?php if (!empty($queryErrors)): ?>
                <div class="debug">
                    <strong>Query warnings:</strong>
                    <ul>
                        <?php foreach ($queryErrors as $qe): ?>
                            <li><?php echo htmlspecialchars($qe); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
        </section>
        <div class="dashboard-logo">
            <img src="images/Logo.png">
        </div>
        </div>
    </main>

    <script>
        // Sidebar accordion & profile dropdown (same behavior as your other pages)
        const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
        submenuButtons.forEach((btn) => {
            btn.addEventListener("click", (e) => {
                e.preventDefault();
                const currentItem = btn.parentElement;
                const isOpen = currentItem.classList.contains("open");
                document.querySelectorAll(".has-submenu.open").forEach((li) => {
                    if (li !== currentItem) {
                        li.classList.remove("open");
                        const b = li.querySelector(".menu-link");
                        if (b) b.setAttribute("aria-expanded", "false");
                    }
                });
                currentItem.classList.toggle("open");
                btn.setAttribute("aria-expanded", String(!isOpen));
            });
        });
        document.querySelectorAll(".submenu").forEach((ul) => ul.addEventListener("click", (e)=>e.stopPropagation()));
        const sidebar = document.getElementById("sidebar");
        const hamburger = document.getElementById("hamburger");
        hamburger.addEventListener("click", () => sidebar.classList.toggle("active"));
        document.addEventListener("click", (e) => {
            if (!sidebar.contains(e.target) && !hamburger.contains(e.target) && sidebar.classList.contains("active")) {
                sidebar.classList.remove("active");
            }
        });
        const profileBtn = document.getElementById("profileBtn");
        const profileDropdown = document.getElementById("profileDropdown");
        profileBtn.addEventListener("click", (e) => {
            e.stopPropagation();
            const open = profileDropdown.classList.toggle("open");
            profileBtn.setAttribute("aria-expanded", String(open));
        });
        document.addEventListener("click", () => profileDropdown.classList.remove("open"));
    </script>


</body>
</html>
