<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();

$pdo = db();
$errors = [];
$schools = $pdo->query('SELECT id, name FROM schools WHERE status = 1 ORDER BY name')->fetchAll();

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token.';
    } else {
        $action = $_POST['action'] ?? 'create';

        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            $pdo->prepare('DELETE FROM departments WHERE id = :id')->execute(['id' => $id]);
            add_flash('success', 'Department removed.');
            redirect('admin/departments.php');
        }

        $payload = [
            'code' => strtoupper(trim($_POST['code'] ?? '')),
            'name' => trim($_POST['name'] ?? ''),
            'school_id' => (int) ($_POST['school_id'] ?? 0),
            'description' => trim($_POST['description'] ?? ''),
            'status' => (int) ($_POST['status'] ?? 1),
        ];

        if ($payload['code'] === '' || $payload['name'] === '') {
            $errors[] = 'Department code and name are required.';
        }

        if (!$errors) {
            if ($action === 'update') {
                $payload['id'] = (int) ($_POST['id'] ?? 0);
                $stmt = $pdo->prepare(
                    'UPDATE departments SET code = :code, name = :name, school_id = :school_id,
                        description = :description, status = :status WHERE id = :id'
                );
                $stmt->execute($payload);
                add_flash('success', 'Department updated.');
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO departments (code, name, school_id, description, status)
                     VALUES (:code, :name, :school_id, :description, :status)'
                );
                $stmt->execute($payload);
                add_flash('success', 'Department added.');
            }

            redirect('admin/departments.php');
        }
    }
}

$departments = $pdo->query(
    'SELECT d.*, s.name AS school_name
     FROM departments d
     LEFT JOIN schools s ON d.school_id = s.id
     ORDER BY d.name ASC'
)->fetchAll();

render_header('Departments', ['active' => 'departments']);
?>
<div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Departments</h5>
            <small class="text-muted"><?= count($departments) ?> total</small>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <?php if ($errors): ?>
                <span class="text-danger small"><?= sanitize(implode(' ', $errors)) ?></span>
            <?php endif; ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#departmentModal" data-mode="create">
                Add Department
            </button>
        </div>
    </div>
    <div class="card-body">
        <?php if (!$departments): ?>
            <p class="text-muted mb-0 text-center">No departments yet.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>School</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($departments as $department): ?>
                        <?php
                        $recordPayload = encode_record([
                            'id' => (int) $department['id'],
                            'code' => $department['code'],
                            'name' => $department['name'],
                            'school_id' => (int) ($department['school_id'] ?? 0),
                            'description' => $department['description'],
                            'status' => (int) $department['status'],
                        ]);
                        ?>
                        <tr>
                            <td><code><?= sanitize($department['code']) ?></code></td>
                            <td><?= sanitize($department['name']) ?></td>
                            <td><?= sanitize($department['school_name'] ?? '—') ?></td>
                            <td>
                                <span class="badge <?= $department['status'] ? 'bg-success-subtle text-success' : 'bg-secondary' ?>">
                                    <?= $department['status'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary"
                                        data-bs-toggle="modal"
                                        data-bs-target="#departmentModal"
                                        data-mode="edit"
                                        data-record="<?= sanitize($recordPayload) ?>">
                                    Edit
                                </button>
                                <button class="btn btn-sm btn-outline-danger"
                                        data-bs-toggle="modal"
                                        data-bs-target="#deleteDepartmentModal"
                                        data-record-name="<?= sanitize($department['name']) ?>"
                                        data-record-ref="<?= sanitize($department['code']) ?>"
                                        data-id="<?= (int) $department['id'] ?>">
                                    Delete
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Department modal -->
<div class="modal fade" id="departmentModal" tabindex="-1" aria-hidden="true"
     data-create-title="Add Department" data-edit-title="Edit Department"
     data-create-submit="Add Department" data-edit-submit="Save Changes">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <form method="post" class="needs-validation" novalidate>
                <div class="modal-header">
                    <h5 class="modal-title" data-modal-title>Add Department</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="create">
                    <input type="hidden" name="id" value="">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Code</label>
                            <input type="text" name="code" class="form-control text-uppercase" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label">School</label>
                            <select name="school_id" class="form-select">
                                <?php foreach ($schools as $school): ?>
                                    <option value="<?= $school['id'] ?>"><?= sanitize($school['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="1" selected>Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Department</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete modal -->
<div class="modal fade" id="deleteDepartmentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Department</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="">
                    <p class="mb-1" data-delete-message>Delete this department?</p>
                    <p class="fw-semibold mb-0" data-delete-name>Department Name</p>
                    <small class="text-muted" data-delete-id data-label="Code">Code: —</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php
render_footer();
