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

/* ---------------- CREATE / UPDATE ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $employee_id = intval($_POST['employee_id']);
    $advance_date = $_POST['advance_date'];
    $amount = floatval($_POST['amount']);
    $note = trim($_POST['note']);

    if ($_POST['action'] === 'create') {
        $stmt = $conn->prepare("
            INSERT INTO advance_pay (employee_id, advance_date, amount, note)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("isds", $employee_id, $advance_date, $amount, $note);
        $stmt->execute();
        $stmt->close();
        header("Location: advance-pay.php?success=1");
        exit;
    }

    if ($_POST['action'] === 'edit') {
        $id = intval($_POST['id']);
        $stmt = $conn->prepare("
            UPDATE advance_pay
            SET employee_id=?, advance_date=?, amount=?, note=?
            WHERE advance_id=?
        ");
        $stmt->bind_param("isdsi", $employee_id, $advance_date, $amount, $note, $id);
        $stmt->execute();
        $stmt->close();
        header("Location: advance-pay.php?updated=1");
        exit;
    }
}

/* ---------------- DELETE ---------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM advance_pay WHERE advance_id=$id");
    header("Location: advance-pay.php?deleted=1");
    exit;
}

/* ---------------- FETCH DATA ---------------- */
$rows = $conn->query("
    SELECT a.*, e.employee_name, d.title AS designation
    FROM advance_pay a
    JOIN employees e ON a.employee_id=e.employee_id
    LEFT JOIN designation d ON e.designation_id=d.designation_id
    ORDER BY a.advance_id DESC
");

$employees = $conn->query("
    SELECT employee_id, employee_name
    FROM employees WHERE status='Active'
    ORDER BY employee_name
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Designation List</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,0.5);justify-content:center;align-items:center}
.modal-content{background:#fff;padding:20px;border-radius:10px;width:420px;max-width:95%}
.modal-content input{
    margin-bottom: 10px;
}
.modal-content select{
    margin-bottom: 10px;
}
.close{float:right;cursor:pointer;font-weight:bold}
.alert {
    padding: 12px 18px;
    border-radius: 6px;
    margin-bottom: 15px;
    font-weight: 500;
    text-align: center;
}
.alert.success { background:#d1fae5;color:#065f46;border:1px solid #10b981; }
.alert.error { background:#fee2e2;color:#991b1b;border:1px solid #ef4444; }
</style>
</head>

<body class="customer-page">

<?php include("global/header.php"); ?>

<main class="main">
<header class="topbar">
    <button class="hamburger" id="hamburger">☰</button>
    <div style="margin-left:8px;font-weight:600;">Dashboard > Advance Pay</div>

    <?php include("global/notify.php"); ?>

    <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" />
        </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="openCreate()">➕ Add Advance</button>
</div>


<table id="advanceTable">
<thead>
<tr>
    <th>ID</th>
    <th>Employee</th>
    <th>Designation</th>
    <th>Date</th>
    <th>Amount</th>
    <th>Note</th>
    <th>Action</th>
</tr>
</thead>
<tbody>

<?php while($r=$rows->fetch_assoc()): ?>
<tr>
<td><?= $r['advance_id']; ?></td>
<td><?= htmlspecialchars($r['employee_name']); ?></td>
<td><?= htmlspecialchars($r['designation']); ?></td>
<td><?= $r['advance_date']; ?></td>
<td><?= number_format($r['amount'],2); ?></td>
<td><?= htmlspecialchars($r['note']); ?></td>
<td>
    <button class="btn" onclick='openEdit(<?= json_encode($r); ?>)'>Edit</button>
    <a class="btn btn-danger"
       href="?delete=<?= $r['advance_id']; ?>"
       onclick="return confirm('Delete this advance?')">Delete</a>
    <button type="button" class="btn" onclick="printAdvance(<?= (int)$r['advance_id'] ?>)">
    Print
</button>

</td>
</tr>
<?php endwhile; ?>

</tbody>
</table>

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

<!-- ================= CREATE MODAL ================= -->
<div class="modal" id="createModal">
<div class="modal-content">
<span class="close" onclick="closeModal('createModal')">&times;</span>
<h3>Add Advance Pay</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']; ?>"><?= $e['employee_name']; ?></option>
<?php endwhile; ?>
</select>

<label>Advance Month Date</label>
<input type="date" name="advance_date" required>

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

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

<br>
<button class="btn submit-btn">Save</button>
</form>
</div>
</div>

<!-- ================= EDIT MODAL ================= -->
<div class="modal" id="editModal">
<div class="modal-content">
<span class="close" onclick="closeModal('editModal')">&times;</span>
<h3>Edit Advance Pay</h3>

<form method="post">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="id" id="editId">

<label>Employee</label>
<select name="employee_id" id="editEmployee"></select>

<label>Advance month Date</label>
<input type="date" name="advance_date" id="editDate">

<label>Amount</label>
<input type="number" step="0.01" name="amount" id="editAmount">

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

<br>
<button class="btn submit-btn">Update</button>
</form>
</div>
</div>

<script>
// ---------- MODAL ----------
function openCreate(){
    document.getElementById('createModal').style.display='flex';
}
function closeModal(id){
    document.getElementById(id).style.display='none';
}

// ---------- EDIT ----------
function openEdit(data){
    document.getElementById('editId').value = data.advance_id;
    document.getElementById('editDate').value = data.advance_date;
    document.getElementById('editAmount').value = data.amount;
    document.getElementById('editNote').value = data.note;

    let sel = document.getElementById('editEmployee');
    sel.innerHTML = document.querySelector('select[name="employee_id"]').innerHTML;
    sel.value = data.employee_id;

    document.getElementById('editModal').style.display='flex';
}


</script>
<script>
function printAdvance(id){
    window.open(
        'advance-pay-print.php?advance_id=' + id,
        '_blank',
        'width=900,height=700'
    );
}
</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>

<script>
// Sidebar / profile dropdown same as customer page
document.getElementById("hamburger").addEventListener("click", () => {
    document.getElementById("sidebar").classList.toggle("active");
});

// Modal functions
function openCreateModal() {
    document.getElementById("createModal").style.display = "flex";
}

function openEditModal(data) {
    document.getElementById("editId").value = data.id;
    document.getElementById("editTitle").value = data.title;
    document.getElementById("editDesc").value = data.description;
    document.getElementById("editModal").style.display = "flex";
}

function closeModal(id) {
    document.getElementById(id).style.display = "none";
}

window.onclick = function(e) {
    if (e.target.classList.contains("modal")) e.target.style.display = "none";
};

// Auto-hide alerts
setTimeout(() => {
    let a = document.querySelector('.alert');
    if (a) a.style.display = 'none';
}, 4000);
</script>

</body>
</html>
