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

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
  $viewurl = new moodle_url('/mod/gradeimporter/view.php', ['id' => $cm->id, 'edit' => 1]);
  redirect($viewurl);
} else if ($formdata = $mform->get_data()) {

  validate_formdata($formdata);
  // If validate didnt throw error then everything is fine
  $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
  $viewurl = new moodle_url('/mod/gradeimporter/view.php', ['id' => $cm->id, 'edit' => 1]);
  redirect($viewurl);

} 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->intro = array('text' => $subdata->intro,
                    'format' => $subdata->introformat
                  );
    $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();
}