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

/* -------------------------
   CREATE / EDIT
---------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    if ($_POST['action'] === 'create') {
        if ($title !== "") {
            $stmt = $conn->prepare("INSERT INTO designation (title, description) VALUES (?, ?)");
            $stmt->bind_param("ss", $title, $description);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: designations.php?success=1");
        exit();
    }

    if ($_POST['action'] === 'edit') {
        $id = intval($_POST['designation_id']);
        if ($id > 0 && $title !== "") {
            $stmt = $conn->prepare("UPDATE designation SET title=?, description=? WHERE designation_id=?");
            $stmt->bind_param("ssi", $title, $description, $id);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: designations.php?updated=1");
        exit();
    }
}

/* -------------------------
   DELETE
---------------------------- */
$message = "";
$message_type = "";

if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);

    // check if designation used in employee table
    $check = $conn->prepare("SELECT COUNT(*) AS total FROM employees WHERE designation_id=?");
    $check->bind_param("i", $id);
    $check->execute();
    $result = $check->get_result()->fetch_assoc();
    $check->close();

    if ($result['total'] > 0) {
        $message = "❌ This designation cannot be deleted because it is used by employees.";
        $message_type = "error";
    } else {
        $stmt = $conn->prepare("DELETE FROM designation WHERE designation_id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();

        $message = "✅ Designation deleted successfully.";
        $message_type = "success";
    }
}

/* -------------------------
   SEARCH
---------------------------- */
$search = isset($_GET['search']) ? trim($_GET['search']) : "";
$sql = "SELECT * FROM designation";

if ($search !== "") {
    $s = $conn->real_escape_string($search);
    $sql .= " WHERE title LIKE '%$s%'";
}

$sql .= " ORDER BY designation_id DESC";
$rows = $conn->query($sql);

?>

<!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%;
            }
            .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 > Designation</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>

            <?php if (!empty($message)): ?>
            <div class="alert <?= $message_type ?>"><?= $message ?></div>
            <?php endif; ?>

            <section class="content">
                <div class="container">
                    <div class="filter-box">
                        <form method="get" style="flex: 1; display: flex; gap: 8px">
                            <input
                                type="text"
                                name="search"
                                placeholder="Search designation..."
                                value="<?= htmlspecialchars($search); ?>"
                            />
                            <button class="btn">🔍︎ Search</button>
                        </form>

                        <button class="btn" onclick="openCreateModal()">✚ Create Designation</button>
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Title</th>
                                <th>Description</th>
                                <th style="width: 180px; text-align: center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($rows->num_rows > 0): ?> <?php while ($d = $rows->fetch_assoc()): ?>
                            <tr>
                                <td><?= $d['designation_id']; ?></td>
                                <td><?= htmlspecialchars($d['title']); ?></td>
                                <td><?= htmlspecialchars($d['description']); ?></td>
                                <td style="text-align: center">
                                    <button class="btn" onclick="openEditModal(<?= json_encode($d); ?>)">Edit</button>
                                    <a
                                        class="btn btn-danger"
                                        href="?delete=<?= $d['designation_id']; ?>"
                                        onclick="return confirm('Delete this designation?')"
                                        >Delete</a
                                    >
                                </td>
                            </tr>
                            <?php endwhile; ?> <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: #666">No records found</td>
                            </tr>
                            <?php endif; ?>
                        </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>Create Designation</h3>

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

                    <label>Title</label>
                    <input type="text" name="title" required /><br /><br />

                    <label>Description</label>
                    <textarea name="description" rows="3"></textarea><br /><br />

                    <button class="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 Designation</h3>

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

                    <label>Title</label>
                    <input type="text" name="title" id="editTitle" required /><br /><br />

                    <label>Description</label>
                    <textarea name="description" id="editDesc" rows="3"></textarea><br /><br />

                    <button class="btn">Update</button>
                </form>
            </div>
        </div>

        <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>
        <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>


