<?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/>.

/**
 * manage-model file
 *
 * @package   mod_certificatebeautiful
 * @copyright 2025 Eduardo Kraus https://eduardokraus.com/
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use mod_certificatebeautiful\model\form_create;
use mod_certificatebeautiful\model\form_create_page;
use mod_certificatebeautiful\vo\certificatebeautiful_model;

require_once('../../config.php');
require_once("{$CFG->libdir}/tablelib.php");
require_once("{$CFG->dirroot}/mod/certificatebeautiful/classes/model/form_create.php");
require_once("{$CFG->dirroot}/mod/certificatebeautiful/classes/model/form_create_page.php");

global $PAGE, $USER, $CFG;

$id = required_param("id", PARAM_INT);

$context = context_system::instance();
$PAGE->set_context($context);
$PAGE->set_url('/mod/certificatebeautiful/manage-model-list.php', ["id" => $id]);

require_login();
require_capability('mod/certificatebeautiful:addinstance', $context);

if ($id > 0) {
    /** @var certificatebeautiful_model $certificatebeautifulmodel */
    $certificatebeautifulmodel = $DB->get_record("certificatebeautiful_model", ["id" => $id], "*", MUST_EXIST);

    $PAGE->set_title($certificatebeautifulmodel->name);
    $PAGE->set_heading(format_string($certificatebeautifulmodel->name));

    $PAGE->navbar->add(get_string("list_model", "certificatebeautiful"), "manage-model-list.php");
    $PAGE->navbar->add($certificatebeautifulmodel->name, $PAGE->url);

    $certificatebeautifulmodel->pages_info_object = json_decode($certificatebeautifulmodel->pages_info);
    if (count($certificatebeautifulmodel->pages_info_object) == 0) {
        $certificatebeautifulmodel->pages_info_object = [form_create_page::empty_page($certificatebeautifulmodel)];
    }
} else {
    $certificatebeautifulmodel = (object)["id" => -1, "name" => "", "pages_info" => "[]", "orientation" => "L"];

    $PAGE->set_title(get_string("new_model", "certificatebeautiful"));
    $PAGE->set_heading(format_string(get_string("new_model", "certificatebeautiful")));

    $PAGE->navbar->add(get_string("list_model", "certificatebeautiful"), "manage-model-list.php");
    $PAGE->navbar->add(get_string("new_model", "certificatebeautiful"), $PAGE->url);
}

switch (optional_param("action", false, PARAM_TEXT)) {
    case "delete":
        $page = required_param("page", PARAM_INT);
        if ($page) {
            unset($certificatebeautifulmodel->pages_info_object[$page]);
            $certificatebeautifulmodel->pages_info_object = array_values($certificatebeautifulmodel->pages_info_object);

            $certificatebeautifulmodel->pages_info = json_encode($certificatebeautifulmodel->pages_info_object, JSON_PRETTY_PRINT);
            $certificatebeautifulmodel->timemodified = time();
            $DB->update_record("certificatebeautiful_model", $certificatebeautifulmodel);

            redirect("manage-model.php?id={$certificatebeautifulmodel->id}");
        }
        break;
    case "deletemodel":
        $PAGE->navbar->add(get_string("edit_page", "certificatebeautiful"));
        $PAGE->navbar->add(get_string("select_model", "certificatebeautiful"));

        echo $OUTPUT->header();

        $model = $DB->get_record("certificatebeautiful_model", ["id" => $id], "*", MUST_EXIST);

        if (optional_param("confirm", 0, PARAM_INT) && confirm_sesskey()) {
            $DB->delete_records("certificatebeautiful_model", ["id" => $model->id]);
            redirect(
                new moodle_url("/mod/certificatebeautiful/manage-model-list.php"),
                get_string("deletedmodel", "certificatebeautiful", $model->name)
            );
        } else {
            $confirmurl = new moodle_url("/mod/certificatebeautiful/manage-model.php",
                ["id" => $model->id, "action" => "deletemodel", "confirm" => 1, "sesskey" => sesskey()]);
            $cancelurl = new moodle_url("/mod/certificatebeautiful/manage-model.php", ["id" => $model->id]);

            $options = ["continuestr" => get_string('yes')];
            echo $OUTPUT->confirm(
                get_string("deletemodelconfirm", "certificatebeautiful", $model->name), $confirmurl, $cancelurl, $options
            );
        }

        echo $OUTPUT->footer();
        break;
    case "duplicate":
        $model = $DB->get_record("certificatebeautiful_model", ["id" => $id]);
        unset($model->id);
        $model->name = get_string("duplicatedmodule", "moodle", $model->name);
        $model->id = $DB->insert_record("certificatebeautiful_model", $model);
        redirect("manage-model.php?id={$model->id}");
        break;
}

$formcreate = new form_create(null, ["certificatebeautiful_model" => $certificatebeautifulmodel]);
if (!$formcreate->is_cancelled() && $certificatebeautifulmodel = $formcreate->get_data()) {

    if ($id > 0) {
        $model = (object)[
            "id" => $certificatebeautifulmodel->id,
            "name" => $certificatebeautifulmodel->name,
            "timemodified" => time(),
        ];
        $DB->update_record("certificatebeautiful_model", $model);
    } else {
        $model = (object)[
            "name" => $certificatebeautifulmodel->name,
            "orientation" => $certificatebeautifulmodel->orientation,
            "pages_info" => json_encode([form_create_page::empty_page($certificatebeautifulmodel)], JSON_PRETTY_PRINT),
            "timecreated" => time(),
            "timemodified" => time(),
        ];
        $certificatebeautifulmodel->id = $DB->insert_record("certificatebeautiful_model", $model);
    }
    redirect("manage-model.php?id={$certificatebeautifulmodel->id}");
}

echo $OUTPUT->header();
$formcreate->display();
echo $OUTPUT->footer();
