<?php
// This file is part of Moodle - http://moodle.org/
//
// 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 <http://www.gnu.org/licenses/>.

/**
 * Export
 *
 * @package    gradingform_kica
 * @copyright  2023 Michael Gardener <mgardener@cissq.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use gradingform_kica\data;
use gradingform_kica\shared_lib as NED;

require_once(__DIR__.'/../../../../config.php');
require_once(__DIR__.'/lib.php');
require_once(__DIR__.'/edit_form.php');
require_once($CFG->dirroot.'/grade/grading/lib.php');
require_once("$CFG->libdir/excellib.class.php");

$cmid = required_param('cmid', PARAM_INT); // Course ID.
$exporttype = optional_param('exporttype', '', PARAM_TEXT);
$includeallattampts = optional_param('includeallattampts', false, PARAM_BOOL);
$includecriteriatext = optional_param('includecriteriateext', false, PARAM_BOOL);
$includeinactivestudents = optional_param('includeinactivestudents', false, PARAM_BOOL);
$includeungradedstudents = optional_param('includeungradedstudents', false, PARAM_BOOL);
$gradinginstanceid = optional_param('gradinginstanceid', 0, PARAM_INT);

if (!$cm = $DB->get_record('course_modules', ['id' => $cmid])) {
    NED::print_module_error('invalidcoursemodule');
}
if (!$course = $DB->get_record('course', ['id' => $cm->course])) {
    NED::print_module_error('coursemisconf');
}
if (!$assign = $DB->get_record('assign', ['id' => $cm->instance])) {
    NED::print_module_error('errorinvalidflashcardid', 'flashcard');
}

require_course_login($course->id, true, $cm);

$context = context_module::instance($cm->id);

require_capability('gradingform/kica:export', $context);

$contextsystem = \context_system::instance();

$exportactions = data::get_export_actions();

if (!in_array($exporttype, $exportactions)) {
    throw new moodle_exception('invalidaction');
}

$data = new data($cm, $includeallattampts, $includeinactivestudents);
$userids = [];
$creteria = $data->get_creteria();
$userid = $data->get_user_id($gradinginstanceid);
$group = $data->get_group($userid);

switch ($exporttype) {
    case gradingform_kica_controller::EXPORT_STUDENT:
        $user = core_user::get_user($userid);
        $filename = "KICA Student " . fullname($user) . " " . ($group->name ?? '') . " " . $course->shortname . ".xlsx";
        $userids = [$userid => $userid];
        break;
    case gradingform_kica_controller::EXPORT_CLASS:
        if (empty($group)) {
            throw new moodle_exception('nogroupassignment', 'gradingform_kica');
        }
        $filename = "KICA Class " . $group->name . " " . $course->shortname . ".xlsx";
        $userid = $data->get_user_id($gradinginstanceid);
        $userids = $data->get_group_users($group);
        break;
    case gradingform_kica_controller::EXPORT_COURSE:
        $filename = "KICA Course " . $assign->name . " " . $course->shortname . ".xlsx";
        $userids = $data->get_course_users();
        break;
    case gradingform_kica_controller::EXPORT_GT:
        $raterid = $data->get_user_id($gradinginstanceid, true);
        $rater = core_user::get_user($raterid);
        $filename = "KICA Grader " . fullname($rater) . " " . $assign->name . " " . $course->shortname . ".xlsx";
        $userids = $data->get_graded_user_ids($raterid);
        break;
}

$headers = [
    get_string('gradername', 'gradingform_kica'),
    get_string('activityname', 'gradingform_kica'),
    get_string('studentname', 'gradingform_kica'),
    get_string('grade', 'gradingform_kica'),
    get_string('gradedate', 'gradingform_kica'),
    get_string('class', 'gradingform_kica'),
    get_string('school', 'gradingform_kica'),
];

$imax = count($creteria);
for ($i = 1; $i <= $imax; $i++) {
    $headers[] = get_string('criterianame', 'gradingform_kica', $i);
    $headers[] = get_string('criterialevel', 'gradingform_kica', $i);
    $headers[] = get_string('criteriacomment', 'gradingform_kica', $i);
    $headers[] = get_string('criteriagrade', 'gradingform_kica', $i);
}

if ($includeallattampts) {
    $headers[] = get_string('attempt', 'gradingform_kica');
}

$headers[] = get_string('finalcomment', 'gradingform_kica');

// Creating a workbook.
$workbook = new \gradingform_kica\excel_workbook("-");
// Sending HTTP headers.
$workbook->send($filename);
// Creating the first worksheet.
$myxls = $workbook->add_worksheet('download');
$worksheet = $myxls->get_worksheet();

// Format types.
$format = $workbook->add_format();
$format->set_bold(0);

$formatbc = $workbook->add_format();
$formatbc->set_bold(1);
$formatbc->set_align('left');
$formatbc->set_bg_color('silver');

$formatlink = $workbook->add_format();
$formatlink->set_color('blue');
$formatlink->set_underline(1);

$colnum = 0;
foreach ($headers as $item) {
    $myxls->write(0, $colnum, $item, $formatbc);
    $colnum++;
}
$worksheet->freezePane('A2');

$rownum = 1;

foreach ($userids as $userid => $d) {
    $user = core_user::get_user($userid);

    $userattemptdata = $data->get_user_data($userid);

    if (!$includeungradedstudents && !$userattemptdata) {
        continue;
    }

    if (empty($userattemptdata)) {
        $colnum = 0;

        // Grader name.
        $myxls->write($rownum, $colnum, '', $format);
        $colnum++;

        // Activity name.
        $myxls->write($rownum, $colnum, $assign->name, $format);
        $colnum++;

        // Student name.
        $userurl = new moodle_url('/mod/assign/view.php', ['id' => $cm->id, 'rownum' => 0, 'action' => 'grader', 'userid' => $user->id]);
        $myxls->write($rownum, $colnum, fullname($user), $formatlink);
        $worksheet->getCellByColumnAndRow($colnum + 1, $rownum + 1)->getHyperlink()->setUrl($userurl->out(false));
        $colnum++;

        // Grade.
        $myxls->write($rownum, $colnum, '', $format);
        $colnum++;

        // Grade.
        $myxls->write($rownum, $colnum, '', $format);
        $colnum++;

        // Class.
        if ($group = $data->get_group($user->id)) {
            $classurl = new moodle_url('/mod/assign/view.php', ['id' => $cm->id, 'action' => 'grading', 'group' => $group->id]);
            $myxls->write($rownum, $colnum, $group->name, $formatlink);
            $worksheet->getCellByColumnAndRow($colnum + 1, $rownum + 1)->getHyperlink()->setUrl($classurl->out(false));
        } else {
            $cell = $myxls->write($rownum, $colnum, '', $format);
        }
        $colnum++;

        // School.
        $schoolname = '';
        if ($school = $data->get_school($user->id)) {
            $schoolname = $school->get('name');
        }
        $myxls->write($rownum, $colnum, $schoolname, $format);
        $colnum++;
        $rownum++;
    } else {
        $firstattemptdata = reset($userattemptdata);
        $firstcriteria = reset($firstattemptdata);
        $graderid = $firstcriteria->raterid;
        $grade = round($firstcriteria->assigngrade, 2) . '/' . $firstcriteria->gradeoutof;
        $gradedate = userdate($firstcriteria->modified);
        $rater = core_user::get_user($graderid);

        foreach ($userattemptdata as $attemptnum => $userattempt) {

            $colnum = 0;

            // Grader name.
            $myxls->write($rownum, $colnum, fullname($rater), $format);
            $colnum++;

            // Activity name.
            $myxls->write($rownum, $colnum, $assign->name, $format);
            $colnum++;

            // Student name.
            $userurl = new moodle_url('/mod/assign/view.php', ['id' => $cm->id, 'rownum' => 0, 'action' => 'grader', 'userid' => $user->id]);
            $myxls->write($rownum, $colnum, fullname($user), $formatlink);
            $worksheet->getCellByColumnAndRow($colnum + 1, $rownum + 1)->getHyperlink()->setUrl($userurl->out(false));
            $colnum++;

            // Grade.
            $myxls->write($rownum, $colnum, $grade, $format);
            $colnum++;

            // Grade.
            $myxls->write($rownum, $colnum, $gradedate, $format);
            $colnum++;

            // Class.
            if ($group = $data->get_group($user->id)) {
                $classurl = new moodle_url('/mod/assign/view.php', ['id' => $cm->id, 'action' => 'grading', 'group' => $group->id]);
                $myxls->write($rownum, $colnum, $group->name, $formatlink);
                $worksheet->getCellByColumnAndRow($colnum + 1, $rownum + 1)->getHyperlink()->setUrl($classurl->out(false));
            } else {
                $cell = $myxls->write($rownum, $colnum, '', $format);
            }
            $colnum++;

            // School.
            $schoolname = '';
            if ($school = $data->get_school($user->id)) {
                $schoolname = $school->get('name');
            }
            $myxls->write($rownum, $colnum, $schoolname, $format);
            $colnum++;

            foreach ($creteria as $index => $item) {

                if (isset($userattempt[$item->id])) {
                    $datarow = $userattempt[$item->id];

                    // Criteria 1 name.
                    $myxls->write($rownum, $colnum, $item->category, $format);
                    $colnum++;

                    // Criteria 1 level.
                    $critlevel = get_string('headerlevelpoint' . ((int)$datarow->level), 'gradingform_kica');
                    if ($includecriteriatext) {
                        $critlevel .= ': ' . $datarow->definition;
                    }
                    $myxls->write($rownum, $colnum, $critlevel, $format);
                    $colnum++;

                    // Criteria 1 comment.
                    $myxls->write($rownum, $colnum, $datarow->remark, $format);
                    $colnum++;

                    // Criteria 1 grade.
                    $myxls->write($rownum, $colnum, $datarow->grade, $format);
                    $colnum++;
                } else {
                    // Criteria 1 name.
                    $myxls->write($rownum, $colnum, $item->category, $format);
                    $colnum++;

                    // Criteria 1 level.
                    $myxls->write($rownum, $colnum, '', $format);
                    $colnum++;

                    // Criteria 1 comment.
                    $myxls->write($rownum, $colnum, '', $format);
                    $colnum++;

                    // Criteria 1 grade.
                    $myxls->write($rownum, $colnum, '', $format);
                    $colnum++;
                }
            }

            if ($includeallattampts) {
                $myxls->write($rownum, $colnum, ++$datarow->attemptnumber, $format);
                $colnum++;
            }

            // Final Comment.
            $finalcomment = $data->get_final_comment($userid, $attemptnum);
            if (!empty($finalcomment)) {
                $finalcomment = html_to_text($finalcomment);
            } else {
                $finalcomment = '';
            }
            $myxls->write($rownum, $colnum, $finalcomment, $format);
            $colnum++;

            $rownum++;
        }
    }
}
//$worksheet->setAutoFilter('A1:E20');
$worksheet->setAutoFilter(
    $worksheet->calculateWorksheetDimension()
);

$workbook->close();