<?php
$db = getDB();

// ---------- Determine action ----------
$action = $_GET['action'] ?? 'list';
if (!in_array($action, ['list', 'create', 'update', 'delete'])) {
    $action = 'list';
}

// ---------- Course filter (from query string) ----------
$course_id = $_GET['course_id'] ?? null;
if ($course_id !== null) $course_id = intval($course_id);

// ---------- Messages ----------
$errors = [];
$success = $_GET['success'] ?? '';

// ---------- Helper: fetch a single lesson ----------
function getLessonById($db, $id): ?array {
    $stmt = $db->prepare("SELECT * FROM lessons WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// ---------- Handle DELETE ----------
if ($action === 'delete' && isset($_GET['id'])) {
    $stmt = $db->prepare("DELETE FROM lessons WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $redirect = 'index.php?page=lessons&success=deleted';
    if ($course_id) $redirect .= "&course_id=$course_id";
    header('Location: ' . $redirect);
    exit;
}

// ---------- Handle CREATE / UPDATE form submission ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['create', 'update'])) {
    $title          = trim($_POST['title'] ?? '');
    $description    = $_POST['description'] ?? null;
    $order          = intval($_POST['order'] ?? 0);
    $is_locked      = isset($_POST['is_locked']) ? 1 : 0;
    $is_premium     = isset($_POST['is_premium']) ? 1 : 0;
    $form_course_id = intval($_POST['course_id'] ?? 0);

    // Validation
    if ($title === '') {
        $errors[] = 'Title is required.';
    }
    if ($form_course_id <= 0) {
        $errors[] = 'A course must be selected.';
    } else {
        // Check the course exists
        $check = $db->prepare("SELECT id FROM courses WHERE id = ?");
        $check->bind_param("i", $form_course_id);
        $check->execute();
        if ($check->get_result()->num_rows === 0) {
            $errors[] = 'The selected course does not exist.';
        }
    }

    if (empty($errors)) {
        $stmt = null;
        if ($action === 'create') {
            $stmt = $db->prepare("INSERT INTO lessons (course_id, title, description, `order`, is_locked, is_premium) 
                                  VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("issiii", $form_course_id, $title, $description, $order, $is_locked, $is_premium);
        } elseif ($action === 'update' && isset($_GET['id'])) {
            $stmt = $db->prepare("UPDATE lessons SET course_id=?, title=?, description=?, `order`=?, is_locked=?, is_premium=? WHERE id=?");
            $stmt->bind_param("issiiii", $form_course_id, $title, $description, $order, $is_locked, $is_premium, $_GET['id']);
        }
        if ($stmt) $stmt->execute();
        $msg = ($action === 'create') ? 'created' : 'updated';
        $redirect = 'index.php?page=lessons&success=' . $msg;
        if ($course_id) $redirect .= "&course_id=$course_id";
        header('Location: ' . $redirect);
        exit;
    }
}

// ---------- Load existing lesson for edit ----------
$lesson = null;
if ($action === 'update' && isset($_GET['id'])) {
    $lesson = getLessonById($db, $_GET['id']);
    if (!$lesson) {
        echo '<div class="alert alert-danger">Lesson not found.</div>';
        $action = 'list';
    }
}

// ---------- Success banners ----------
if ($success === 'created') {
    echo '<div class="alert alert-success">Lesson created successfully.</div>';
} elseif ($success === 'updated') {
    echo '<div class="alert alert-success">Lesson updated successfully.</div>';
} elseif ($success === 'deleted') {
    echo '<div class="alert alert-success">Lesson deleted.</div>';
}

// ---------- LIST view ----------
if ($action === 'list'):
    // Fetch course name if filtered
    $courseName = '';
    if ($course_id) {
        $cstmt = $db->prepare("SELECT title FROM courses WHERE id = ?");
        $cstmt->bind_param("i", $course_id);
        $cstmt->execute();
        $cres = $cstmt->get_result()->fetch_assoc();
        $courseName = $cres['title'] ?? '';
    }
?>
    <h3>Lessons <?= $course_id ? 'for course: ' . htmlspecialchars($courseName) . " (ID $course_id)" : '' ?></h3>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <form class="d-flex" method="get">
            <input type="hidden" name="page" value="lessons">
            <?php if ($course_id): ?>
                <input type="hidden" name="course_id" value="<?= $course_id ?>">
            <?php endif; ?>
            <input type="text" name="search" class="form-control me-2" placeholder="Search title..."
                   value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            <button type="submit" class="btn btn-outline-secondary"><i class="fa fa-search"></i></button>
        </form>
        <a href="?page=lessons&action=create<?= $course_id ? "&course_id=$course_id" : '' ?>" class="btn btn-primary">
            <i class="fa fa-plus me-1"></i> New Lesson
        </a>
    </div>

    <?php
    // ---------- Pagination & search ----------
    $pageNum = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
    $limit = 50;
    $offset = ($pageNum - 1) * $limit;

    $where = [];
    $params = [];
    $types = '';

    if ($course_id) {
        $where[] = "l.course_id = ?";
        $params[] = $course_id;
        $types .= 'i';
    }
    if (!empty($_GET['search'])) {
        $where[] = "l.title LIKE ?";
        $params[] = "%" . $_GET['search'] . "%";
        $types .= 's';
    }

    $whereSQL = '';
    if (!empty($where)) {
        $whereSQL = 'WHERE ' . implode(' AND ', $where);
    }

    // Count
    $countSQL = "SELECT COUNT(*) FROM lessons l $whereSQL";
    $stmt = $db->prepare($countSQL);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total = $stmt->get_result()->fetch_row()[0];
    $totalPages = ceil($total / $limit);

    // Fetch lessons with course title
    $sql = "SELECT l.*, c.title AS course_title 
            FROM lessons l 
            JOIN courses c ON l.course_id = c.id 
            $whereSQL 
            ORDER BY l.course_id, l.order 
            LIMIT ? OFFSET ?";
    $types .= 'ii';
    $params[] = $limit;
    $params[] = $offset;
    $stmt = $db->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $lessons = $stmt->get_result();
    ?>

    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Course</th>
                    <th>Title</th>
                    <th>Order</th>
                    <th>Words</th>
                    <th>Premium</th>
                    <th>Locked</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($lessons->num_rows > 0): ?>
                <?php while($row = $lessons->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['course_title']) ?> (<?= $row['course_id'] ?>)</td>
                    <td><?= htmlspecialchars($row['title']) ?></td>
                    <td><?= $row['order'] ?></td>
                    <td><?= $row['total_words'] ?></td>
                    <td><?= $row['is_premium'] ? '<span class="badge bg-warning text-dark">Yes</span>' : 'No' ?></td>
                    <td><?= $row['is_locked'] ? '<span class="badge bg-secondary">Yes</span>' : 'No' ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="?page=flashcards&lesson_id=<?= $row['id'] ?>" class="btn btn-outline-info" title="Flashcards">
                                <i class="fa fa-clone"></i>
                            </a>
                            <a href="?page=exam_questions&lesson_id=<?= $row['id'] ?>" class="btn btn-outline-primary" title="Exam Questions">
                                <i class="fa fa-question-circle"></i>
                            </a>
                            <a href="?page=lessons&action=update&id=<?= $row['id'] ?><?= $course_id ? "&course_id=$course_id" : '' ?>" class="btn btn-outline-warning" title="Edit">
                                <i class="fa fa-edit"></i>
                            </a>
                            <a href="?page=lessons&action=delete&id=<?= $row['id'] ?><?= $course_id ? "&course_id=$course_id" : '' ?>"
                               class="btn btn-outline-danger" title="Delete"
                               onclick="return confirm('Delete this lesson and all its flashcards & exam questions?')">
                                <i class="fa fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="8" class="text-center">No lessons found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav>
        <ul class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $pageNum ? 'active' : '' ?>">
                    <a class="page-link" href="?page=lessons&p=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?><?= $course_id ? "&course_id=$course_id" : '' ?>">
                        <?= $i ?>
                    </a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>

<?php
// ---------- CREATE / UPDATE form ----------
else:
    // Build list of courses for the dropdown
    $courseList = $db->query("SELECT id, title FROM courses ORDER BY sort_order, title");
?>
    <h3><?= $action === 'create' ? 'Create New Lesson' : 'Edit Lesson' ?></h3>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $err): ?>
                    <li><?= htmlspecialchars($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form method="post" class="card p-4" style="max-width: 600px;">
        <div class="mb-3">
            <label for="course_id" class="form-label">Course *</label>
            <select name="course_id" id="course_id" class="form-select" required>
                <option value="">-- Select a course --</option>
                <?php while($c = $courseList->fetch_assoc()): 
                    $selected = ($lesson['course_id'] ?? $_POST['course_id'] ?? $course_id ?? '') == $c['id'];
                ?>
                    <option value="<?= $c['id'] ?>" <?= $selected ? 'selected' : '' ?>>
                        <?= htmlspecialchars($c['title']) ?> (ID: <?= $c['id'] ?>)
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="mb-3">
            <label for="title" class="form-label">Title *</label>
            <input type="text" name="title" id="title" class="form-control"
                   value="<?= htmlspecialchars($lesson['title'] ?? $_POST['title'] ?? '') ?>" required>
        </div>

        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea name="description" id="description" class="form-control" rows="3"><?= htmlspecialchars($lesson['description'] ?? $_POST['description'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label for="order" class="form-label">Order</label>
            <input type="number" name="order" id="order" class="form-control" min="0"
                   value="<?= htmlspecialchars($lesson['order'] ?? $_POST['order'] ?? '0') ?>">
            <small class="text-muted">Lower numbers appear first within a course.</small>
        </div>

        <div class="mb-3 form-check">
            <input type="checkbox" name="is_premium" id="is_premium" class="form-check-input"
                   <?= ($lesson['is_premium'] ?? $_POST['is_premium'] ?? 0) ? 'checked' : '' ?>>
            <label for="is_premium" class="form-check-label">Premium lesson</label>
        </div>

        <div class="mb-3 form-check">
            <input type="checkbox" name="is_locked" id="is_locked" class="form-check-input"
                   <?= ($lesson['is_locked'] ?? $_POST['is_locked'] ?? 1) ? 'checked' : '' ?>>
            <label for="is_locked" class="form-check-label">Locked (requires previous lesson completion)</label>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-success">
                <i class="fa fa-save me-1"></i> Save
            </button>
            <a href="?page=lessons<?= $course_id ? "&course_id=$course_id" : '' ?>" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
<?php endif; ?>