<?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.

namespace local_kid\local;

defined('MOODLE_INTERNAL') || die();

/**
 * Everything touching mod_assign lives here, via the real Moodle assign API
 * (never raw SQL against mod_assign's own tables). `new \assign(...)` is the
 * historical, non-namespaced class — it is not autoloaded, so
 * mod/assign/locallib.php must be required explicitly before instantiating it.
 */
class moodle_assign_bridge {

    /**
     * Level 2 of the category → course → devoir cascade used by the
     * évaluation form (classes/form/eval_form.php) to pick a Devoir Moodle
     * without ever listing every course/assignment on the site at once.
     *
     * @return array id => fullname, the courses directly in this category
     *   (not recursive into subcategories — matches what the category level
     *   itself already lists as immediate children). Hidden courses are
     *   included only for users who can already see hidden courses in
     *   Moodle (moodle/course:viewhiddencourses on the category), so admins
     *   aren't missing courses that plain teachers rightly don't see.
     */
    public static function get_courses_for_category(int $categoryid): array {
        global $DB;

        if ($categoryid <= 0) {
            // {course}.category = 0 is the site front page's sentinel, not
            // a real course_category row — never let a stray categoryid=0
            // (our own "nothing selected" placeholder value) surface it.
            return [];
        }

        $conditions = ['category' => $categoryid];
        $catcontext = \context_coursecat::instance($categoryid, IGNORE_MISSING);
        if (!$catcontext || !has_capability('moodle/course:viewhiddencourses', $catcontext)) {
            $conditions['visible'] = 1;
        }

        $courses = $DB->get_records('course', $conditions, 'fullname ASC', 'id, fullname');
        $options = [];
        foreach ($courses as $course) {
            $options[$course->id] = format_string($course->fullname);
        }
        return $options;
    }

    /**
     * Level 3 of the cascade: every visible Devoir Moodle (mod_assign) in
     * one course.
     *
     * @return array cmid => assignment name
     */
    public static function get_assigns_for_course(int $courseid): array {
        global $DB;

        $sql = "SELECT cm.id AS cmid, a.name AS assignname
                  FROM {assign} a
                  JOIN {course_modules} cm ON cm.instance = a.id
                  JOIN {modules} m ON m.id = cm.module AND m.name = 'assign'
                 WHERE cm.course = :courseid AND cm.visible = 1
                 ORDER BY a.name";
        $rows = $DB->get_records_sql($sql, ['courseid' => $courseid]);

        $options = [];
        foreach ($rows as $row) {
            $options[$row->cmid] = format_string($row->assignname);
        }
        return $options;
    }

    /**
     * @return \stdClass|null {courseid, feedbacktext, feedbackformat, timemodified} or null if no grade/feedback yet.
     */
    public static function get_feedback(int $cmid, int $userid): ?\stdClass {
        global $CFG, $DB;
        require_once($CFG->dirroot . '/mod/assign/locallib.php');

        $cm = get_coursemodule_from_id('assign', $cmid, 0, false, IGNORE_MISSING);
        if (!$cm) {
            return null;
        }
        $course = $DB->get_record('course', ['id' => $cm->course], '*', MUST_EXIST);
        $context = \context_module::instance($cm->id);
        $assign = new \assign($context, $cm, $course);

        $grade = $assign->get_user_grade($userid, false);
        if (!$grade) {
            return null;
        }

        $plugin = $assign->get_feedback_plugin_by_type('comments');
        $feedbacktext = '';
        $feedbackformat = FORMAT_PLAIN;
        if ($plugin && $plugin->is_enabled() && $plugin->is_visible()) {
            $feedbacktext = $plugin->text_for_gradebook($grade) ?? '';
            $feedbackformat = FORMAT_HTML;
        }

        return (object) [
            'courseid' => $cm->course,
            'feedbacktext' => $feedbacktext,
            'feedbackformat' => $feedbackformat,
            'timemodified' => (int) $grade->timemodified,
        ];
    }
}
