<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';

require_role(['super_admin']);

$page_title = 'Manage Schools';
$pdo = Database::getConnection();
$messages = [];
$errors   = [];

/**
 * Utility: generate slug from name
 */
function generate_slug(string $name): string
{
    $slug = strtolower($name);
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');
    return $slug ?: 'school';
}

/**
 * Toggle active status (via GET)
 */
if (isset($_GET['toggle']) && ctype_digit($_GET['toggle'])) {
    $id = (int) $_GET['toggle'];

    $stmt = $pdo->prepare('SELECT id, active FROM schools WHERE id = :id');
    $stmt->execute(['id' => $id]);
    if ($school = $stmt->fetch()) {
        $newActive = $school['active'] ? 0 : 1;
        $upd = $pdo->prepare('UPDATE schools SET active = :active WHERE id = :id');
        $upd->execute(['active' => $newActive, 'id' => $id]);
        $messages[] = 'School status updated.';
    } else {
        $errors[] = 'School not found.';
    }
}

/**
 * Handle create new school (POST)
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $active = isset($_POST['active']) ? 1 : 0;

    if ($name === '') {
        $errors[] = 'School name is required.';
    }

    if ($slug === '' && $name !== '') {
        $slug = generate_slug($name);
    } elseif ($slug !== '') {
        $slug = generate_slug($slug); // normalise whatever they typed
    }

    if ($slug === '') {
        $errors[] = 'Unable to generate a valid slug.';
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare('
                INSERT INTO schools (name, slug, active)
                VALUES (:name, :slug, :active)
            ');
            $stmt->execute([
                'name'   => $name,
                'slug'   => $slug,
                'active' => $active,
            ]);

            $schoolId = (int) $pdo->lastInsertId();

            // Create default school_settings row
            $stmtSettings = $pdo->prepare('
                INSERT INTO school_settings (school_id)
                VALUES (:school_id)
            ');
            $stmtSettings->execute(['school_id' => $schoolId]);

            $pdo->commit();
            $messages[] = 'School created successfully.';
        } catch (PDOException $e) {
            $pdo->rollBack();

            if ((int)$e->getCode() === 23000) { // unique constraint
                $errors[] = 'A school with this slug already exists. Please choose another name/slug.';
            } else {
                $errors[] = 'Database error: ' . $e->getMessage();
            }
        }
    }
}

// Fetch list of schools
$stmt = $pdo->query('SELECT * FROM schools ORDER BY created_at DESC');
$schools = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<section class="content">
    <div class="container-fluid">
        <h1 class="mb-4">Manage Schools</h1>

        <?php if ($messages): ?>
            <div class="alert alert-success">
                <?php foreach ($messages as $msg): ?>
                    <div><?= e($msg) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <?php foreach ($errors as $err): ?>
                    <div><?= e($err) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-4">
                <!-- Add School Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Add New School</h3>
                    </div>
                    <form method="post">
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name">School Name</label>
                                <input type="text" name="name" id="name" class="form-control" required>
                            </div>

                            <div class="form-group">
                                <label for="slug">Slug (optional)</label>
                                <input type="text" name="slug" id="slug" class="form-control"
                                       placeholder="e.g. my-school">
                                <small class="form-text text-muted">
                                    If left blank, a slug will be generated from the name.
                                </small>
                            </div>

                            <div class="form-check">
                                <input type="checkbox" name="active" id="active" class="form-check-input" checked>
                                <label for="active" class="form-check-label">Active</label>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Create School
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-md-8">
                <!-- Schools List -->
                <div class="card card-outline card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">Existing Schools</h3>
                    </div>
                    <div class="card-body table-responsive p-0">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Slug</th>
                                <th>Active</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($schools)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted">No schools found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($schools as $school): ?>
                                    <tr>
                                        <td><?= (int)$school['id'] ?></td>
                                        <td><?= e($school['name']) ?></td>
                                        <td><?= e($school['slug']) ?></td>
                                        <td>
                                            <?php if ($school['active']): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= e($school['created_at']) ?></td>
                                        <td>
                                            <a href="?toggle=<?= (int)$school['id'] ?>"
                                               class="btn btn-sm btn-outline-secondary"
                                               onclick="return confirm('Toggle active status for this school?');">
                                                <?= $school['active'] ? 'Deactivate' : 'Activate' ?>
                                            </a>
                                            <!-- Later: edit link for name/slug/branding -->
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div>
</section>

<?php include __DIR__ . '/../includes/footer.php'; ?>
