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

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

/* ======================
   CREATE BONUS
====================== */
if ($_SERVER['REQUEST_METHOD']==='POST' && $_POST['action']=='create') {

    $employee_id  = (int)$_POST['employee_id'];
    $bonus_type   = trim($_POST['bonus_type']);
    $bonus_amount = floatval($_POST['bonus_amount']);
    $bonus_date   = $_POST['bonus_date'];
    $note         = trim($_POST['note']);

    if ($employee_id && $bonus_amount > 0) {
        $stmt = $conn->prepare("
            INSERT INTO bonus_pay
            (employee_id, bonus_type, bonus_amount, bonus_date, note)
            VALUES (?,?,?,?,?)
        ");
        $stmt->bind_param(
            "isdss",
            $employee_id,
            $bonus_type,
            $bonus_amount,
            $bonus_date,
            $note
        );
        $stmt->execute();
    }

    header("Location: bonus-pay.php");
    exit;
}

/* DELETE */
if (isset($_GET['delete'])) {
    $conn->query("DELETE FROM bonus_pay WHERE bonus_id=".(int)$_GET['delete']);
    header("Location: bonus-pay.php");
    exit;
}

/* DATA */
$employees = $conn->query("
    SELECT employee_id, employee_name
    FROM employees
    WHERE status='Active'
");

$bonuses = $conn->query("
    SELECT 
        b.*, 
        e.employee_name
    FROM bonus_pay b
    JOIN employees e ON b.employee_id = e.employee_id
    ORDER BY b.bonus_id DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bonus Pay</title>
<link rel="stylesheet" href="css/style.css">
<style>
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);justify-content:center;align-items:center}
.modal-content{background:#fff;padding:20px;border-radius:10px;width:420px}
.modal-content input{
    margin-bottom: 10px;
}
.modal-content select{
    margin-bottom: 10px;
}
.modal-content textarea{
    margin-bottom: 10px;
}
</style>
</head>

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

<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> Bonus Pay</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 class="filter-box">
<button class="btn" onclick="openModal()">➕ Pay Bonus</button>
</div>

<table>
<thead>
<tr>
<th>#</th>
<th>Employee</th>
<th>Bonus Type</th>
<th>Amount</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $i=1; while($b=$bonuses->fetch_assoc()): ?>
<tr>
<td><?= $i++ ?></td>
<td><?= htmlspecialchars($b['employee_name']) ?></td>
<td><?= htmlspecialchars($b['bonus_type']) ?></td>
<td><?= number_format($b['bonus_amount'],2) ?></td>
<td><?= $b['bonus_date'] ?></td>
<td>

<a href="?delete=<?= $b['bonus_id'] ?>" class="btn btn-danger"
onclick="return confirm('Delete bonus?')">Delete</a>
<button class="btn" onclick="printBonus(<?= (int)$b['bonus_id'] ?>)">Print</button>


<script>
function printBonus(id){
    if(!id){
        alert('Invalid Bonus ID');
        return;
    }

    window.open(
        'bonus-pay-print.php?bonus_id=' + id,
        '_blank',
        'width=900,height=700'
    );
}
</script>


</td>
</tr>
<?php endwhile ?>
</tbody>
</table>

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

<!-- BONUS MODAL -->
<div class="modal" id="bonusModal">
<div class="modal-content">
<h3>Pay Bonus</h3>

<form method="post">
<input type="hidden" name="action" value="create">

<label>Employee</label>
<select name="employee_id" required>
<option value="">Select</option>
<?php while($e=$employees->fetch_assoc()): ?>
<option value="<?= $e['employee_id'] ?>">
<?= htmlspecialchars($e['employee_name']) ?>
</option>
<?php endwhile ?>
</select>

<label>Bonus Type</label>
<input type="text" name="bonus_type" placeholder="Festival / Event" required>

<label>Bonus Amount</label>
<input type="number" step="0.01" name="bonus_amount" required>

<label>Bonus Date</label>
<input type="date" name="bonus_date" required>

<label>Note</label>
<textarea name="note"></textarea>

<br>
<button class="btn">Save</button>
<button type="button" class="btn btn-danger" onclick="closeModal()">Cancel</button>
</form>
</div>
</div>



<script>
function openModal(){document.getElementById('bonusModal').style.display='flex'}
function closeModal(){document.getElementById('bonusModal').style.display='none'}

document.getElementById("hamburger").addEventListener("click",()=>{
    document.getElementById("sidebar").classList.toggle("active");
});
</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>
