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

require_once "db.php";

// Year filter
$year  = isset($_GET['year']) ? $_GET['year'] : date('Y');

// ---------------- SALES ----------------
$sqlSales = "SELECT s.sale_id, s.invoice_no, s.sale_date, c.customer_name,
                    IFNULL(SUM(si.subtotal),0) as total_amount,
                    IFNULL(SUM(si.qty),0) as total_qty
             FROM sales s
             LEFT JOIN sale_items si ON s.sale_id=si.sale_id
             LEFT JOIN customers c ON s.customer_id=c.customer_id
             WHERE YEAR(s.sale_date)='$year'
             GROUP BY s.sale_id
             ORDER BY s.sale_date DESC";
$resSales = $conn->query($sqlSales);
$sales=[]; $sumSalesAmount=0; $sumSalesQty=0;
if($resSales){ while($r=$resSales->fetch_assoc()){ $sales[]=$r; $sumSalesAmount+=$r['total_amount']; $sumSalesQty+=$r['total_qty']; } }

// ---------------- PURCHASE ----------------
$sqlPur = "SELECT p.purchase_id, p.invoice_no, p.purchase_date, sup.supplier_name,
                  IFNULL(SUM(pi.subtotal),0) as total_amount,
                  IFNULL(SUM(pi.qty),0) as total_qty
           FROM purchases p
           LEFT JOIN purchase_items pi ON p.purchase_id=pi.purchase_id
           LEFT JOIN suppliers sup ON p.supplier_id=sup.supplier_id
           WHERE YEAR(p.purchase_date)='$year'
           GROUP BY p.purchase_id
           ORDER BY p.purchase_date DESC";
$resPur = $conn->query($sqlPur);
$purchases=[]; $sumPurAmount=0; $sumPurQty=0;
if($resPur){ while($r=$resPur->fetch_assoc()){ $purchases[]=$r; $sumPurAmount+=$r['total_amount']; $sumPurQty+=$r['total_qty']; } }

// ---------------- EXPENSE ----------------
$sqlExp = "SELECT e.expense_id, e.expense_name, e.amount, DATE(e.created_at) as expense_date
           FROM expenses e
           WHERE YEAR(e.created_at)='$year'
           ORDER BY e.created_at DESC";
$resExp = $conn->query($sqlExp);
$expenses=[]; $sumExpense=0;
if($resExp){ 
    while($r=$resExp->fetch_assoc()){ 
        $expenses[]=$r; 
        $sumExpense+=$r['amount']; 
    } 
}

?>
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Yearly Report</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <style>
        
    </style>
</head>

<body class="yearly-report-page">
   <!-- Global header start -->
   <?php include("global/header.php"); ?>
   <!-- Global header end -->

   <main class="main">
        <header class="topbar">
            <button class="hamburger" id="hamburger">☰</button>
            <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Yearly Report</div>
            <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->
            <div class="profile">
                <button class="profile-btn" id="profileBtn">
                    <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">

                <!-- Filter box -->
                <form method="get" class="filter-box">
                    <div class="form-group" style="display: flex; align-items: center; gap: 5px;">
                        <label>Year:</label>
                        <select name="year">
                          <?php for($y=date('Y')-10;$y<=date('Y');$y++): ?>
                            <option value="<?php echo $y; ?>" <?php if($year==$y) echo "selected"; ?>><?php echo $y; ?></option>
                          <?php endfor; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">Search</button>
                    </div>
                    <div class="form-group">
                        <a href="yearly-report.php"><button type="button" class="filter-reset-btn">Reset</button></a>
                    </div>
                    <div class="form-group">
                        <button type="button" class="filter-print-btn btn btn-print" onclick="printReport()">Print</button>
                    </div>
                </form>

                <!-- Tabs -->
                <div class="tabs">
                    <div class="tab-buttons">
                        <button type="button" class="active" data-tab="sales">Sales</button>
                        <button type="button" data-tab="purchase">Purchase</button>
                        <button type="button" data-tab="expense">Expenses</button>
                    </div>

                    <!-- Sales Table -->
                    <div class="tab-content active" id="sales">
                        <table id="salesTable" class="display">
                            <thead>
                                <tr><th>#</th><th>Invoice</th><th>Date</th><th>Customer</th><th>Qty</th><th>Total (à§³)</th></tr>
                            </thead>
                            <tbody>
                                <?php $i=1; foreach($sales as $row): ?>
                                <tr>
                                    <td><?php echo $i++; ?></td>
                                    <td><?php echo htmlspecialchars($row['invoice_no']); ?></td>
                                    <td><?php echo htmlspecialchars($row['sale_date']); ?></td>
                                    <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
                                    <td><?php echo (int)$row['total_qty']; ?></td>
                                    <td style="text-align:right;"><?php echo number_format($row['total_amount'],2); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="4">Total</td>
                                    <td><?php echo $sumSalesQty; ?></td>
                                    <td style="text-align:right;"><?php echo number_format($sumSalesAmount,2); ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Purchase Table -->
                    <div class="tab-content" id="purchase">
                        <table id="purchaseTable" class="display">
                            <thead>
                                <tr><th>#</th><th>Invoice</th><th>Date</th><th>Supplier</th><th>Qty</th><th>Total (à§³)</th></tr>
                            </thead>
                            <tbody>
                                <?php $i=1; foreach($purchases as $row): ?>
                                <tr>
                                    <td><?php echo $i++; ?></td>
                                    <td><?php echo htmlspecialchars($row['invoice_no']); ?></td>
                                    <td><?php echo htmlspecialchars($row['purchase_date']); ?></td>
                                    <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                    <td><?php echo (int)$row['total_qty']; ?></td>
                                    <td style="text-align:right;"><?php echo number_format($row['total_amount'],2); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="4">Total</td>
                                    <td><?php echo $sumPurQty; ?></td>
                                    <td style="text-align:right;"><?php echo number_format($sumPurAmount,2); ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Expense Table -->
<div class="tab-content" id="expense">
    <table id="expenseTable" class="display">
        <thead>
            <tr><th>#</th><th>Date</th><th>Expense Name</th><th>Amount (৳)</th></tr>
        </thead>
        <tbody>
            <?php $i=1; foreach($expenses as $row): ?>
            <tr>
                <td><?php echo $i++; ?></td>
                <td><?php echo htmlspecialchars($row['expense_date']); ?></td>
                <td><?php echo htmlspecialchars($row['expense_name']); ?></td>
                <td style="text-align:right;"><?php echo number_format($row['amount'],2); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3">Total</td>
                <td style="text-align:right;"><?php echo number_format($sumExpense,2); ?></td>
            </tr>
        </tfoot>
    </table>
</div>


                </div>
            </div>
        </section>
   </main>

   <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
   <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
   <script>
   $(function() {
       $('#salesTable').DataTable({ pageLength: 10, lengthChange: false });
       $('#purchaseTable').DataTable({ pageLength: 10, lengthChange: false });
       $('#expenseTable').DataTable({ pageLength: 10, lengthChange: false });

       $('.tab-buttons button').on('click', function() {
           var tab = $(this).data('tab');
           $('.tab-buttons button').removeClass('active');
           $(this).addClass('active');
           $('.tab-content').removeClass('active');
           $('#' + tab).addClass('active');
       });
   });

   function printReport() {
       var activeTab = $('.tab-buttons button.active').data('tab');
       var tableHtml = document.getElementById(activeTab + "Table").outerHTML;
       var title = "Yearly " + activeTab.charAt(0).toUpperCase() + activeTab.slice(1) + " Report";
       var win = window.open('', '_blank');
       win.document.write(`
           <html><head><title>${title}</title>
           <style>
             body { font-family:Arial,sans-serif; margin:20px; }
             h2,h4,h3 { text-align:center; margin:0; }
             table { width:100%; border-collapse:collapse; margin-top:20px; }
             th,td { border:1px solid #ccc; padding:6px; }
             th { background:#f3f4f6; }
             tfoot td { font-weight:bold; background:#f9fafb; }
             .footer { margin-top:40px; text-align:right; }
                 /* Global Print css */
.global-print .heading{
    text-align: center;
}
.global-print .print-bg{
    position: relative;
    height: auto !important;
}
.global-print .print-bg img{
    width: 300px;
    position: absolute;
    z-index: -1;
    top: 350px;
    left: 50%;
    transform: translate(-50%, -50%);
    opacity: .2;
}
.global-print .heading p{
    margin: 0;
    margin-bottom: 10px;
}
           </style>
           </head><body class="global-print">
             <?php
    include("global/global-print-heading.php");
?>
            <main class="print-body-content">
             <h3>${title} (<?php echo $year; ?>)</h3>
             ${tableHtml}
             </main>
             <?php
    include("global/global-print-footer.php");
?>
           </body></html>
       `);
       win.document.close();
       win.print();
   }
   </script>
   <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>
</body>
</html>
