<?php
include "auth.php";
checkPermission(['admin','manager']);
require_once "db.php";

$month = $_GET['month'] ?? date('Y-m');

$sql = "
SELECT 
    e.employee_id,
    e.employee_name,
    e.phone,
    d.title AS designation,
    e.base_salary,

    IFNULL(SUM(DISTINCT sp.paid_amount),0) AS salary_paid,
    IFNULL(SUM(DISTINCT ap.amount),0) AS advance_paid,
    IFNULL(SUM(DISTINCT bp.bonus_amount),0) AS bonus_paid

FROM employees e
LEFT JOIN designation d ON d.designation_id = e.designation_id

LEFT JOIN salary_pay sp 
    ON sp.employee_id = e.employee_id
    AND DATE_FORMAT(sp.pay_date,'%Y-%m') = '$month'

LEFT JOIN advance_pay ap 
    ON ap.employee_id = e.employee_id
    AND DATE_FORMAT(ap.created_at,'%Y-%m') = '$month'

LEFT JOIN bonus_pay bp 
    ON bp.employee_id = e.employee_id
    AND DATE_FORMAT(bp.bonus_date,'%Y-%m') = '$month'

GROUP BY e.employee_id
ORDER BY e.employee_name
";

$result = $conn->query($sql);
if(!$result){ die("SQL Error: ".$conn->error); }
?>
<!DOCTYPE html>
<html>
<head>
<title>Monthly Employee Report</title>
<link rel="stylesheet" href="css/style.css">
<style>
    .filter-reset-btn{
        font-size: 18px;
        border-radius: 6px;
    }
</style>
</head>

<body class="customer-page">
<?php include "global/header.php"; ?>

<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> Monthly Employee 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">

<div>
<form method="get" class="filter-box">
    <div class="form-group">
        <input type="month" name="month" value="<?= htmlspecialchars($month) ?>">
    </div>
    <div class="form-group">
        <button class="btn">Search</button>
    </div>
    <div class="form-group">
        <button type="button" class="btn btn-print" onclick="printMonthly()">🖨 Print</button>
    </div>
    <div class="form-group" style="display: flex;">
        <a href="employee-report-monthly.php" class="btn filter-reset-btn">↻ Reset</a>
    </div>
    
</form>
</div>

<table class="table">
<thead>
<tr>
<th>#</th>
<th>Employee</th>
<th>Designation</th>
<th>Phone</th>
<th>Base Salary</th>
<th>Advance</th>
<th>Salary Paid</th>
<th>Due</th>
<th>Bonus</th>
<th>Total Paid</th>
</tr>
</thead>

<tbody>
<?php
$i=1;
$total_base=$total_adv=$total_salary=$total_due=$total_bonus=$total_paid=0;

while($r=$result->fetch_assoc()):
    $due = max(0, $r['base_salary'] - $r['advance_paid'] - $r['salary_paid']);
    $paid = $r['salary_paid'] + $r['advance_paid'] + $r['bonus_paid'];

    $total_base += $r['base_salary'];
    $total_adv += $r['advance_paid'];
    $total_salary += $r['salary_paid'];
    $total_due += $due;
    $total_bonus += $r['bonus_paid'];
    $total_paid += $paid;
?>
<tr>
<td><?= $i++ ?></td>
<td><?= htmlspecialchars($r['employee_name']) ?></td>
<td><?= htmlspecialchars($r['designation']) ?></td>
<td><?= htmlspecialchars($r['phone']) ?></td>
<td><?= number_format($r['base_salary'],2) ?></td>
<td><?= number_format($r['advance_paid'],2) ?></td>
<td><?= number_format($r['salary_paid'],2) ?></td>
<td><?= number_format($due,2) ?></td>
<td><?= number_format($r['bonus_paid'],2) ?></td>
<td><?= number_format($paid,2) ?></td>
</tr>
<?php endwhile; ?>
</tbody>

<tfoot>
<tr>
<th colspan="4">TOTAL</th>
<th><?= number_format($total_base,2) ?></th>
<th><?= number_format($total_adv,2) ?></th>
<th><?= number_format($total_salary,2) ?></th>
<th><?= number_format($total_due,2) ?></th>
<th><?= number_format($total_bonus,2) ?></th>
<th><?= number_format($total_paid,2) ?></th>
</tr>
</tfoot>
</table>

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

<script>
function printMonthly(){
    let m=document.querySelector('[name="month"]').value;
    if(!m){alert('Select month');return;}
    window.open('employee-report-monthly-print.php?month='+m,'_blank');
}
</script>
<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>
