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

namespace local_gamibot_manager\local;

use core\event\user_deleted;
use core\event\course_module_created;
use core\event\course_module_deleted;
use core\event\course_module_updated;

/**
 * Observer functions for local_gamibot_manager.
 *
 * @package   local_gamibot_manager
 * @copyright 2025 Centro de Inovação Pedagógica P. Porto
 * @author    José C. Paiva
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class observers {

    /**
     * Observer for user_deleted event.
     *
     * This will wipe the userinfo record and the userusage records for the user.
     *
     * @param user_deleted $event The user deleted event
     */
    public static function user_deleted(user_deleted $event): void
    {
        $datawiper = new data_wiper();
        $datawiper->delete_userinfo($event->objectid);
        $datawiper->delete_userusage($event->objectid);
        $datawiper->anonymize_request_log_for_user($event->objectid, true);
    }

    public static function course_module_created(course_module_created $event): void
    {
        self::process_file_upload_event($event);
    }

    public static function course_module_updated(course_module_updated $event): void
    {
        self::process_file_upload_event($event);
    }

    protected static function process_file_upload_event($event): void
    {
        global $DB, $CFG;

        $modname = $event->other['modulename'] ?? '';
        if (!in_array($modname, ['resource', 'folder'])) {
            return;
        }

        $cmid      = $event->objectid;
        $courseid  = $event->courseid;
        $contextid = $event->contextid;

        $cm = get_coursemodule_from_id($modname, $cmid, 0, false, MUST_EXIST);

        $modinfo = get_fast_modinfo($courseid);

        $cminfo = $modinfo->get_cm($cmid);

        $section = $cminfo->get_section_info();

        $record = $DB->get_record($modname, ['id' => $cm->instance], '*', IGNORE_MISSING);
        if (!$record) {
            return;
        }

        $filearea = 'content';
        $baseurl = $CFG->wwwroot . "/webservice/pluginfile.php/{$contextid}/mod_{$modname}/{$filearea}/0";

        $fs = get_file_storage();
        $files = $fs->get_area_files($contextid, "mod_{$modname}", $filearea, 0, '', false);
        if (empty($files)) {
            return;
        }

        $endpoint = get_config('local_gamibot_manager', 'ingestion_endpoint');
        $secret   = get_config('local_gamibot_manager', 'webhook_secret');

        if (empty($endpoint)) {
            return;
        }

        foreach ($files as $file) {
            $filename = $file->get_filename();
            if ($filename === '.') {
                continue;
            }

            $filepath = $file->get_filepath();
            $fileurl  = $baseurl . $filepath . $filename;

            $payload = [
                'event'        => 'file_uploaded',
                'secret'       => $secret,
                'course_id'    => $courseid,
                'section_id'   => $section->id ?? 0,
                'section_name' => $section->name ?? '',
                'module_id'    => $cmid,
                'module_name'  => $cm->name,
                'moodle_url'   => $CFG->wwwroot,
                'file_url'     => $fileurl,
                'filename'     => $filename,
                'mimetype'     => $file->get_mimetype(),
                'filesize'     => $file->get_filesize(),
            ];

            self::send_webhook($endpoint, $payload);
        }
    }


    public static function course_module_deleted(course_module_deleted $event)
    {
        global $CFG;

        // 1. Only care about resources (files) and folders.
        $modname = $event->other['modulename'] ?? '';
        if (!in_array($modname, ['resource', 'folder'])) {
            return;
        }

        $endpoint = get_config('local_gamibot_manager', 'ingestion_endpoint'); // LangFlow webhook URL
        $secret   = get_config('local_gamibot_manager', 'webhook_secret'); // Shared secret

        if (empty($endpoint)) {
            return;
        }

        // 2. Build Payload
        $payload = [
            'event'     => 'file_deleted',
            'secret'    => $secret,
            'course_id' => $event->courseid,
            'module_id' => $event->objectid, // This is the cmid
            'moodle_url'   => $CFG->wwwroot,
        ];

        self::send_webhook($endpoint, $payload);
    }

    protected static function send_webhook(string $endpoint, array $payload): void
    {
        $curl = new \curl();
        $options = [
            'CURLOPT_HTTPHEADER'     => ['Content-Type: application/json'],
            'CURLOPT_RETURNTRANSFER' => true,
        ];
        $curl->post($endpoint, json_encode($payload), $options);
    }
}
