<?php
// This file is part of
//
// 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/>.

require_once('../../../../config.php');
require_once('../../locallib.php');
require_once('../../lib.php');

// Test libs
// require_once('../../libs/testlib.php'); // Remove when going to production

require_once('submission_form.php'); // Requires Form class File
require_once('submission_form_functions.php'); // Require functions file for submission form

$cmid = required_param('cmid', PARAM_INT);            // Course Module ID.
$id = optional_param('id', 0, PARAM_INT);           // Gradeimporter id.
$subid = optional_param('subid', -1, PARAM_INT);       // Submission id.
// $update = optional_param('update', 0, PARAM_INT);      // If 1 the submission is beign updated.

// Checks if everything is correct
// If any of the queries fail, throw error because of MUST_EXIST clause
$cm = get_coursemodule_from_id('gradeimporter', $cmid, 0, false, MUST_EXIST);
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
$gradeimporter = $DB->get_record('gradeimporter', array('id' => $cm->instance), '*', MUST_EXIST);


// Gets context for File API
$context = context_module::instance($cm->id);

// Sets URL
$url = new moodle_url('/mod/gradeimporter/forms/submission/submission.php', array('cmid' => $cm->id));
if (!empty($id)) {
    $url->param('id', $id);
}
$PAGE->set_url($url);

// Requires capabilities
require_login($course, false, $cm);
require_capability('mod/gradeimporter:edit', $context);

// Prepare data for submission form

if (!isset($entry)) {
    // If its creating new submission
    $entry = new stdClass();
    $entry->id = null;
}

// Set parameters to sendo to the form
$entry->cmid = $cm->id;
$maxbytes = $course->maxbytes;

// Prepare file manager
$filemanageroptions = array('subdirs' => 0,
                                    'maxbytes' => $maxbytes,
                                    'areamaxbytes' => 10485760,
                                    'maxfiles' => 1,
                                    'accepted_types' => array('.csv', '.zip')
                                );

$entry = file_prepare_standard_filemanager($entry, 'submissionfiles', $filemanageroptions, $context,
                                                'mod_gradeimporter', 'submissionfiles', $entry->id);

// Create new mform to show to the user
$mform = new mod_gradeimporter_submission_form(null, array('submission' => $entry,
                                                            'filemanageroptions' => $filemanageroptions,
                                                            'gradeimporterid' => $gradeimporter->id,
                                                            'cmid' => $cm->id
                                                        )
                                                );

if ($mform->is_cancelled()) {
    // Handle form cancel operation, if cancel button is present on form
    redirect("view.php?id=$cm->id&edit=1");
} else if ($formdata = $mform->get_data()) {

    // reset_submissions($context->id); // Remove when going to production

    $entry = create_submission($formdata, $gradeimporter->id, $USER->id);

    // Gets file manager content
    $entry = file_postupdate_standard_filemanager($entry, 'submissionfiles',
                                            $filemanageroptions, $context, 'mod_gradeimporter',
                                            'submissionfiles', $entry->id);

    store_files($context, $cm, $entry);
    // When complete redirect to view.php
    // uncomment later
    redirect("view.php?id=$cm->id&edit=1");
    // In this case you process validated data. $mform->get_data() returns data posted in form.
} else {
    // This branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
    // ...or on the first display of the form.
    if ($subid != -1) {
        // If its updating an existing submission
        // Get data from db and insert into form
        $subdata = $DB->get_record('gradeimporter_submission', array('id' => $subid));
        $subdata->description = array('text' => $subdata->description,
                                        'format' => $subdata->descriptionformat
                                    );
        $mform->set_data($subdata);
    }

    $PAGE->set_title($gradeimporter->name);
    $PAGE->set_heading($course->fullname);
    echo $OUTPUT->header();
    echo $OUTPUT->heading(format_string($gradeimporter->name), 2);

    $mform->display();

    echo $OUTPUT->footer();
}