<?php
require_once($CFG->dirroot.'/course/modlib.php');

use local_treestudyplan\local\helpers\webservicehelper;
use \local_treestudyplan\studyplan;
defined('MOODLE_INTERNAL') || die();

function local_treestudyplan_unit_get_editor_options($context) {
    global $CFG;
    return array('subdirs'=>1, 'maxbytes'=>$CFG->maxbytes, 'maxfiles'=>-1, 'changeformat'=>1, 'context'=>$context, 'noclean'=>1, 'trusttext'=>0);
}

function local_treestudyplan_extend_navigation(global_navigation $navigation) {
    global $CFG, $PAGE, $COURSE, $USER;

	$systemcontext = context_system::instance();

	// Moodle 4.0-4.2 do not yet support customizing the primary navigation bar (it is a planned feature though)
	// For now, go to theme settings and add the following into "Custom menu items"
	//    [your name for my studyplan]|/local/treestudyplan/myreport.php
	//    [your name for studyplan viewing]|/local/treestudyplan/view-plan.php
	//    [your name for studyplan managing]|/local/treestudyplan/edit-plan.php
	// For example:
	//    Mijn studieplan|/local/treestudyplan/myreport.php
	//    Studieplannen|/local/treestudyplan/view-plan.php
	//    Studieplannen beheren|/local/treestudyplan/edit-plan.php

	// Using some javascript magic we'll hide the links that are not accessible
	// (Since the Output API does not easily support inline style tags, adding one through Javascript is easier,
	//  and not much more complex than loading a separate stylesheet for each link we want to hide)
	// we will add all the hrefs that should be hidden to this variable below
	$hide_primary_hrefs = [];

	if($USER->id > 1) // Don't show if user is not logged in (id == 0) or is guest user (id == 1)
	{

		$userstudyplans = studyplan::find_for_user($USER->id);
		if(!empty($userstudyplans))
		{
		
			// create studyplan node
			$node = navigation_node::create(
				get_string("link_myreport","local_treestudyplan"),
				new moodle_url($CFG->wwwroot . "/local/treestudyplan/myreport.php", array()),
				global_navigation::TYPE_SYSTEM, 
				null, 
				"local_treestudyplan_myreport",
				new pix_icon("myreport", '', 'local_treestudyplan')
				);
			$node->showinflatnavigation = true;
			$node->showinsecondarynavigation=true;
		
			// create invitenode node
			$invitenode = navigation_node::create(
				get_string("manage_invites","local_treestudyplan"),
				new moodle_url($CFG->wwwroot . "/local/treestudyplan/invitations.php", array()),
				global_navigation::TYPE_CUSTOM , 
				null, 
				"local_treestudyplan_invitemgmt",
				new pix_icon("invitemgmt", '', 'local_treestudyplan')
				);
			$invitenode->showinflatnavigation = false;
			$node->add_node($invitenode);


			$navigation->add_node($node,'mycourses');
		}
		else {
			$hide_primary_hrefs[] = "/local/treestudyplan/myreport.php";
		}
		if(	has_capability('local/treestudyplan:viewuserreports',context_system::instance()) 
			|| webservicehelper::has_capability_in_any_category('local/treestudyplan:viewuserreports'))
		{
			$node = navigation_node::create(
				get_string("link_viewplan","local_treestudyplan"),
				new moodle_url($CFG->wwwroot . "/local/treestudyplan/view-plan.php", array()),
				global_navigation::TYPE_SYSTEM , 
				null, 
				"local_treestudyplan_viewplan",
				new pix_icon("viewplans", '', 'local_treestudyplan')
				);
			$node->showinflatnavigation = true;
			$node->showinsecondarynavigation=true;
			$navigation->add_node($node,'mycourses');
		}
		else {
			$hide_primary_hrefs[] = "/local/treestudyplan/view-plan.php";
		}
		if(	has_capability('local/treestudyplan:editstudyplan',context_system::instance())
		  	|| webservicehelper::has_capability_in_any_category('local/treestudyplan:editstudyplan')
		   )
		{
			$node = navigation_node::create(
				get_string("cfg_plans","local_treestudyplan"),
				new moodle_url($CFG->wwwroot . "/local/treestudyplan/edit-plan.php", array()),
				global_navigation::TYPE_SYSTEM , 
				null, 
				"local_treestudyplan_editplan",
				new pix_icon("viewplans", '', 'local_treestudyplan')
				);
			$node->showinflatnavigation = true;
			$node->showinsecondarynavigation=true;
			$navigation->add_node($node,'mycourses');
		}
		else {
			$hide_primary_hrefs[] = "/local/treestudyplan/edit-plan.php";
		}
	} 
	else {
		$hide_primary_hrefs[] = "/local/treestudyplan/myreport.php";
		$hide_primary_hrefs[] = "/local/treestudyplan/edit-plan.php";
		$hide_primary_hrefs[] = "/local/treestudyplan/view-plan.php";
	}
	// create invitenode node
	$invitenode = navigation_node::create(
		get_string("nav_invited","local_treestudyplan"),
		new moodle_url($CFG->wwwroot . "/local/treestudyplan/invited.php", array()),
		global_navigation::TYPE_USER , 
		null, 
		"local_treestudyplan_invitemgmt",
		new pix_icon("nav_invited", '', 'local_treestudyplan')
		);
	$invitenode->showinflatnavigation = false;
	$navigation->add_node($invitenode,'mycourses');


	// Now using some javascript magic, we'll hide the links that are not accessible
	$PAGE->requires->js_call_amd('local_treestudyplan/primary-nav-tools', 'hide_primary', [$hide_primary_hrefs]);



}

function local_treestudyplan_extend_navigation_category_settings($navigation, context_coursecat $coursecategorycontext) {
	global $CFG, $PAGE;
	$categoryid = $coursecategorycontext->instanceid;
	if(has_capability('local/treestudyplan:editstudyplan',$coursecategorycontext)){
		$node = $navigation->add(
			get_string('treestudyplan:editstudyplan',"local_treestudyplan"),
			new moodle_url($CFG->wwwroot . "/local/treestudyplan/edit-plan.php", ["categoryid"=>$categoryid]),
			global_navigation::TYPE_CATEGORY, 
			null, 
			"local_treestudyplan_editplan",
			new pix_icon("editplans", '', 'local_treestudyplan')
		);
		//$node->make_active();
	}
	if(has_capability('local/treestudyplan:viewuserreports',$coursecategorycontext)){
		$node = $navigation->add(
			get_string('link_viewplan',"local_treestudyplan"),
			new moodle_url($CFG->wwwroot . "/local/treestudyplan/view-plan.php", ["categoryid"=>$categoryid]),
			global_navigation::TYPE_CATEGORY, 
			null, 
			"local_treestudyplan_viewplan",
			new pix_icon("viewplans", '', 'local_treestudyplan')
		);
		//$node->make_active();
	}

}

function local_treestudyplan_get_fontawesome_icon_map() {

    // Create the icon map with the icons which are used in any case.
    $iconmapping = [
            'local_treestudyplan:myreport' => 'fa-vcard',
			'local_treestudyplan:editplans' => 'fa-share-alt',
			'local_treestudyplan:viewplans' => 'fa-share-alt',
    ];

    return $iconmapping;
}
/**
 * Helper function to reset the icon system used as updatecallback function when saving some of the plugin's settings.
 */
function local_treestudyplan_reset_fontawesome_icon_map() {
    // Reset the icon system cache.
    // There is the function \core\output\icon_system::reset_caches() which does seem to be only usable in unit tests.
    // Thus, we clear the icon system cache brutally.
    $cache = \cache::make('core', 'fontawesomeiconmapping');
    $cache->delete('mapping');
    // And rebuild it brutally.
    $instance = \core\output\icon_system::instance(\core\output\icon_system::FONTAWESOME);
    $instance->get_icon_name_map();
}

function local_treestudyplan_send_invite($inviteid)
{
	global $DB,$USER,$CFG;
	$invite = $DB->get_record("local_treestudyplan_invit", array('id' => $inviteid));

	$noreply = 'noreply@' . get_host_from_url($CFG->wwwroot);
	$mailer = get_mailer();
	$mailer->setFrom($noreply,"{$USER->firstname} {$USER->lastname}");
	$mailer->addAddress($invite->email,$invite->name);
	$mailer->addReplyTo($USER->email,"{$USER->firstname} {$USER->lastname}");

	$invitehref = $CFG->wwwroot."/local/treestudyplan/invited.php?key={$invite->invitekey}";

	$data = [	'permissions'=> '', 
				'invitee' => $invite->name,
				'sender' => "{$USER->firstname} {$USER->lastname}",
				'link' => $invitehref];

	if($invite->allow_details || $invite->allow_calendar || $invite->allow_badges)
	{
		$data['permissions'] = get_string('invite_mail_permissions','local_treestudyplan');
		$data['permissions'] .= "<ul>\n";
		if($invite->allow_details )
		{
			$data['permissions'] .= "<li>".get_string('invite_allow_details','local_treestudyplan')."</li>\n";
		}
		if($invite->allow_calendar)
		{
			$data['permissions'] .= "<li>".get_string('invite_allow_calendar','local_treestudyplan')."</li>\n";
		}
		if($invite->allow_badges)
		{
			$data['permissions'] .= "<li>".get_string('invite_allow_badges','local_treestudyplan')."</li>\n";
		}

		$data['permissions'] .= "</ul></p>\n";
	}

	$body = get_string('invite_mail_text','local_treestudyplan',$data);
	$subject = get_string('invite_mail_subject','local_treestudyplan', $data);

	$html = "
	<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
	<html xmlns='http://www.w3.org/1999/xhtml'>
	 <head>
	  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
	  <title>{$subject}</title>
	  <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
	</head>
	<body>
	{$body}
	</body>
	</html>";

	$mailer->isHTML(true);
	$mailer->Subject = $subject;
	$mailer->Body = $html;
	$mailer->AltBody = strip_tags($body);

	$mailer->send();

}

function local_treestudyplan_find_cohortmembers($cohortid)
{
    global $DB;
    // By default wherecondition retrieves all users except the deleted, not confirmed and guest.
    $params = ['cohortid' => $cohortid];
    $sql = "SELECT * FROM {user} u
                JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)
            WHERE u.suspended = 0 AND u.id > 1
            ORDER BY u.lastname
            ";
    $availableusers = $DB->get_records_sql($sql,$params);
    return $availableusers;
}

function local_treestudyplan_get_cohort_path($cohort)
{
    $cohortcontext = context::instance_by_id($cohort->contextid);
    if($cohortcontext && $cohortcontext->id != SYSCONTEXTID)
    {
        $ctxpath = array_map(
            function($ctx){ return $ctx->get_context_name(false);},
            $cohortcontext->get_parent_contexts(true)
            );
        array_pop($ctxpath); // pop system context off the list
        $ctxpath = array_reverse($ctxpath);
        $ctxpath[] = $cohort->name;

        return implode(" / ",$ctxpath);
    }
    else
    {
        return $cohort->name;
    }
}


function local_treestudyplan_output_fragment_mod_edit_form($args){
	global $CFG;
	global $DB;
	$args = (object)$args;
	$context = $args->context;
	
	if(empty($args->cmid)){
		return "RANDOM!";
	}

	// Check the course module exists.
	$cm = \get_coursemodule_from_id('', $args->cmid, 0, false, MUST_EXIST);

	// Check the course exists.
	$course = \get_course($cm->course);

	// require_login
	require_login($course, false, $cm); // needed to setup proper $COURSE

	list($cm, $context, $module, $data, $cw) = \get_moduleinfo_data($cm, $course);

	$modmoodleform = "$CFG->dirroot/mod/$module->name/mod_form.php";
	if (file_exists($modmoodleform)) {
		require_once($modmoodleform);
	} else {
		print_error('noformdesc');
	}

	$mformclassname = 'mod_'.$module->name.'_mod_form';
	$mform = new $mformclassname($data, $cw->section, $cm, $course);
	$mform->set_data($data);

	return $mform->render();


}