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

require_once "db.php"; // your DB connection

// Default filter = last 12 months
$to_date   = isset($_GET['to_date']) ? $_GET['to_date'] : date("Y-m");
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date("Y-m", strtotime("-11 months"));

// Detect if user searched by exact dates (Y-m-d)
$is_date_to_date = (strlen($from_date) == 10 && strlen($to_date) == 10);

// Report function
function get_report($conn, $from_date, $to_date, $is_date_to_date) {
    if ($is_date_to_date) {
        // Date-to-date (daily)
        $sql = "SELECT DATE(s.sale_date) as period,
                       SUM(s.total) as sales,
                       (SELECT IFNULL(SUM(p.total),0) 
                        FROM purchases p 
                        WHERE DATE(p.purchase_date)=DATE(s.sale_date)) as cogs,
                       (SELECT IFNULL(SUM(e.amount),0) 
                        FROM expenses e 
                        WHERE DATE(e.created_at)=DATE(s.sale_date)) as expenses
                FROM sales s
                WHERE DATE(s.sale_date) BETWEEN ? AND ?
                GROUP BY period
                ORDER BY period ASC";
    } else {
        // Monthly (last 12 months or filter months)
        $sql = "SELECT DATE_FORMAT(s.sale_date,'%Y-%m') as period,
                       SUM(s.total) as sales,
                       (SELECT IFNULL(SUM(p.total),0) 
                        FROM purchases p 
                        WHERE DATE_FORMAT(p.purchase_date,'%Y-%m')=DATE_FORMAT(s.sale_date,'%Y-%m')) as cogs,
                       (SELECT IFNULL(SUM(e.amount),0) 
                        FROM expenses e 
                        WHERE DATE_FORMAT(e.created_at,'%Y-%m')=DATE_FORMAT(s.sale_date,'%Y-%m')) as expenses
                FROM sales s
                WHERE DATE_FORMAT(s.sale_date,'%Y-%m') BETWEEN ? AND ?
                GROUP BY period
                ORDER BY period ASC";
    }

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from_date, $to_date);
    $stmt->execute();
    $res = $stmt->get_result();

    $rows = [];
    while ($r = $res->fetch_assoc()) {
        $r['gross_profit'] = $r['sales'] - $r['cogs'];
        $r['net_profit']   = $r['gross_profit'] - $r['expenses'];
        $rows[] = $r;
    }
    return $rows;
}

$data = get_report($conn, $from_date, $to_date, $is_date_to_date);

// Totals
$total_sales = $total_cogs = $total_gross = $total_exp = $total_net = 0;
foreach ($data as $row) {
    $total_sales += $row['sales'];
    $total_cogs  += $row['cogs'];
    $total_gross += $row['gross_profit'];
    $total_exp   += $row['expenses'];
    $total_net   += $row['net_profit'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Profit Loss Report</title>
  <link rel="stylesheet" href="css/style.css">
  <style>



  </style>
</head>
<body>
<!-- Global header start -->
        <?php
            include("global/header.php");
         ?>
        <!-- Global header end -->

            <!-- Main -->
            <main class="main">
                <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> Profit Loss Report</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 $_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="container">
      <h2>Profit Loss Report</h2>
      <form method="get" class="filter-box">
        <input type="date" id="from_date" name="from_date" value="<?php echo strlen($from_date)==7?$from_date.'-01':$from_date; ?>">
<input type="date" id="to_date" name="to_date" value="<?php echo strlen($to_date)==7?$to_date.'':$to_date; ?>">

        <button type="submit">Search</button>
        <a href="profit-loss-report.php"><button class="filter-reset-btn" type="button">Reset</button></a>
        <button type="button" id="printBtn" class="filter-print-btn btn btn-secondary">🖨️ Print</button>
      </form>

      <table>
        <thead>
          <tr>
            <th><?php echo $is_date_to_date ? "Date" : "Month"; ?></th>
            <th>Sales</th>
            <th>Cost of Goods Sold</th>
            <th>Gross Profit</th>
            <th>Expenses</th>
            <th>Net Profit</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($data): ?>
            <?php foreach ($data as $row): ?>
              <tr>
                <td><?php echo $is_date_to_date ? date("d M Y", strtotime($row['period'])) : date("M Y", strtotime($row['period']."-01")); ?></td>
                <td><?php echo number_format($row['sales'],2); ?></td>
                <td><?php echo number_format($row['cogs'],2); ?></td>
                <td><?php echo number_format($row['gross_profit'],2); ?></td>
                <td><?php echo number_format($row['expenses'],2); ?></td>
                <td><?php echo number_format($row['net_profit'],2); ?></td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr><td colspan="6">No data available</td></tr>
          <?php endif; ?>
        </tbody>
        <tfoot>
          <tr>
            <td>Total</td>
            <td><?php echo number_format($total_sales,2); ?></td>
            <td><?php echo number_format($total_cogs,2); ?></td>
            <td><?php echo number_format($total_gross,2); ?></td>
            <td><?php echo number_format($total_exp,2); ?></td>
            <td><?php echo number_format($total_net,2); ?></td>
          </tr>
        </tfoot>
      </table>
    </div>
  </section>
</main>

 <script>
            // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault(); // keep as a toggle, no page jump
                    const currentItem = btn.parentElement; // .has-submenu
                    const isOpen = currentItem.classList.contains("open");

                    // Close other open menus (accordion behavior)
                    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");
                        }
                    });

                    // Toggle current
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });

            // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
            document.querySelectorAll(".submenu").forEach((ul) => {
                ul.addEventListener("click", (e) => {
                    e.stopPropagation();
                });
            });

            // Mobile: show/hide sidebar
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => {
                sidebar.classList.toggle("active");
            });

            // Close sidebar when clicking outside on small screens
            document.addEventListener("click", (e) => {
                const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                if (!isClickInside && sidebar.classList.contains("active")) {
                    sidebar.classList.remove("active");
                }
            });

            // Profile dropdown
            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> 
  <script>
    document.addEventListener("DOMContentLoaded", function() {
        const printBtn = document.getElementById("printBtn");
        if (printBtn) {
            printBtn.addEventListener("click", function() {
                let from_date = document.getElementById("from_date").value;
                let to_date = document.getElementById("to_date").value;

                if (!from_date || !to_date) {
                    alert("⚠️ Please select both From and To dates before printing.");
                    return;
                }

                window.open("profit_loss_print.php?from_date=" + from_date + "&to_date=" + to_date, "_blank");
            });
        }
    });
    </script>

</body>
</html>
