<?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");
use core\context\system as context_system;

$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;
    }
}

$action = optional_param("action", "", PARAM_TEXT);
if ($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_completed"] as $handle) {
                $key = "s_{$scale->id}_{$handle}";
                if (($v = optional_param($key, null, PARAM_INT)) !== null) {
                    if ($v != $scalecfg->$handle) {
                        $scalecfg->$handle = $v;
                        $needupdate = true;
                    }
                }
            }
            if ($needupdate) {
                $DB->update_record(GRADECFG_TABLE, $scalecfg);
            }
        } else {
            $scalecfg = (object)[ "scale_id" => $scale->id];
            $requireinsert = false;
            foreach (["min_completed"] as $handle) {
                $key = "s_{$scale->id}_{$handle}";
                if (($v = optional_param($key, null, PARAM_INT)) !== null) {
                    $scalecfg->$handle = $v;
                    $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";
        $dval = optional_param($deletekey, "", PARAM_TEXT);
        if (in_array(strtolower($dval), ["on", "true"])) {
            $DB->delete_records(GRADECFG_TABLE, ["id" => $gradecfg->id]);
            $deletelist[] = $gradecfg;
        } else {
            foreach (["min_completed"] as $handle) {
                $key = "g_{$gradecfg->grade_points}_{$handle}";
                $gradecfg->$handle = optional_param($key, null, PARAM_LOCALISEDFLOAT);
                if ($gradecfg->$handle !== null) {
                    $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[$gradeconfig->grade_points]);
    }
    unset($deletelist);

    // And add an optionally existing new gradepoint setting.
    if (($gp = optional_param("g_new_gradepoints", null, PARAM_INT)) !== null) {
        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 (($v = optional_param($key, null, PARAM_LOCALISEDFLOAT)) !== null) {
                    $gradecfg->$handle = $v;
                    $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.
$scalesdata = [];
foreach ($scales as $scale) {
    $scale->load_items();
    unset($scalecfg); // Unset variable each iteration.
    if (array_key_exists($scale->id, $scalecfgs)) {
        $scalecfg = $scalecfgs[$scale->id];
    }

    $scaledata = new \stdClass();
    $scaledata->id = $scale->id;
    $scaledata->name = $scale->name;
    $scaledata->options = [ // Initialize with the default "unset" option.
        [
            "value" => '',
            "title" => get_string('select_scaleitem', 'local_treestudyplan'),
            "disabled" => true,
            "selected" => boolval(!isset($scalecfg) || $scalecfg->min_completed == ""),
        ],
    ];

    $key = 1; // Start counting by one, as used in sum aggregations.
    foreach ($scale->scale_items as $value) {
        $scaledata->options[] = [
            "value" => $key,
            "title" => $value,
            "selected" => boolval(isset($scalecfg) && intval($scalecfg->min_completed) == $key),
        ];
        $key++;
    }

    $scalesdata[] = $scaledata;
}

$gradesdata = [];
foreach ($gradecfgs as $g) {
    $gradedata = new \stdClass();
    $gradedata->points = $g->grade_points;
    $gradedata->threshold = $g->min_completed;
    $gradesdata[] = $gradedata;
}

print $OUTPUT->header();
$data = [
    "scales" => $scalesdata,
    "grades" => $gradesdata,
];
print $OUTPUT->render_from_template('local_treestudyplan/cfg-grades', $data);
print $OUTPUT->footer();
