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

/**
 * Dépôt multi-fichiers pour les documents de stage (PDF/Word/Excel), stockés
 * via l'API fichiers Moodle, itemid == local_kid_stage_entry.id.
 *
 * @package local_kid
 */

require(__DIR__ . '/../../../config.php');

use local_kid\local\access_helper;
use local_kid\local\stage_repository;

require_login();
$context = context_system::instance();
access_helper::require_capability_or_teacher('local/kid:evaluate_stage', $context);
require_sesskey();

$entryid = required_param('entryid', PARAM_INT);
$entry = stage_repository::get_entry($entryid);
if (!$entry) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$returnurl = new moodle_url('/local/kid/pages/stages.php', ['stageid' => $entry->stageid, 'studentid' => $entry->studentid]);

$allowedextensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx'];

if (empty($_FILES['files']['name'][0] ?? null)) {
    redirect($returnurl, get_string('stagedoc_error_none', 'local_kid'), null, \core\output\notification::NOTIFY_ERROR);
}

$fs = get_file_storage();
$uploaded = 0;
$rejected = [];

foreach ($_FILES['files']['name'] as $index => $originalname) {
    if ($_FILES['files']['error'][$index] !== UPLOAD_ERR_OK) {
        continue;
    }
    $extension = strtolower(pathinfo($originalname, PATHINFO_EXTENSION));
    if (!in_array($extension, $allowedextensions, true)) {
        $rejected[] = $originalname;
        continue;
    }

    $tmpname = $_FILES['files']['tmp_name'][$index];
    $filename = clean_param($originalname, PARAM_FILE);
    if ($filename === '') {
        $filename = 'document_' . time() . '.' . $extension;
    }

    // Avoid clobbering an existing file with the same name for this entry.
    $existing = $fs->file_exists($context->id, 'local_kid', 'stagedoc', $entryid, '/', $filename);
    if ($existing) {
        $filename = pathinfo($filename, PATHINFO_FILENAME) . '_' . time() . '.' . $extension;
    }

    $filerecord = [
        'contextid' => $context->id,
        'component' => 'local_kid',
        'filearea' => 'stagedoc',
        'itemid' => $entryid,
        'filepath' => '/',
        'filename' => $filename,
    ];
    $storedfile = $fs->create_file_from_pathname($filerecord, $tmpname);

    $DB->insert_record('local_kid_stage_doc', (object) [
        'entryid' => $entryid,
        'filename' => $filename,
        'filesize' => $storedfile->get_filesize(),
        'mimetype' => $storedfile->get_mimetype(),
        'pathnamehash' => $storedfile->get_pathnamehash(),
        'uploadedby' => $USER->id,
        'timecreated' => time(),
    ]);
    $uploaded++;
}

$message = get_string('stagedoc_upload_result', 'local_kid', $uploaded);
if (!empty($rejected)) {
    $message .= ' ' . get_string('stagedoc_rejected', 'local_kid', implode(', ', $rejected));
}

redirect($returnurl, $message, null,
    empty($rejected) ? \core\output\notification::NOTIFY_SUCCESS : \core\output\notification::NOTIFY_WARNING);
