Server : LiteSpeed
System : Linux terra.hostitbro.com 5.14.0-611.54.3.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Thu May 7 16:31:24 EDT 2026 x86_64
User : outerorb ( 1091)
PHP Version : 8.1.34
Disable Function : mail
Directory :  /home2/outerorb/emp.outerorbittech.in/admin/

📁 Create New:
⬆️ Upload File:
Current Dir [ Writable ] Root [ Writable ]


OR Upload from URL:
URL: Save as:

📄 File: departments.php

Path: /home2/outerorb/emp.outerorbittech.in/admin/departments.php

Size: 11.25 KB

Permissions: 0666

<?php
require __DIR__ . '/../includes/helpers.php';

require_admin();
ensure_departments_table();

$roleLabel = 'Admin';
$pdo = db();
$flash = flash();
$errors = [];
$formContext = '';
$editId = isset($_GET['edit']) ? (int) $_GET['edit'] : 0;
$editRow = null;
$allowedDepartments = allowed_departments_for_admin();
$deptFilterSql = '';
$deptParams = [];
if (!empty($allowedDepartments)) {
    $ph = [];
    foreach ($allowedDepartments as $idx => $dept) {
        $key = ':dept' . $idx;
        $ph[] = $key;
        $deptParams[$key] = $dept;
    }
    $deptFilterSql = ' AND department IN (' . implode(',', $ph) . ')';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verify_csrf($_POST['csrf_token'])) {
        redirect_with_message('departments.php', 'Session expired. Try again.', 'error');
    }

    $action = $_POST['action'] ?? '';
    $formContext = $action;
    $name = sanitize_text($_POST['name'] ?? '');
    $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

    if ($action === 'edit' && $id) {
        $editId = $id;
    }

    if (in_array($action, ['add', 'edit'], true)) {
        if ($name === '') {
            $errors['name'] = 'Name is required';
        } else {
            $sql = 'SELECT id FROM departments WHERE name = ?' . ($action === 'edit' ? ' AND id != ?' : '');
            $stmt = $pdo->prepare($sql);
            $stmt->execute($action === 'edit' ? [$name, $id] : [$name]);
            if ($stmt->fetch()) {
                $errors['name'] = 'That name already exists';
            }
        }
    }

    if ($action === 'add' && empty($errors)) {
        $stmt = $pdo->prepare('INSERT INTO departments (name) VALUES (?)');
        $stmt->execute([$name]);
        redirect_with_message('departments.php', 'Department added.');
    }

    if ($action === 'edit' && empty($errors)) {
        if (!$id) {
            redirect_with_message('departments.php', 'Invalid department.', 'error');
        }
        $stmt = $pdo->prepare('UPDATE departments SET name = ? WHERE id = ?');
        $stmt->execute([$name, $id]);
        redirect_with_message('departments.php', 'Department updated.');
    }

    if ($action === 'edit' && !empty($errors) && $id) {
        $editRow = ['id' => $id, 'name' => $name];
    }

    if ($action === 'delete') {
        if (!$id) {
            redirect_with_message('departments.php', 'Invalid department.', 'error');
        }

        $stmt = $pdo->prepare('SELECT name FROM departments WHERE id = ?');
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if (!$row) {
            redirect_with_message('departments.php', 'Department not found.', 'error');
        }

        $name = $row['name'];
        $usageSql = 'SELECT COUNT(*) FROM employees WHERE department = ?' . $deptFilterSql;
        $usage = $pdo->prepare($usageSql);
        $usage->execute(array_merge([$name], $deptParams));
        if ((int) $usage->fetchColumn() > 0) {
            redirect_with_message('departments.php', 'Cannot delete: department is used by employees.', 'error');
        }

        $pdo->prepare('DELETE FROM departments WHERE id = ?')->execute([$id]);
        redirect_with_message('departments.php', 'Department deleted.');
    }
}

$listSql = 'SELECT d.*, (SELECT COUNT(*) FROM employees e WHERE e.department = d.name' . $deptFilterSql . ') AS usage_count FROM departments d ORDER BY d.name ASC';
$stmt = $pdo->prepare($listSql);
$stmt->execute($deptParams);
$departments = $stmt->fetchAll();

if ($editRow === null && $editId) {
    foreach ($departments as $row) {
        if ((int) $row['id'] === $editId) {
            $editRow = $row;
            break;
        }
    }

    if (!$editRow) {
        redirect_with_message('departments.php', 'Department not found.', 'error');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Manage Departments</title>
    <link rel="stylesheet" href="../assets/css/style.css?v=<?php echo filemtime(__DIR__ . '/../assets/css/style.css'); ?>" />
    <link rel="stylesheet" href="../assets/css/polish.css?v=<?php echo filemtime(__DIR__ . '/../assets/css/polish.css'); ?>" />
</head>
<body class="dashboard-layout">
<div class="app-wrapper">
    <!-- Include Sidebar -->
    <?php require '_sidebar.php'; ?>

    <!-- MAIN CONTENT -->
    <div class="main-content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="top-bar-left">
                <button class="sidebar-toggle" id="sidebarToggle" aria-label="Toggle sidebar">☰</button>
                <div>
                    <h1 class="page-title">Manage Departments</h1>
                    <div class="breadcrumb-nav">
                        <span>Add, edit, or delete departments</span>
                    </div>
                </div>
            </div>
            <div class="top-bar-right">
                <a href="dashboard.php" style="color: #cbd5e1; text-decoration: none; padding: 8px 12px; border-radius: 6px; transition: background 0.15s; font-size: 13px; font-weight: 600;" title="Dashboard">← Dashboard</a>
            </div>
        </div>

        <!-- Page Content -->
        <div class="dashboard-container" style="max-width: 1200px;">
<div class="container">
    <div class="header" style="display: none;">
        <div class="brand-title">
            <h1 style="margin:0;">Manage Departments / Process</h1>
            <p class="helper" style="margin:2px 0 0 0;">Add, edit, or delete available departments.</p>
        </div>
        <div class="actions">
            <a class="badge" href="dashboard.php">Back to Dashboard</a>
            <a class="badge" href="designations.php">Designations</a>
            <a class="badge" href="logout.php">Logout</a>
        </div>
    </div>

    <?php if ($flash): ?>
        <div class="alert <?php echo $flash['type'] === 'error' ? 'alert-error' : 'alert-success'; ?>">
            <?php echo htmlspecialchars($flash['message'], ENT_QUOTES, 'UTF-8'); ?>
        </div>
    <?php endif; ?>

        <div class="card">
            <h3 class="section-title">Add Department</h3>
            <form method="post" action="departments.php" class="form-grid" style="grid-template-columns: 2fr 1fr; gap: 12px 16px;">
                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>" />
                <input type="hidden" name="action" value="add" />
                <div>
                    <label for="name">Department Name</label>
                    <input id="name" name="name" type="text" required class="<?php echo ($formContext === 'add' && !empty($errors['name'])) ? 'input-invalid' : ''; ?>" value="<?php echo $formContext === 'add' ? htmlspecialchars($name ?? '', ENT_QUOTES, 'UTF-8') : ''; ?>" />
                    <p class="error"><?php echo $formContext === 'add' ? htmlspecialchars($errors['name'] ?? '', ENT_QUOTES, 'UTF-8') : ''; ?></p>
                </div>
                <div style="align-self:end;">
                    <button type="submit">Add</button>
                </div>
            </form>
        </div>

    <?php if ($editRow): ?>
        <div class="card" style="margin-top:16px;">
            <h3 class="section-title">Edit Department</h3>
            <form method="post" action="departments.php" class="form-grid" style="grid-template-columns: 2fr 1fr; gap: 12px 16px;">
                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>" />
                <input type="hidden" name="action" value="edit" />
                <input type="hidden" name="id" value="<?php echo (int) $editRow['id']; ?>" />
                <div>
                    <label for="edit-name">Department Name</label>
                    <input id="edit-name" name="name" type="text" required class="<?php echo ($formContext === 'edit' && !empty($errors['name'])) ? 'input-invalid' : ''; ?>" value="<?php echo htmlspecialchars($editRow['name'], ENT_QUOTES, 'UTF-8'); ?>" />
                    <p class="error"><?php echo $formContext === 'edit' ? htmlspecialchars($errors['name'] ?? '', ENT_QUOTES, 'UTF-8') : ''; ?></p>
                </div>
                <div style="align-self:end; display:flex; gap:8px;">
                    <a class="button-ghost" href="departments.php">Cancel</a>
                    <button type="submit">Save</button>
                </div>
            </form>
        </div>
    <?php endif; ?>

        <div class="card" style="margin-top:16px;">
            <h3 class="section-title">Existing Departments</h3>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                    <tr>
                        <th>Name</th>
                        <th class="cell-nowrap">In Use</th>
                        <th class="cell-nowrap">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($departments)): ?>
                        <tr><td colspan="3">No departments added yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($departments as $dept): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($dept['name'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td class="cell-nowrap"><?php echo (int) $dept['usage_count']; ?></td>
                                <td class="cell-nowrap" style="display:flex; gap:8px;">
                                    <a class="button-ghost" href="departments.php?edit=<?php echo (int) $dept['id']; ?>">Edit</a>
                                    <form method="post" action="departments.php" onsubmit="return confirm('Delete this department?');" style="margin:0;">
                                        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>" />
                                        <input type="hidden" name="action" value="delete" />
                                        <input type="hidden" name="id" value="<?php echo (int) $dept['id']; ?>" />
                                        <button type="submit" style="background: var(--danger);">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
</div>
        </div>
        </div>
    </div>
</div>

<div class="sidebar-overlay" id="sidebarOverlay"></div>

<script>
    // Sidebar Toggle
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    sidebarToggle?.addEventListener('click', () => {
        sidebar.classList.toggle('open');
        sidebarOverlay.classList.toggle('open');
    });

    sidebarOverlay?.addEventListener('click', () => {
        sidebar.classList.remove('open');
        sidebarOverlay.classList.remove('open');
    });
</script>
</body>
</html>



← Back to Directory Edit File 🔒 Chmod

WP File Manager