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

/**
 * Tâche planifiée (section 26 du cahier des charges) : synchronise le
 * feedback Moodle des évaluations de type "Devoir Moodle", en réutilisant
 * exactement le même chemin de code que le bouton de synchronisation
 * manuelle (`eval_repository::sync_feedback()`) — ne touche jamais
 * `local_kid_eval_result`, ni les niveaux/commentaires saisis dans le
 * plugin.
 *
 * @package local_kid
 */

namespace local_kid\task;

use local_kid\local\eval_repository;

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

class sync_moodle_feedback_task extends \core\task\scheduled_task {

    public function get_name() {
        return get_string('task_sync_moodle_feedback', 'local_kid');
    }

    public function execute() {
        global $DB;

        $lookback = (int) get_config('local_kid', 'tasklookback');
        $cutoff = $lookback > 0 ? (time() - $lookback) : 0;

        $sql = "SELECT ee.id, ee.lastsyncat
                  FROM {local_kid_eval_entry} ee
                  JOIN {local_kid_eval} e ON e.id = ee.evalid
                 WHERE e.sourcetype = 'moodle_devoir' AND e.active = 1";
        $entries = $DB->get_records_sql($sql);

        $synced = 0;
        $skipped = 0;
        foreach ($entries as $entry) {
            if ($cutoff && $entry->lastsyncat && $entry->lastsyncat > $cutoff) {
                $skipped++;
                continue;
            }
            eval_repository::sync_feedback((int) $entry->id);
            $synced++;
        }

        mtrace("local_kid: synced feedback for $synced entrie(s), skipped $skipped already-recent entrie(s).");
    }
}
