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

namespace local_hshexport\local\helpers;

use core\context;

/**
 * Plugin version and other meta-data are defined here.
 *
 * @package     local_hshexport
 * @copyright   2024 Elke Kreim elke.kreim@hs-hannover.de
 * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

class download {
    public static function get_evaluation_filename(int $courseid = 0, string $course_code = null): string
    {
        global $DB;

        define('FILENAME_PREFIX', 'TN_');

        $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
        $context = context\course::instance($course->id, MUST_EXIST);

        if ($context->contextlevel != CONTEXT_COURSE) {
            throw new \moodle_exception('invalidcontext');
        }

        $timestamp = download::get_file_timestamp();
        $filename = $course_code;

        // use course shortname if no course_code is given
        if ($course_code == null) {
            $filename = str_replace(',', '-', $course->shortname);
        }

        // extend filename with prefix and date
        $filename = FILENAME_PREFIX . $filename . '_' . $timestamp;

        return $filename;
    }

    public static function get_file_timestamp(): string
    {
        $now = date_create('now');
        $timestamp = ($now->format('Ymd'));

        return $timestamp;
    }

    public static function get_rows($users, $course_code = null): array
    {
        if ($course_code === null) {
            return $users;
        }

        $rows = [];

        foreach ($users as $user) {
            $row = [
                'course_code' => $course_code,
                'email' => $user->email
            ];
            array_push($rows, $row);
        }
        return $rows;
    }
}