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

ini_set('display_errors',1);
error_reporting(E_ALL);

/* =========================
   FILTER
========================= */
$from = $_GET['from_month'] ?? '';
$to   = $_GET['to_month'] ?? '';

$whereSalary  = "";
$whereAdvance = "";
$whereBonus   = "";
$monthsCount  = 1;

if ($from && $to) {

    $whereSalary  = " AND sp.salary_month BETWEEN '$from' AND '$to' ";
    $whereAdvance = " AND DATE_FORMAT(ap.advance_date,'%Y-%m') BETWEEN '$from' AND '$to' ";
    $whereBonus   = " AND DATE_FORMAT(bp.bonus_date,'%Y-%m') BETWEEN '$from' AND '$to' ";

    $start = new DateTime($from . '-01');
    $end   = new DateTime($to . '-01');
    $end->modify('+1 month');

    $diff = $start->diff($end);
    $monthsCount = ($diff->y * 12) + $diff->m;
}

/* =========================
   EMPLOYEE REPORT QUERY
========================= */
$sql = "
SELECT
    e.employee_id,
    e.employee_name,
    e.phone,
    d.title AS designation,
    e.base_salary,

    /* SALARY PAID */
    IFNULL(SUM(DISTINCT sp.paid_amount),0) AS salary_paid,

    /* ADVANCE PAID */
    (
        SELECT IFNULL(SUM(ap.amount),0)
        FROM advance_pay ap
        WHERE ap.employee_id = e.employee_id
        $whereAdvance
    ) AS advance_paid,

    /* BONUS */
    (
        SELECT IFNULL(SUM(bp.bonus_amount),0)
        FROM bonus_pay bp
        WHERE bp.employee_id = e.employee_id
        $whereBonus
    ) 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
    $whereSalary

WHERE e.status='Active'
GROUP BY e.employee_id
ORDER BY e.employee_name ASC
";

$result = $conn->query($sql);
if (!$result) {
    die("SQL Error: " . $conn->error);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Employee Report</title>
<link rel="stylesheet" href="https://insaf.shopnofy.com/update9/css/style.css">
<style>
@media print {
    .filter-box,.btn { display:none; }
}
</style>
</head>

<body>
<?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> 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">

<!-- FILTER -->
<form method="get" class="filter-box" style="display:flex;gap:10px;align-items:center;">
    <input type="month" name="from_month" id="from_month" value="<?= $_GET['from_month'] ?? '' ?>">
<input type="month" name="to_month" id="to_month" value="<?= $_GET['to_month'] ?? '' ?>">
    <button class="btn">Search</button>
    <a href="employee-report.php" class="btn btn-danger">Reset</a>
    <button type="button" class="btn btn-secondary" onclick="printReport()">
    🖨️ Print
</button>

</form>

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

<?php
$sl=1;
$g_base=$g_salary=$g_advance=$g_paid=$g_due=$g_bonus=$g_total=0;

while($row = $result->fetch_assoc()):

    $base_total   = $row['base_salary'] * $monthsCount;
    $salary_paid  = $row['salary_paid'];
    $advance_paid = $row['advance_paid'];
    $total_paid   = $salary_paid + $advance_paid;
    $due          = max(0, $base_total - $total_paid);
    $bonus        = $row['bonus_paid'];
    $paid_bonus   = $total_paid + $bonus;

    $g_base    += $base_total;
    $g_salary  += $salary_paid;
    $g_advance += $advance_paid;
    $g_paid    += $total_paid;
    $g_due     += $due;
    $g_bonus   += $bonus;
    $g_total   += $paid_bonus;
?>
<tr>
    <td><?= $sl++ ?></td>
    <td><?= htmlspecialchars($row['employee_name']) ?></td>
    <td><?= htmlspecialchars($row['designation']) ?></td>
    <td><?= htmlspecialchars($row['phone']) ?></td>
    <td><?= number_format($base_total,2) ?></td>
    <td><?= number_format($salary_paid,2) ?></td>
    <td><?= number_format($advance_paid,2) ?></td>
    <td><?= number_format($total_paid,2) ?></td>
    <td><?= number_format($due,2) ?></td>
    <td><?= number_format($bonus,2) ?></td>
    <td><?= number_format($paid_bonus,2) ?></td>
</tr>
<?php endwhile; ?>
</tbody>

<tfoot>
<tr>
    <th colspan="4">TOTAL</th>
    <th><?= number_format($g_base,2) ?></th>
    <th><?= number_format($g_salary,2) ?></th>
    <th><?= number_format($g_advance,2) ?></th>
    <th><?= number_format($g_paid,2) ?></th>
    <th><?= number_format($g_due,2) ?></th>
    <th><?= number_format($g_bonus,2) ?></th>
    <th><?= number_format($g_total,2) ?></th>
</tr>
</tfoot>
</table>

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


<script>
function printReport() {

    let from = document.getElementById('from_month').value;
    let to   = document.getElementById('to_month').value;

    if(!from || !to){
        alert("Please select From Month and To Month");
        return;
    }

    let url = `employee-report-print.php?from_month=${from}&to_month=${to}`;
    window.open(url, '_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>
