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

$pdo = db();
$errors = [];
$departments = $pdo->query('SELECT id, name FROM departments 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 courses WHERE id = :id')->execute(['id' => $id]);
            add_flash('success', 'Course removed.');
            redirect('admin/courses.php');
        }

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

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

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

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

$courses = $pdo->query(
    'SELECT c.*, d.name AS department_name
     FROM courses c
     LEFT JOIN departments d ON c.department_id = d.id
     ORDER BY c.name ASC'
)->fetchAll();

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

<!-- Course modal -->
<div class="modal fade" id="courseModal" tabindex="-1" aria-hidden="true"
     data-create-title="Add Course" data-edit-title="Edit Course"
     data-create-submit="Add Course" 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 Course</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">Department</label>
                            <select name="department_id" class="form-select">
                                <?php foreach ($departments as $department): ?>
                                    <option value="<?= $department['id'] ?>"><?= sanitize($department['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 Course</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete modal -->
<div class="modal fade" id="deleteCourseModal" 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 Course</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 course?</p>
                    <p class="fw-semibold mb-0" data-delete-name>Course 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();
