<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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 <https://www.gnu.org/licenses/>.
/**
 * Configure how grades and scales are interpreted by the plugin if no other grade to pass is specified
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

require_once("../../config.php");

require_once($CFG->libdir.'/adminlib.php');
admin_externalpage_setup("local_treestudyplan_gradeconfig");

$systemcontext = context_system::instance();
// Check if user has capability to manage this.
require_capability('local/treestudyplan:configure', $systemcontext);

$PAGE->requires->js_call_amd('local_treestudyplan/cfg-grades', 'init');

/**
 * Table name for gradecfg table
 * @var string
 */
const GRADECFG_TABLE = "local_treestudyplan_gradecfg";

$scales = \grade_scale::fetch_all_global();
$mappings = $DB->get_records(GRADECFG_TABLE);
$scalecfgs = [];
$gradecfgs = [];
foreach ($mappings as $cfg) {
    if (!empty($cfg->scale_id)) {
        $scalecfgs[$cfg->scale_id] = $cfg;
    } else if (!empty($cfg->grade_points)) {
        $gradecfgs[$cfg->grade_points] = $cfg;
    }
}

print $OUTPUT->header();
print "<pre>";
print $CFG->gradebookroles;
print "</pre>";

if ($_POST["action"] == "update") {
    // First loop through the scales to see which need to be updated.
    foreach ($scales as $scale) {
        if (array_key_exists($scale->id, $scalecfgs)) {
            $scalecfg = $scalecfgs[$scale->id];

            $needupdate = false;
            foreach (["min_progress", "min_completed"] as $handle) {
                $key = "s_{$scale->id}_{$handle}";
                if (array_key_exists($key, $_POST) && is_numeric($_POST[$key])) {
                    $value = intval($_POST[$key]);
                    if ($value != $scalecfg->$handle) {
                        $scalecfg->$handle = $value;
                        $needupdate = true;
                    }
                }
            }
            if ($needupdate) {
                $DB->update_record(GRADECFG_TABLE, $scalecfg);
            }

        } else {
            $scalecfg = (object)[ "scale_id" => $scale->id];
            $requireinsert = false;
            foreach (["min_progress", "min_completed"] as $handle) {
                $key = "s_{$scale->id}_{$handle}";
                if (array_key_exists($key, $_POST) && is_numeric($_POST[$key])) {
                    $scalecfg->$handle = intval($_POST[$key]);
                    $requireinsert = true;
                }
            }
            if ($requireinsert) {
                // Insert into database and add to the list of scale configs.
                $id = $DB->insert_record(GRADECFG_TABLE, $scalecfg);
                $scalecfg = $DB->get_record(GRADECFG_TABLE, ['id' => $id]);
                $scalecfgs[$id] = $scalecfg;
            }
        }
    }
    // Now, loop through the gradepoints to parse .
    $deletelist = [];
    foreach ($gradecfgs as $gradecfg) {
        $deletekey = "g_{$gradecfg->grade_points}_delete";
        if (array_key_exists($deletekey, $_POST) && boolval($_POST[$deletekey]) === true) {
            $DB->delete_records(GRADECFG_TABLE, ["id" => $gradecfg->id]);
            $deletelist[] = $gradecfg;
        } else {
            foreach (["min_progress", "min_completed"] as $handle) {
                $key = "g_{$gradecfg->grade_points}_{$handle}";
                if (array_key_exists($key, $_POST) && is_numeric($_POST[$key])) {
                    $gradecfg->$handle = floatval($_POST[$key]);
                }
            }
            $DB->update_record(GRADECFG_TABLE, $gradecfg);
            // Reload to ensure proper rounding is done.
            $gradecfgs[$gradecfg->grade_points] = $DB->get_record(GRADECFG_TABLE, ['id' => $gradecfg->id]);
        }
    }

    foreach ($deletelist as $gradeconfig) {
        unset($gradecfgs[$gradecfg->grade_points]);
    }
    unset($deletelist);

    // And add an optionally existing new gradepoint setting.
    if (array_key_exists("g_new_gradepoints", $_POST)
        && !empty($_POST["g_new_gradepoints"])
        && is_numeric($_POST["g_new_gradepoints"]) ) {
        $gp = intval($_POST["g_new_gradepoints"]);
        if (!array_key_exists($gp, $gradecfgs)) {
            $gradecfg = (object)[ "grade_points" => $gp];
            $requireinsert = false;
            foreach (["min_progress", "min_completed"] as $handle) {
                $key = "g_new_{$handle}";
                if (array_key_exists($key, $_POST) && is_numeric($_POST[$key])) {
                    $gradecfg->$handle = floatval($_POST[$key]);
                    $requireinsert = true;
                }
            }
            if ($requireinsert) {
                // Insert into database and add to the list of grade configs.
                $id = $DB->insert_record(GRADECFG_TABLE, $gradecfg);
                // Reload to ensure proper rounding is done.
                $gradecfg = $DB->get_record(GRADECFG_TABLE, ['id' => $id]);
                $gradecfgs[$id] = $gradecfg;
            }
        }
    }

}

    // Process all available scales and load the current configuration for it.
$data = [];
foreach ($scales as $scale) {
    $scale->load_items();
    $scalecfg = null;
    if (array_key_exists($scale->id, $scalecfgs)) {
        $scalecfg = $scalecfgs[$scale->id];
    }

    $attrsc = ['value' => '', 'disabled' => 'disabled'];
    $attrsp = ['value' => '', 'disabled' => 'disabled'];

    if (!isset($scalecfg) || $scalecfg->min_completed == "") {
        $attrsc["selected"] = "selected";
    }
    if (!isset($scalecfg) || $scalecfg->min_progress == "") {
        $attrsp["selected"] = "selected";
    }

    $optionscompleted = html_writer::tag("option",
                                         get_string('select_scaleitem', 'local_treestudyplan'),
                                         $attrsc);
    $optionsprogress = html_writer::tag("option",
                                         get_string('select_scaleitem', 'local_treestudyplan'),
                                         $attrsp);
    $key = 1; // Start counting by one, as used in sum aggregations.

    foreach ($scale->scale_items as $value) {
        $attrsc = ["value" => $key];
        $attrsp = ["value" => $key];

        if (isset($scalecfg)) {
            if (intval($scalecfg->min_completed) == $key) {
                $attrsc["selected"] = "selected";
            }
            if (intval($scalecfg->min_progress) == $key) {
                $attrsp["selected"] = "selected";
            }
        }
        $optionsprogress .= html_writer::tag("option", $value, $attrsp);
        $optionscompleted .= html_writer::tag("option", $value, $attrsc);
        $key++;
    }

    $row = [];
    $row[] = $scale->name;

    $row[] = html_writer::tag("select",
                              $optionscompleted,
                              ['name' => "s_{$scale->id}_min_completed", 'autocomplete' => 'off']);
    $data[] = $row;
}

print html_writer::start_tag("form", ["method" => "post"]);
print html_writer::tag("input", null, ['name' => "action", 'value' => 'update', 'type' => 'hidden']);

$table = new html_table();
$table->id = "";
$table->attributes['class'] = 'generaltable m-roomtable';
$table->tablealign = 'center';
$table->head = [];
$table->data = $data;
$table->head[] = get_string('scale');
$table->head[] = get_string('min_completed', 'local_treestudyplan');

print $OUTPUT->heading(get_string('cfg_grades_desc_head', 'local_treestudyplan'));
print html_writer::tag('p', get_string('cfg_grades_desc', 'local_treestudyplan'));
print $OUTPUT->heading(get_string('cfg_grades_scales', 'local_treestudyplan'));
print html_writer::tag('div', html_writer::table($table), ['class' => 'flexible-wrap']);

$data = [];
foreach ($gradecfgs as $g) {
    $row = [];
    $row[] = $g->grade_points;
    $row[] = html_writer::tag(  "input", null,
                               ['name' => "g_{$g->grade_points}_min_completed",
                                'value' => "{$g->min_completed}",
                                'type' => 'text',
                                "class" => "float",
                                'autocomplete' => 'off']);
    $row[] = html_writer::tag("input",
                              null,
                              ['name' => "g_{$g->grade_points}_delete", 'type' => 'checkbox']);
    $data[] = $row;
}

$row = [];
$row[] = html_writer::tag("input", null,
                          [ 'name' => "g_new_gradepoints",
                            'value' => '',
                            'type' => 'number',
                            'min' => '0',
                            'pattern' => '/d+',
                            'step' => '1',
                            'autocomplete' => 'off']);
$row[] = html_writer::tag("input", null,
                          [ 'name' => "g_new_min_completed",
                          'value' => '',
                          'type' => 'text',
                          "class" => "float",
                          'autocomplete' => 'off']);

$data[] = $row;

$table = new html_table();
$table->id = "";
$table->attributes['class'] = 'generaltable m-roomtable';
$table->tablealign = 'center';
$table->head = [];
$table->data = $data;
$table->head[] = get_string('grade_points', 'local_treestudyplan');
$table->head[] = get_string('min_completed', 'local_treestudyplan');
$table->head[] = get_string('delete', );

print $OUTPUT->heading(get_string('cfg_grades_grades', 'local_treestudyplan'));
print html_writer::tag('div', html_writer::table($table), ['class' => 'flexible-wrap']);
print html_writer::tag("input",
                        null,
                        ['value' => get_string("save"), 'type' => 'submit', "class" => "btn btn-primary"]);
print html_writer::end_tag("form");

print $OUTPUT->footer();
