<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Lessons
 * File: teacher/lessons/index.php
 *
 * Architecture:
 * Books -> Units -> Lessons -> Practices
 */

require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$pdo = getDbConnection();

// Limit teachers to books assigned by Admin. Admin can see all books.
$teacherId = (int)($_SESSION['teacher_id'] ?? $_SESSION['user_id'] ?? 0);
$role = strtolower((string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? 'teacher'));
$isAdmin = ($role === 'admin');

$pageTitle = 'Lessons';
$pageSubtitle = 'Manage lessons inside each Unit';
$activeTeacherNav = 'content';

$keyword = trim((string)($_GET['keyword'] ?? ''));
$bookId = max(0, (int)($_GET['book_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? 0));
$status = (string)($_GET['status'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 12;

if (!in_array($status, ['', 'active', 'inactive'], true)) {
    $status = '';
}

/**
 * Build a URL while keeping current filters.
 *
 * @param array<string, int|string|null> $changes
 */
function lessonsUrl(array $changes = []): string
{
    $query = [
        'keyword' => trim((string)($_GET['keyword'] ?? '')),
        'book_id' => max(0, (int)($_GET['book_id'] ?? 0)),
        'unit_id' => max(0, (int)($_GET['unit_id'] ?? 0)),
        'status' => (string)($_GET['status'] ?? ''),
        'page' => max(1, (int)($_GET['page'] ?? 1)),
    ];

    foreach ($changes as $key => $value) {
        if ($value === null || $value === '' || $value === 0) {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return 'index.php' . ($query !== [] ? '?' . http_build_query($query) : '');
}

// Books for filter: teachers only see books assigned by Admin.
if ($isAdmin) {
    $booksStmt = $pdo->query(
        "SELECT id, name
         FROM books
         WHERE status = 'active'
         ORDER BY sort_order ASC, name ASC"
    );
} else {
    $booksStmt = $pdo->prepare(
        "SELECT DISTINCT b.id, b.name, b.sort_order
         FROM books b
         INNER JOIN teacher_books tb ON tb.book_id = b.id
         WHERE b.status = 'active'
           AND tb.teacher_id = :teacher_id
         ORDER BY b.sort_order ASC, b.name ASC"
    );
    $booksStmt->execute([':teacher_id' => $teacherId]);
}
$books = $booksStmt->fetchAll(PDO::FETCH_ASSOC);

$allowedBookIds = array_map(static fn(array $book): int => (int)$book['id'], $books);
if (!$isAdmin && $bookId > 0 && !in_array($bookId, $allowedBookIds, true)) {
    $bookId = 0;
}

// Units for filter.
$unitsSql = "
    SELECT
        u.id,
        u.book_id,
        u.unit_number,
        u.title,
        b.name AS book_name
    FROM units u
    INNER JOIN books b ON b.id = u.book_id
    WHERE u.status = 'active'
";
$unitsParams = [];

if (!$isAdmin) {
    $unitsSql .= " AND EXISTS (SELECT 1 FROM teacher_books tb WHERE tb.teacher_id = :teacher_units_id AND tb.book_id = u.book_id)";
    $unitsParams[':teacher_units_id'] = $teacherId;
}

if ($bookId > 0) {
    $unitsSql .= " AND u.book_id = :book_id";
    $unitsParams[':book_id'] = $bookId;
}

$unitsSql .= " ORDER BY b.sort_order ASC, u.sort_order ASC, u.id ASC";

$unitsStmt = $pdo->prepare($unitsSql);
$unitsStmt->execute($unitsParams);
$units = $unitsStmt->fetchAll(PDO::FETCH_ASSOC);

// If selected Unit belongs to another Book, clear it.
if ($unitId > 0) {
    $validUnit = false;

    foreach ($units as $unit) {
        if ((int)$unit['id'] === $unitId) {
            $validUnit = true;
            break;
        }
    }

    if (!$validUnit) {
        $unitId = 0;
    }
}

// Dynamic WHERE.
$where = [];
$params = [];

if (!$isAdmin) {
    $where[] = 'EXISTS (SELECT 1 FROM teacher_books tb WHERE tb.teacher_id = :teacher_lessons_id AND tb.book_id = u.book_id)';
    $params[':teacher_lessons_id'] = $teacherId;
}

if ($keyword !== '') {
    $where[] = '(
        l.lesson_number LIKE :keyword
        OR l.title LIKE :keyword
        OR l.lesson_type LIKE :keyword
        OR l.description LIKE :keyword
    )';
    $params[':keyword'] = '%' . $keyword . '%';
}

if ($bookId > 0) {
    $where[] = 'u.book_id = :filter_book_id';
    $params[':filter_book_id'] = $bookId;
}

if ($unitId > 0) {
    $where[] = 'l.unit_id = :unit_id';
    $params[':unit_id'] = $unitId;
}

if ($status !== '') {
    $where[] = 'l.status = :status';
    $params[':status'] = $status;
}

$whereSql = $where !== [] ? 'WHERE ' . implode(' AND ', $where) : '';

// Count.
$countStmt = $pdo->prepare(
    "SELECT COUNT(*)
     FROM lessons l
     INNER JOIN units u ON u.id = l.unit_id
     {$whereSql}"
);
$countStmt->execute($params);
$totalLessons = (int)$countStmt->fetchColumn();

$totalPages = max(1, (int)ceil($totalLessons / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}
$offset = ($page - 1) * $perPage;

// Lesson list.
$listSql = "
    SELECT
        l.id,
        l.unit_id,
        l.created_by_teacher_id,
        l.lesson_number,
        l.title,
        l.lesson_type,
        l.thumbnail,
        l.description,
        l.access_type,
        l.required_xp,
        l.sort_order,
        l.status,
        l.created_at,
        l.updated_at,
        u.unit_number,
        u.title AS unit_title,
        u.book_id,
        b.name AS book_name,
        (
            SELECT COUNT(*)
            FROM activities a
            WHERE a.lesson_id = l.id
              AND a.status = 'active'
        ) AS practice_count
    FROM lessons l
    INNER JOIN units u ON u.id = l.unit_id
    INNER JOIN books b ON b.id = u.book_id
    {$whereSql}
    ORDER BY
        b.sort_order ASC,
        u.sort_order ASC,
        l.sort_order ASC,
        l.id ASC
    LIMIT :limit OFFSET :offset
";

$listStmt = $pdo->prepare($listSql);

foreach ($params as $name => $value) {
    $listStmt->bindValue(
        $name,
        $value,
        is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
    );
}

$listStmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$listStmt->execute();
$lessons = $listStmt->fetchAll(PDO::FETCH_ASSOC);

// Summary: use the same current filters as the lesson list so the cards
// always match "Showing ... of ..." below.
$summaryStmt = $pdo->prepare(
    "SELECT
        COUNT(*) AS total_count,
        COALESCE(SUM(l.status = 'active'), 0) AS active_count,
        COALESCE(SUM(l.status = 'inactive'), 0) AS inactive_count
     FROM lessons l
     INNER JOIN units u ON u.id = l.unit_id
     {$whereSql}"
);
$summaryStmt->execute($params);
$summary = $summaryStmt->fetch(PDO::FETCH_ASSOC) ?: [];

$totalAll = (int)($summary['total_count'] ?? 0);
$activeAll = (int)($summary['active_count'] ?? 0);
$inactiveAll = (int)($summary['inactive_count'] ?? 0);

$message = (string)($_SESSION['lessons_message'] ?? '');
$messageType = (string)($_SESSION['lessons_message_type'] ?? 'success');
unset($_SESSION['lessons_message'], $_SESSION['lessons_message_type']);

ob_start();
?>

<style>
.lessons-page{display:grid;gap:18px}
.lessons-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}
.lessons-header h2{margin:4px 0 0;font-size:28px;line-height:1.2}
.lessons-kicker{display:block;color:#7c3aed;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.lessons-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
.lessons-stat{padding:16px 18px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.lessons-stat span{display:block;color:#64748b;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.04em}
.lessons-stat strong{display:block;margin-top:6px;font-size:25px;color:#0f172a}
.lessons-toolbar{display:grid;grid-template-columns:minmax(220px,1fr) minmax(170px,230px) minmax(190px,290px) minmax(140px,180px) auto;gap:10px;padding:14px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.lessons-input,.lessons-select{width:100%;min-height:42px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.lessons-input:focus,.lessons-select:focus{outline:3px solid rgba(124,58,237,.12);border-color:#7c3aed}
.lessons-card{overflow:hidden;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.lessons-table{width:100%;border-collapse:collapse}
.lessons-table th{padding:12px 14px;background:#f8fafc;color:#64748b;font-size:11px;text-align:left;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #e5e7eb}
.lessons-table td{padding:14px;border-bottom:1px solid #eef2f7;vertical-align:middle}
.lessons-table tr:last-child td{border-bottom:0}
.lessons-table tbody tr:hover{background:#fcfbff}
.lesson-cell{display:flex;align-items:center;gap:12px;min-width:260px}
.lesson-badge{display:grid;place-items:center;flex:0 0 46px;height:46px;border-radius:13px;background:#f1eaff;color:#7c3aed;font-weight:800}
.lesson-info strong{display:block;color:#0f172a}
.lesson-info small{display:block;margin-top:4px;max-width:420px;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lesson-path{font-weight:650;color:#334155;line-height:1.45}
.lesson-path small{display:block;color:#64748b;font-weight:500}
.lessons-number{font-weight:750;color:#0f172a}
.access-pill,.status-pill{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:750}
.access-free{background:#ecfdf3;color:#15803d}
.access-premium{background:#fff7ed;color:#c2410c}
.status-pill:before{content:"";width:7px;height:7px;border-radius:50%}
.status-active{background:#ecfdf3;color:#15803d}.status-active:before{background:#22c55e}
.status-inactive{background:#f1f5f9;color:#64748b}.status-inactive:before{background:#94a3b8}
.lessons-actions{display:flex;align-items:center;gap:7px;white-space:nowrap}
.lessons-action{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 11px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:12px;font-weight:700}
.lessons-action:hover{border-color:#7c3aed;color:#7c3aed}
.lessons-action-danger:hover{border-color:#ef4444;color:#dc2626}
.lessons-empty{padding:58px 20px;text-align:center}
.lessons-empty-icon{font-size:42px}
.lessons-empty h3{margin:12px 0 6px}
.lessons-empty p{margin:0 0 18px;color:#64748b}
.lessons-footer{display:flex;align-items:center;justify-content:space-between;gap:16px}
.lessons-pagination{display:flex;align-items:center;gap:6px}
.lessons-pagination a,.lessons-pagination span{display:grid;place-items:center;min-width:36px;height:36px;padding:0 9px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:13px;font-weight:700}
.lessons-pagination .current{border-color:#7c3aed;background:#7c3aed;color:#fff}
.lessons-pagination .disabled{opacity:.45}
.lessons-flash{padding:12px 15px;border-radius:12px;font-weight:650}
.lessons-flash-success{background:#ecfdf3;color:#166534;border:1px solid #bbf7d0}
.lessons-flash-error{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
@media(max-width:1180px){
 .lessons-toolbar{grid-template-columns:1fr 1fr}
 .lessons-card{overflow-x:auto}
}
@media(max-width:680px){
 .lessons-header,.lessons-footer{align-items:stretch;flex-direction:column}
 .lessons-stats{grid-template-columns:1fr}
 .lessons-toolbar{grid-template-columns:1fr}
}
</style>

<div class="lessons-page">
    <div class="lessons-header">
        <div>
            <span class="lessons-kicker">Content Library</span>
            <h2>Lessons</h2>
            <p style="margin:7px 0 0;color:#64748b">
                Books → Units → Lessons → Practices
            </p>
        </div>

        <a
            href="create.php<?= $unitId > 0 ? '?unit_id=' . $unitId : '' ?>"
            class="button button-primary"
        >
            + New Lesson
        </a>
    </div>

    <?php if ($message !== ''): ?>
        <div class="lessons-flash lessons-flash-<?= $messageType === 'error' ? 'error' : 'success' ?>">
            <?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <div class="lessons-stats">
        <div class="lessons-stat">
            <span>Total Lessons</span>
            <strong><?= $totalAll ?></strong>
        </div>
        <div class="lessons-stat">
            <span>Active</span>
            <strong><?= $activeAll ?></strong>
        </div>
        <div class="lessons-stat">
            <span>Hidden</span>
            <strong><?= $inactiveAll ?></strong>
        </div>
    </div>

    <form class="lessons-toolbar" method="get" action="index.php">
        <input
            class="lessons-input"
            type="search"
            name="keyword"
            value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>"
            placeholder="Search Lesson number, title..."
        >

        <select
            class="lessons-select"
            name="book_id"
            onchange="this.form.unit_id.value=''; this.form.submit();"
        >
            <option value="">All Books</option>
            <?php foreach ($books as $book): ?>
                <option value="<?= (int)$book['id'] ?>" <?= (int)$book['id'] === $bookId ? 'selected' : '' ?>>
                    <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select class="lessons-select" name="unit_id" onchange="this.form.submit()">
            <option value="">All Units</option>
            <?php foreach ($units as $unit): ?>
                <option value="<?= (int)$unit['id'] ?>" <?= (int)$unit['id'] === $unitId ? 'selected' : '' ?>>
                    <?= htmlspecialchars(
                        (string)$unit['book_name'] . ' • ' .
                        (string)$unit['unit_number'] . ' • ' .
                        (string)$unit['title'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select class="lessons-select" name="status" onchange="this.form.submit()">
            <option value="">All Status</option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Hidden</option>
        </select>

        <div style="display:flex;gap:8px">
            <button type="submit" class="button button-primary">Search</button>

            <?php if ($keyword !== '' || $bookId > 0 || $unitId > 0 || $status !== ''): ?>
                <a href="index.php" class="button button-secondary">Reset</a>
            <?php endif; ?>
        </div>
    </form>

    <div class="lessons-card">
        <?php if ($lessons === []): ?>
            <div class="lessons-empty">
                <div class="lessons-empty-icon">📖</div>
                <h3>No Lessons found</h3>
                <p>Create a Lesson or adjust the current filters.</p>

                <a
                    href="create.php<?= $unitId > 0 ? '?unit_id=' . $unitId : '' ?>"
                    class="button button-primary"
                >
                    + Create Lesson
                </a>
            </div>
        <?php else: ?>
            <table class="lessons-table">
                <thead>
                    <tr>
                        <th>Lesson</th>
                        <th>Book / Unit</th>
                        <th>Type</th>
                        <th>Practices</th>
                        <th>Access</th>
                        <th>Status</th>
                        <th style="width:210px">Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($lessons as $lesson): ?>
                        <?php
                        $lessonOwnerId = isset($lesson['created_by_teacher_id'])
                            ? (int)$lesson['created_by_teacher_id']
                            : 0;
                        $canManageLesson = $isAdmin
                            || ($lessonOwnerId > 0 && $lessonOwnerId === $teacherId);
                        ?>
                        <tr>
                            <td>
                                <div class="lesson-cell">
                                    <div class="lesson-badge">
                                        <?php
                                        $lessonNumber = (string)$lesson['lesson_number'];
                                        preg_match('/\d+/', $lessonNumber, $match);
                                        echo htmlspecialchars(
                                            isset($match[0]) ? 'L' . $match[0] : 'L',
                                            ENT_QUOTES,
                                            'UTF-8'
                                        );
                                        ?>
                                    </div>

                                    <div class="lesson-info">
                                        <strong>
                                            <?= htmlspecialchars(
                                                trim(
                                                    (string)$lesson['lesson_number']
                                                    . ' • '
                                                    . (string)$lesson['title']
                                                ),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </strong>

                                        <small>
                                            <?= htmlspecialchars(
                                                (string)($lesson['description'] ?: 'No description'),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </small>
                                    </div>
                                </div>
                            </td>

                            <td class="lesson-path">
                                <?= htmlspecialchars((string)$lesson['book_name'], ENT_QUOTES, 'UTF-8') ?>
                                <small>
                                    <?= htmlspecialchars(
                                        (string)$lesson['unit_number']
                                        . ' • '
                                        . (string)$lesson['unit_title'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </small>
                            </td>

                            <td>
                                <?= htmlspecialchars(
                                    (string)($lesson['lesson_type'] ?: 'Standard'),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </td>

                            <td class="lessons-number">
                                <?= (int)$lesson['practice_count'] ?>
                            </td>

                            <td>
                                <?php $isPremium = (string)$lesson['access_type'] === 'premium'; ?>
                                <span class="access-pill <?= $isPremium ? 'access-premium' : 'access-free' ?>">
                                    <?= $isPremium ? 'Premium' : 'Free' ?>
                                </span>
                            </td>

                            <td>
                                <?php $isActive = (string)$lesson['status'] === 'active'; ?>
                                <span class="status-pill <?= $isActive ? 'status-active' : 'status-inactive' ?>">
                                    <?= $isActive ? 'Active' : 'Hidden' ?>
                                </span>
                            </td>

                            <td>
                                <div class="lessons-actions">
                                    <a
                                        class="lessons-action"
                                        href="detail.php?id=<?= (int)$lesson['id'] ?>"
                                    >
                                        Practices
                                    </a>

                                    <?php if ($canManageLesson): ?>
                                        <a
                                            class="lessons-action"
                                            href="edit.php?id=<?= (int)$lesson['id'] ?>"
                                        >
                                            Edit
                                        </a>

                                        <a
                                            class="lessons-action lessons-action-danger"
                                            href="delete.php?id=<?= (int)$lesson['id'] ?>"
                                        >
                                            Delete
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="lessons-footer">
        <div style="color:#64748b">
            Showing
            <strong><?= $totalLessons === 0 ? 0 : $offset + 1 ?></strong>
            –
            <strong><?= min($offset + $perPage, $totalLessons) ?></strong>
            of <strong><?= $totalLessons ?></strong> Lesson(s)
        </div>

        <?php if ($totalPages > 1): ?>
            <nav class="lessons-pagination" aria-label="Lessons pagination">
                <?php if ($page > 1): ?>
                    <a href="<?= htmlspecialchars(lessonsUrl(['page' => $page - 1]), ENT_QUOTES, 'UTF-8') ?>">‹</a>
                <?php else: ?>
                    <span class="disabled">‹</span>
                <?php endif; ?>

                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);

                for ($i = $startPage; $i <= $endPage; $i++):
                ?>
                    <?php if ($i === $page): ?>
                        <span class="current"><?= $i ?></span>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(lessonsUrl(['page' => $i]), ENT_QUOTES, 'UTF-8') ?>">
                            <?= $i ?>
                        </a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <a href="<?= htmlspecialchars(lessonsUrl(['page' => $page + 1]), ENT_QUOTES, 'UTF-8') ?>">›</a>
                <?php else: ?>
                    <span class="disabled">›</span>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    </div>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
