<?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\task;

require_once $CFG->dirroot . '/vendor/autoload.php';
require_once $CFG->dirroot . '/vendor/autoload.php';
use Smalot\PdfParser\Parser;
use PhpOffice\PhpWord\IOFactory;

class send_resources extends \core\task\scheduled_task {

    public function get_name() {
        return get_string('send_resources_task', 'local_gamibot_manager');
    }

    public function execute() {
        global $DB;

        $sql = "SELECT cm.id, cm.course
                FROM {course_modules} cm
                JOIN {modules} m ON m.id = cm.module
                WHERE m.name = :modname";
        $params = ['modname' => 'resource'];
        $cms = $DB->get_records_sql($sql, $params);

        mtrace("Number of courses found: " . count($cms));

        $interval = 30 * 60;
        $apikey = 'sk-cYROebXhOFZBAB324dAgsDhhg0I92wjzQiX6QihBPPM';
        $url = 'https://langflow.hub.inov-norte.ipp.pt/api/v1/run/3cc8128b-0d07-4253-bef6-246e53216d1f';

        $responses = [];
        $parser = new Parser();

        foreach ($cms as $cm) {
            $context = \context_module::instance($cm->id);
            $fs = get_file_storage();
            $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'filename', true);

            mtrace("Number of files found: " . count($files));

            foreach ($files as $file) {
                if ($file->is_directory()) {
                    continue;
                }

                $timemodified = $file->get_timemodified();
                if ($timemodified < (time() - $interval)) {
                    continue;
                }

                $filename = $file->get_filename();
                $content = $file->get_content();
                
                $tempfile = tempnam(sys_get_temp_dir(), 'moodle_pdf_');
                file_put_contents($tempfile, $content);

                try {
                    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

                    $text = '';

                    if ($extension === 'pdf') {
                        $pdf = $parser->parseFile($tempfile);
                        $text = $pdf->getText();
                    } elseif ($extension === 'docx') {
                        $phpWord = IOFactory::load($tempfile, 'Word2007');
                        foreach ($phpWord->getSections() as $section) {
                            foreach ($section->getElements() as $element) {
                                if (method_exists($element, 'getText')) {
                                    $text .= $element->getText() . "\n";
                                }
                            }
                        }
                    } else {
                        unlink($tempfile);
                        continue;
                    }
                    
                } catch (\Exception $e) {
                    unlink($tempfile);
                    continue;
                }

                unlink($tempfile);

                $input_value = "Ficheiro: $filename\nConteúdo:\n$text";

                $payload = json_encode([
                    'input_value' => $input_value,
                    'input_type' => 'any',
                    'output_type' => 'text'
                ]);

                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/json',
                    'x-api-key: ' . $apikey
                ]);

                $response = curl_exec($ch);
                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
                $header = substr($response, 0, $header_size);
                $body = substr($response, $header_size);
                curl_close($ch);

                if ($response && $httpcode >= 200 && $httpcode < 300) {
                    $responses[] = json_decode($response, true);
                    mtrace("Resource sent succesfully: $filename");
                } else {
                    mtrace("Error sending resource: $filename - HTTP code: $httpcode");
                }
            }
        }

        return $responses;
    }
}*/