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

/**
 * Displays the import page for minilesson.
 *
 * @package mod_minilesson
 * @copyright  2025 Justin Hunt  {@link http://poodll.com}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 **/

use mod_minilesson\constants;
use mod_minilesson\utils;
use mod_minilesson\local\importform\baseimportform;

require_once(__DIR__ . '/../../config.php');
require_once($CFG->libdir . '/csvlib.class.php');

$cmid = optional_param('id', 0, PARAM_INT); // Course_module ID, or.
$n = optional_param('n', 0, PARAM_INT);  // Minilesson instance ID.
$leftoverrows = optional_param('leftover_rows', '', PARAM_TEXT);
$action = optional_param('action', null, PARAM_ALPHA);
$iid = optional_param('iid', '', PARAM_INT);
$fromlang = optional_param('fromlang', '', PARAM_TEXT);
$tolang = optional_param('tolang', '', PARAM_TEXT);


if ($cmid) {
    $cm = get_coursemodule_from_id('minilesson', $cmid, 0, false, MUST_EXIST);
    $course = $DB->get_record('course', ['id' => $cm->course], '*', MUST_EXIST);
    $moduleinstance = $DB->get_record('minilesson', ['id' => $cm->instance], '*', MUST_EXIST);
} elseif ($n) {
    $moduleinstance = $DB->get_record('minilesson', ['id' => $n], '*', MUST_EXIST);
    $course = $DB->get_record('course', ['id' => $moduleinstance->course], '*', MUST_EXIST);
    $cm = get_coursemodule_from_instance('minilesson', $moduleinstance->id, $course->id, false, MUST_EXIST);
} else {
    print_error('You must specify a course_module ID or an instance ID');
}


require_login($course, true, $cm);
$modulecontext = context_module::instance($cm->id);
require_capability('mod/minilesson:manage', $modulecontext);

$pagetitle = format_string($moduleinstance->name, true, $course->id);
$pagetitle .= ': ' . get_string('import', constants::M_COMPONENT);
$baseurl = new moodle_url('/mod/minilesson/import.php', ['id' => $cmid, 'fromlang' => $fromlang, 'tolang' => $tolang]);
$formurl = new moodle_url($baseurl);
$term = null;

$PAGE->set_url($baseurl);
$PAGE->navbar->add($pagetitle, $PAGE->url);
$PAGE->set_heading(format_string($course->fullname, true, $course->id));
$PAGE->set_title($pagetitle);
$mode = 'import';

// Get admin settings.
$config = get_config(constants::M_COMPONENT);
if ($config->enablesetuptab) {
    $PAGE->set_pagelayout('popup');
} else {
    $PAGE->set_pagelayout('incourse');
}

$renderer = $PAGE->get_renderer(constants::M_COMPONENT);
$form = new baseimportform($formurl->out(false), ['leftover_rows' => $leftoverrows]);

if ($data = $form->get_data()) {
    $errormessage = '';
    $shouldtranslate = !empty($data->dotranslate);
    $importfromlang = trim((string)($data->fromlang ?? ''));
    $importtolang = trim((string)($data->tolang ?? ''));
    $content = $form->get_file_content('importfile');
    $theimport = new \mod_minilesson\import($moduleinstance, $modulecontext, $course, $cm);

    // Temporarily raise memory limit.
    raise_memory_limit(MEMORY_HUGE);

    $isjson = utils::is_json($content);
    if ($isjson) {
        if (!utils::is_json($content)) {
            $errormessage = get_string('error:invalidjson', constants::M_COMPONENT);
        } else {
            $importdata = json_decode($content);
            if (!isset($importdata->items)) {
                $errormessage = get_string('error:noitemsinjson', constants::M_COMPONENT);
            } else {
                // Optionally translate JSON payloads before importing.
                if ($shouldtranslate && $importfromlang !== '' && $importtolang !== '') {
                    $itemsjson = json_encode($importdata->items);
                    $translateditems = $theimport->call_translate($itemsjson, $importfromlang, $importtolang);
                    if (is_array($translateditems)) {
                        $importdata->items = $translateditems;
                    } elseif ($translateditems && utils::is_json($translateditems)) {
                        $importdata->items = json_decode($translateditems);
                    }
                }
                $theimport->set_reader($importdata, $isjson);
            }
        }
    } else {
        $iid = csv_import_reader::get_new_iid('importminilessonitems');
        $cir = new csv_import_reader($iid, 'importminilessonitems');
        $readcount = $cir->load_csv_content($content, $data->encoding, $data->delimiter_name);
        $csvloaderror = $cir->get_error();
        $theimport->set_reader($cir, $isjson);

        if (!is_null($csvloaderror)) {
            $errormessage = get_string('error:csvloaderror', constants::M_COMPONENT);
        }
        unset($content);
    }


    echo $renderer->header($moduleinstance, $cm, $mode, null, get_string('importing', constants::M_COMPONENT));
    echo $renderer->heading($pagetitle);
    echo $renderer->box(get_string('importresults', constants::M_COMPONENT), 'generalbox minilesson_importintro', 'intro');
    if (empty($errormessage)) {
        $theimport->import_process();
    } else {
        echo $renderer->box($errormessage, 'generalbox minilesson_importintro', 'intro');
    }
    echo $renderer->back_to_import_button($cm);
    echo $renderer->footer();
    die;
}




echo $renderer->header($moduleinstance, $cm, $mode, null, get_string('import', constants::M_COMPONENT));
echo $renderer->heading($pagetitle);
// Import form and instructions.
echo $renderer->heading(get_string('importheading', constants::M_COMPONENT), 4);
echo $renderer->box(
    get_string('importinstructions', constants::M_COMPONENT),
    'generalbox minilesson_importintro',
    'intro'
);
$form->display();

// Export form and instructions.
echo $renderer->heading(get_string('exportheading', constants::M_COMPONENT), 4);
echo $renderer->box(
    get_string('exportinstructions', constants::M_COMPONENT),
    'generalbox minilesson_importintro',
    'intro'
);
$exporturl = moodle_url::make_pluginfile_url(
    $modulecontext->id,
    constants::M_COMPONENT,
    'exportjson',
    0,
    "/",
    'exportitems.json',
    true
);
echo html_writer::link($exporturl, get_string('exportitems', constants::M_COMPONENT), ["class" => "btn btn-primary"]);

// Add an export and translate section to the page.
echo $renderer->heading(get_string('exportandtranslateheading', constants::M_COMPONENT), 4);
echo $renderer->box(
    get_string('exportandtranslateinstructions', constants::M_COMPONENT),
    'generalbox minilesson_importintro',
    'intro'
);
$allangs = utils::get_lang_options();

// Langs Select.
// From Lang.
$actionurl = new moodle_url($PAGE->url, ['sesskey' => sesskey()]);
$fromlangselect = new single_select($actionurl, 'fromlang', $allangs, $fromlang, ['' => get_string('adddots')], 'fromlang');
$fromlangselect->set_label(get_string('fromlang', constants::M_COMPONENT), []);
echo html_writer::div($OUTPUT->render($fromlangselect), 'ml_import_lang mb-2');

// To Lang.
$actionurl = new moodle_url($PAGE->url, ['sesskey' => sesskey()]);
$tolangselect = new single_select($actionurl, 'tolang', $allangs, $tolang, ['' => get_string('adddots')], 'tolang');
$tolangselect->set_label(get_string('tolang', constants::M_COMPONENT), []);
echo html_writer::div($OUTPUT->render($tolangselect), 'ml_import_lang mb-2');

if (
    (!empty($fromlang) && array_key_exists($fromlang, $allangs)) &&
    (!empty($tolang) && array_key_exists($tolang, $allangs))
) {
    $exporturl = moodle_url::make_pluginfile_url(
        $modulecontext->id,
        constants::M_COMPONENT,
        'translatejson',
        0,
        "/$fromlang/$tolang/",
        'exportitems.json',
        true
    );
    echo html_writer::link(
        $exporturl,
        get_string('exportandtranslateitems', constants::M_COMPONENT),
        ["class" => "btn btn-primary"]
    );
}
echo $renderer->footer();
