<?php
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');

const GRADECFG_TABLE = "local_treestudyplan_gradecfg";

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

print $OUTPUT->header();

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,$scale_cfgs)){
            $scalecfg = $scale_cfgs[$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]);
                $scale_cfgs[$id] = $scalecfg;
            }
        }
    }
    // Now, loop through the gradepoints to parse 
    $deletelist = [];
    foreach($grade_cfgs 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
            $grade_cfgs[$gradecfg->grade_points] = $DB->get_record(GRADECFG_TABLE,['id' => $gradecfg->id]);
        }
    }

    foreach($deletelist as $gradeconfig){
        unset($grade_cfgs[$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,$grade_cfgs)){
            $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]);
                $grade_cfgs[$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,$scale_cfgs)){
        $scalecfg = $scale_cfgs[$scale->id];
    }

    $attrs_c = ['value' => '','disabled' => 'disabled', ];
    $attrs_p = ['value' => '','disabled' => 'disabled', ];

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

    $options_completed = html_writer::tag("option",get_string('select_scaleitem','local_treestudyplan'),$attrs_c);
    $options_progress = html_writer::tag("option",get_string('select_scaleitem','local_treestudyplan'),$attrs_p);
    $key = 1; // Start counting by one, as used in sum aggregations

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

        if(isset($scalecfg)){
            if(intval($scalecfg->min_completed) == $key){
                $attrs_c["selected"] = "selected";
            }
            if(intval($scalecfg->min_progress) == $key){
                $attrs_p["selected"] = "selected";
            }
        }
        $options_progress .= html_writer::tag("option",$value,$attrs_p);
        $options_completed .= html_writer::tag("option",$value,$attrs_c);
        $key++;
    }

	$row = [];
	$row[] = $scale->name;
	//$row[] = html_writer::tag("select", $options_progress, ['name' => "s_{$scale->id}_min_progress",'autocomplete' => 'off']) ;
	$row[] = html_writer::tag("select", $options_completed, ['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->summary = '';//get_string('uploadtimetable_preview', 'local_chronotable');
$table->head = [];
$table->data = $data;
$table->head[] = get_string('scale');
//$table->head[] = get_string('min_progress', 'local_treestudyplan');
$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($grade_cfgs as $g){
    $row = [];
	$row[] = $g->grade_points;
//    $row[] = html_writer::tag("input", null, ['name' => "g_{$g->grade_points}_min_progress", 'value' => "{$g->min_progress}", 'type' => 'text', "class" => "float", 'autocomplete' => 'off']) ;
    $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_progress", 'value' => '', 'type' => 'text', "class" => "float", '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->summary = '';//get_string('uploadtimetable_preview', 'local_chronotable');
$table->head = [];
$table->data = $data;
$table->head[] = get_string('grade_points', 'local_treestudyplan');
//$table->head[] = get_string('min_progress', '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();
