<?php
// This file is part of mod_datalynx for Moodle - http://moodle.org/
//
// It 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.
//
// It 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/>.

namespace mod_datalynx\form;
use stdClass;

/**
 *
 * Contains class mod_customfilter_form used at the BACKEND ("Manage") to create or edit a
 * customfilter
 *
 * @package mod_datalynx
 * @copyright 2016 Thomas Niedermaier
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class datalynx_customfilter_backend_form extends datalynx_customfilter_base_form {
    /**
     * Define form elements.
     *
     * @return void
     */
    public function definition() {
        if ($id = $this->customfilter->id) {
            $customfilter = $this->get_customfilter($id);
        } else {
            $customfilter = new stdClass();
            $customfilter->name = "";
            $customfilter->description = "";
            $customfilter->fulltextsearch = false;
            $customfilter->visible = true;
            $customfilter->timecreated = false;
            $customfilter->timecreatedsortable = false;
            $customfilter->timemodified = false;
            $customfilter->timemodifiedsortable = false;
            $customfilter->authorsearch = false;
            $customfilter->approve = false;
            $customfilter->status = false;
            $customfilter->fieldlist = "";
        }

        $name = empty($customfilter->name) ? get_string('filternew', 'datalynx') : $customfilter->name;

        $mform = &$this->_form;

        $mform->addElement('text', 'name', get_string('name'));
        $mform->addElement('text', 'description', get_string('description'), ['size' => '64']);
        $mform->setType('name', PARAM_TEXT);
        $mform->setType('description', PARAM_TEXT);
        $mform->setDefault('name', $name);
        $mform->setDefault('description', $customfilter->description);

        $mform->addElement('advcheckbox', 'visible', get_string('visible'));
        $mform->setType('visible', PARAM_INT);
        $mform->setDefault('visible', $customfilter->visible);

        $mform->addElement('advcheckbox', 'fulltextsearch', get_string('fulltextsearch', 'datalynx'));
        $mform->setType('fulltextsearch', PARAM_INT);
        $mform->setDefault('fulltextsearch', $customfilter->fulltextsearch);

        $grp = [];
        $attr = ['size' => 1];
        $grp[] = $mform->createElement(
            'advcheckbox',
            'timecreated',
            get_string('timecreated', 'datalynx'),
            null,
            $attr
        );
        $grp[] = $mform->createElement(
            'advcheckbox',
            'timecreatedsortable',
            null,
            get_string('sortable', 'datalynx'),
            $attr,
            [0, 1]
        );
        $mform->addGroup($grp, '', null, ' ', false);
        $mform->setType('timecreated', PARAM_INT);
        $mform->setDefault('timecreated', $customfilter->timecreated);
        $mform->setType('timecreatedsortable', PARAM_INT);
        $mform->setDefault('timecreatedsortable', $customfilter->timecreatedsortable);

        $grp = [];
        $grp[] = $mform->createElement(
            'advcheckbox',
            'timemodified',
            get_string('timemodified', 'datalynx'),
            null,
            $attr
        );
        $grp[] = $mform->createElement(
            'advcheckbox',
            'timemodifiedsortable',
            null,
            get_string('sortable', 'datalynx'),
            $attr,
            [0, 1]
        );
        $mform->addGroup($grp, '', null, ' ', false);
        $mform->setType('timemodified', PARAM_INT);
        $mform->setDefault('timemodified', $customfilter->timemodified);
        $mform->setType('timemodifiedsortable', PARAM_INT);
        $mform->setDefault('timemodifiedsortable', $customfilter->timemodifiedsortable);

        $mform->addElement('advcheckbox', 'authorsearch', get_string('authorsearch', 'datalynx'), null, $attr);
        $mform->setType('authorsearch', PARAM_INT);
        $mform->setDefault('authorsearch', $customfilter->authorsearch);

        $mform->addElement('advcheckbox', 'approve', get_string('approved', 'datalynx'), null, $attr);
        $mform->setType('approve', PARAM_INT);
        $mform->setDefault('approve', $customfilter->approve);

        $mform->addElement('advcheckbox', 'status', get_string('status', 'datalynx'), null, $attr);
        $mform->setType('status', PARAM_INT);
        $mform->setDefault('status', $customfilter->status);

        $mform->addElement('header', 'fieldlistheader', get_string('userfields', 'datalynx'));

        $fieldlist = [];
        if ($customfilter->fieldlist) {
            $fieldlist = json_decode($customfilter->fieldlist);
        }
        $fields = $this->get_possible_customfilter_fields($this->dl);
        foreach ($fields as $field) {
            $formfieldname = 'fieldlist[' . $field->field->id . '][name]';
            $formfieldsortablename = 'fieldlist[' . $field->field->id . '][sortable]';
            $grp = [];
            $grp[] = $mform->createElement(
                'advcheckbox',
                $formfieldname,
                $field->field->name . ' (' . $field->type . ')',
                '',
                '',
                $field->field->name
            );
            $grp[] = $mform->createElement(
                'advcheckbox',
                $formfieldsortablename,
                '',
                get_string('sortable', 'datalynx'),
                '',
                [0, 1]
            );
            $mform->addGroup($grp, '', null, ' ', false);
            $mform->setType($formfieldname, PARAM_TEXT);
            $mform->setType($formfieldsortablename, PARAM_INT);
            foreach ($fieldlist as $fid => $listfield) {
                if ($field->field->id == $fid) {
                    $mform->setDefault($formfieldname, $field->field->name);
                    if ($listfield->sortable) {
                        $mform->setDefault($formfieldsortablename, 1);
                    }
                    break;
                }
            }
        }

        $this->add_action_buttons(true, get_string('savechanges'));
    }

    /**
     * Get all fields that can be used in a customfilter.
     *
     * @param mixed $dl The datalynx instance.
     * @return array
     */
    protected function get_possible_customfilter_fields($dl): array {
        global $DB;

        $fields = [];
        $customfilterfieldtypes = $dl->get_customfilterfieldtypes();
        $fieldsdb = $DB->get_records('datalynx_fields', ['dataid' => $dl->id()], 'name asc');
        foreach ($fieldsdb as $fieldid => $field) {
            if (in_array($field->type, $customfilterfieldtypes)) {
                $fields[$fieldid] = $dl->get_field($field);
            }
        }

        return $fields;
    }

    /**
     * Get a customfilter record from the database by id.
     *
     * @param int $filterid The customfilter record ID.
     * @return mixed
     */
    protected function get_customfilter($filterid) {
        global $DB;
        return $DB->get_record('datalynx_customfilters', ['id' => $filterid]);
    }

    /**
     * Get submitted form data and encode field list as JSON.
     *
     * @return object
     */
    public function get_data() {
        if ($data = parent::get_data()) {
            if (!empty($data->fieldlist)) {
                $fieldlistarray = [];
                foreach ($data->fieldlist as $fieldid => $field) {
                    if ($field['name']) {
                        $fieldlistarray[$fieldid]['name'] = $field['name'];
                        $fieldlistarray[$fieldid]['sortable'] = $field['sortable'];
                    }
                }
                $data->fieldlist = json_encode($fieldlistarray);
            } else {
                $data->fieldlist = null;
            }
        }
        return $data;
    }

    /**
     * Render the form as HTML.
     *
     * @return string
     */
    public function html() {
        return $this->_form->toHtml();
    }

    /**
     * Validate the submitted form data.
     *
     * @param array $data
     * @param array $files
     * @return array
     * @throws coding_exception
     */
    public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        $dl = $this->dl;
        if (empty($data['name']) || $dl->name_exists('customfilters', $data['name'], $this->customfilter->id)) {
            $errors['name'] = get_string(
                'invalidname',
                'datalynx',
                get_string('filter', 'datalynx')
            );
        }

        return $errors;
    }
}
