<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace local_coursegen\mod_settings;

use context_module;
use lesson;
use lesson_page;
use stdClass;

/**
 * Class lesson_settings
 *
 * Creates the lesson pages (content and question pages) generated by the AI
 * service after the lesson instance exists. Pages are linked linearly:
 * content pages continue to the next page; question pages jump to the next
 * page on a correct answer and stay on the page otherwise.
 *
 * @package    local_coursegen
 * @copyright  2026 Wilber Narvaez <https://datacurso.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class lesson_settings extends base_settings {
    /**
     * Add the AI-generated pages to the lesson.
     */
    public function add_settings() {
        global $CFG;

        require_once($CFG->dirroot . '/mod/lesson/locallib.php');
        // The LESSON_PAGE_* constants live in each page type file and are not
        // loaded by locallib until the page type manager runs.
        require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
        require_once($CFG->dirroot . '/mod/lesson/pagetypes/multichoice.php');
        require_once($CFG->dirroot . '/mod/lesson/pagetypes/truefalse.php');

        $pages = $this->modsettings['pages'] ?? [];
        if (empty($pages)) {
            return;
        }

        $lesson = lesson::load($this->cm->instance);
        $context = context_module::instance($this->cm->coursemodule);

        $previouspageid = 0;
        foreach ($pages as $page) {
            $properties = $this->build_page_properties($page, $previouspageid);
            if ($properties === null) {
                continue;
            }

            $created = lesson_page::create($properties, $lesson, $context, $CFG->maxbytes);
            $previouspageid = $created->id;
        }
    }

    /**
     * Build the lesson_page::create() properties for one AI page.
     *
     * @param array $page AI page definition (page_type, title, content_html, ...).
     * @param int $previouspageid Page id to insert after (0 for the first page).
     * @return stdClass|null Properties object, or null when the page is invalid.
     */
    protected function build_page_properties(array $page, int $previouspageid): ?stdClass {
        $title = trim((string) ($page['title'] ?? ''));
        $contenthtml = trim((string) ($page['content_html'] ?? ''));
        $pagetype = (string) ($page['page_type'] ?? '');

        if ($title === '' || $contenthtml === '') {
            return null;
        }

        $properties = new stdClass();
        $properties->title = $title;
        $properties->contents_editor = [
            'text' => $contenthtml,
            'format' => FORMAT_HTML,
            'itemid' => 0,
        ];
        $properties->pageid = $previouspageid;

        if ($pagetype === 'content') {
            $buttontext = trim((string) ($page['button_text'] ?? ''));
            if ($buttontext === '') {
                return null;
            }
            $properties->qtype = LESSON_PAGE_BRANCHTABLE;
            // Branch table answers are plain strings (button labels).
            $properties->answer_editor = [$buttontext];
            $properties->jumpto = [LESSON_NEXTPAGE];
            return $properties;
        }

        if ($pagetype === 'multi_choice') {
            $properties->qtype = LESSON_PAGE_MULTICHOICE;
        } else if ($pagetype === 'true_false') {
            $properties->qtype = LESSON_PAGE_TRUEFALSE;
        } else {
            return null;
        }

        $options = $page['options'] ?? [];
        if (empty($options)) {
            return null;
        }

        $properties->answer_editor = [];
        $properties->response_editor = [];
        $properties->jumpto = [];
        $properties->score = [];

        foreach ($options as $option) {
            $text = trim((string) ($option['text'] ?? ''));
            if ($text === '') {
                continue;
            }
            $correct = !empty($option['correct']);

            $properties->answer_editor[] = [
                'text' => $text,
                'format' => FORMAT_HTML,
            ];
            $properties->response_editor[] = [
                'text' => trim((string) ($option['feedback'] ?? '')),
                'format' => FORMAT_HTML,
            ];
            $properties->jumpto[] = $correct ? LESSON_NEXTPAGE : LESSON_THISPAGE;
            $properties->score[] = $correct ? 1 : 0;
        }

        if (empty($properties->answer_editor)) {
            return null;
        }

        return $properties;
    }
}
