<?php
// If not, assume the cwd is not symlinked and proceed as we are used to
require_once("../../config.php");

require_once($CFG->libdir.'/weblib.php');
require_once($CFG->dirroot.'/grade/querylib.php');
require_once($CFG->dirroot.'/cohort/lib.php');
require_once($CFG->dirroot.'/cohort/locallib.php');
require_once("lib.php");

use local_treestudyplan;

//admin_externalpage_setup('major');
$systemcontext = context_system::instance();


require_login();
require_capability('local/treestudyplan:viewothercards',$systemcontext);

$PAGE->set_pagelayout('base');
$PAGE->set_context($systemcontext);
$PAGE->set_title(get_string('report_index','local_treestudyplan'));
$PAGE->set_heading(get_string('report_index','local_treestudyplan'));

// Load javascripts
//$PAGE->requires->js_call_amd('local_treestudyplan/fixlinks', 'init', ['div.tab-content']);
$PAGE->requires->js_call_amd('block_gradelevel/renderbadge', 'init');
$PAGE->requires->js_call_amd('local_treestudyplan/report', 'init');
//$PAGE->requires->css(new moodle_url($CFG->wwwroot.'/local/treestudyplan/css/eqstyles.css'));
$PAGE->requires->css(new moodle_url($CFG->wwwroot.'/local/treestudyplan/css/bootstrap-toggle.min.css'));


$userid = null;
$studentid = optional_param('studentid', '', PARAM_INT);
$cohortid = optional_param('cohortid', '', PARAM_INT);
if(!empty($studentid)){
    $PAGE->set_url("/local/treestudyplan/reports.php",array('studentid' => $studentid));
    $student = $DB->get_record("user",['id' => $studentid]);

    $userlist = [];
    $nextstudent = null;
    $prevstudent = null;
    if(!empty($cohortid))
    {
        $cohort = $DB->get_record("cohort",['id' => $cohortid]);
        $userlist = array_values(local_treestudyplan_find_cohortmembers($cohortid));
        for($i = 0; $i < count($userlist); $i++)
        {
            if($userlist[$i]->userid == $studentid)
            {
                if($i > 0)
                {
                    $prevstudent = (object)['id' => $userlist[$i - 1]->userid, 'name' => "{$userlist[$i - 1]->firstname} {$userlist[$i - 1]->lastname}"];
                }
                if($i < count($userlist) - 1)
                {
                    $nextstudent = (object)['id' => $userlist[$i + 1]->userid, 'name' => "{$userlist[$i + 1]->firstname} {$userlist[$i + 1]->lastname}"];
                }
                break;
            }
        }

        $cohortpath = local_treestudyplan_get_cohort_path($cohort);
        $PAGE->set_title(get_string('report_invited','local_treestudyplan',"{$cohortpath}: {$student->firstname} {$student->lastname}"));
        $PAGE->set_heading(get_string('report_invited','local_treestudyplan',"{$cohortpath}: {$student->firstname} {$student->lastname}"));
    }
    else
    {
        $PAGE->set_title(get_string('report_invited','local_treestudyplan',"$cohort->{$student->firstname} {$student->lastname}"));
        $PAGE->set_heading(get_string('report_invited','local_treestudyplan',"{$student->firstname} {$student->lastname}"));
    }

    $gradewriter = new local_treestudyplan_cardwriter($studentid,true);
    $badgewriter = new local_treestudyplan_badgewriter($studentid);
    $calendarwriter = new local_treestudyplan_calendarwriter($studentid);

    print $OUTPUT->header();

    print "<div class='m-buttonbar' style='margin-bottom: 1.5em; height: 1em;'>";
    if(isset($prevstudent))
    {
        print "<a style='float:left;' href='/local/treestudyplan/reports.php?studentid={$prevstudent->id}&cohortid={$cohortid}'><i class='fa fa-arrow-left'></i> {$prevstudent->name} </a>";
    }
    if(isset($nextstudent))
    {
        print "<a style='float:right;' href='/local/treestudyplan/reports.php?studentid={$nextstudent->id}&cohortid={$cohortid}'>{$nextstudent->name} <i class='fa fa-arrow-right'></i></a>";
    }    
    print "</div>";
    print "<ul class='nav nav-tabs' role='tablist'>";
    print "<li class='nav-item'><a class='nav-link active' href='#link-report' data-toggle='tab' role='tab'>".get_string('nav_report','local_treestudyplan')."</a></li>";
    print "<li class='nav-item'><a class='nav-link ' href='#link-badges' data-toggle='tab' role='tab'>".get_string('nav_badges','local_treestudyplan')."</a></li>";
    print "<li class='nav-item'><a class='nav-link ' href='#link-calendar' data-toggle='tab' role='tab'>".get_string('nav_calendar','local_treestudyplan')."</a></li>";
    print "</ul>";

    print "<div class='tab-content mt-3'>";

    print "<div class='tab-pane active' id='link-report' data-toggle='tab' role='tab'>";
    print $gradewriter->render(true,false);
    print "</div>";

    print "<div class='tab-pane ' id='link-badges' data-toggle='tab' role='tab'>";
    print $badgewriter->render();
    print "</div>";

    print "<div class='tab-pane' id='link-calendar' data-toggle='tab' role='tab'>";
    print $calendarwriter->render();
    print "</div>";

    print "</div>";


    print $OUTPUT->footer();

}
else {
	$PAGE->set_url("/local/treestudyplan/reports.php",array());
    // show student picker
    $cohortlist = $DB->get_records("cohort");
    $cohorts = [];
    foreach($cohortlist as $c)
    {
	    if($c->visible)
	    {
            $cohortcontext = context::instance_by_id($c->contextid);
            if($cohortcontext) // TODO: add check if user has rights in this context
            {
                $users = local_treestudyplan_find_cohortmembers($c->id);

		        $cohorts[$c->id] = (object)[
                    'id' => $c->id,
                    'cohort' => $c,
                    'name' => $c->name,
                    'path' => local_treestudyplan_get_cohort_path($c),
                    'users' => $users,
                    ];
            }
	    }
    }

    print $OUTPUT->header();
    usort($cohorts,function($a,$b){
        return $a->path <=> $b->path;
    });

     $regex = get_config('local_treestudyplan', 'cohortidregex');
    foreach($cohorts as $c)
    {
        $m = [];
		if(preg_match("/".$regex."/",$c->cohort->idnumber,$m) && $c->cohort->visible)
        {
            print "<legend class='collapse-header'><a data-toggle='collapse' class='collapsed' href='#cohort-{$c->id}' role='button'>{$c->path}</a></legend>";
            print "<div id='cohort-{$c->id}' class='collapse'>";
            print "<div class='card card-body'><ul class='gradecardlist'>";
            foreach($c->users as $u)
            {
                print "<li class='gradestudent'>";
                print "<a href='/local/treestudyplan/reports.php?studentid={$u->userid}&cohortid={$c->id}'>{$u->firstname} {$u->lastname}</a>";
                print "</li>";
            }

            print "</ul>";
            print "</div></div>";
        }
    }
    print "</div>";
    
    print $OUTPUT->footer();
}
