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

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use local_kid\local\access_helper;
use local_kid\local\bulk_action_service;

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

/**
 * AJAX backing for the grouped actions bar's "Publier"/"Masquer" (the
 * write half — downloads go through pages/bulk_fiche_zip.php instead,
 * since a ZIP response can't travel through core/ajax). Re-verifies the
 * capability for the target screen's domain and the eligibility of every
 * selected studentid server-side — the browser's checkbox selection is
 * only ever treated as a list of candidate ids, never trusted directly
 * (see {@see bulk_action_service::apply()}).
 */
class bulk_publish_action extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'screen' => new external_value(PARAM_ALPHA, 'evaluations, stages or capp'),
            'itemid' => new external_value(PARAM_INT, 'evalid / stageid / sessionid'),
            'studentids' => new external_multiple_structure(
                new external_value(PARAM_INT, 'local_kid_student.id')
            ),
            'action' => new external_value(PARAM_ALPHA, 'publish or hide'),
        ]);
    }

    public static function execute(string $screen, int $itemid, array $studentids, string $action): array {
        global $USER;

        [
            'screen' => $screen, 'itemid' => $itemid, 'studentids' => $studentids, 'action' => $action,
        ] = self::validate_parameters(self::execute_parameters(), [
            'screen' => $screen, 'itemid' => $itemid, 'studentids' => $studentids, 'action' => $action,
        ]);

        $context = \context_system::instance();
        self::validate_context($context);

        if (!bulk_action_service::is_valid_screen($screen) || !in_array($action, ['publish', 'hide'], true)) {
            throw new \moodle_exception('invalidparameter', 'error');
        }
        if (!bulk_action_service::get_item($screen, $itemid)) {
            throw new \moodle_exception('invalidrecord', 'error');
        }

        access_helper::require_capability_or_teacher(bulk_action_service::publish_capability($screen), $context);

        $studentids = array_values(array_unique(array_map('intval', $studentids)));
        if (empty($studentids)) {
            throw new \moodle_exception('invalidparameter', 'error');
        }

        $result = bulk_action_service::apply($screen, $itemid, $studentids, $action, (int) $USER->id);

        $entries = [];
        foreach ($result['changed'] as $studentid => $published) {
            $entries[] = ['studentid' => $studentid, 'published' => $published];
        }

        return [
            'donecount' => $result['donecount'],
            'donenames' => $result['donenames'],
            'ignoredcount' => $result['ignoredcount'],
            'ignorednames' => $result['ignorednames'],
            'entries' => $entries,
        ];
    }

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'donecount' => new external_value(PARAM_INT, 'Entries actually published/hidden'),
            'donenames' => new external_multiple_structure(new external_value(PARAM_TEXT, 'Student full name')),
            'ignoredcount' => new external_value(PARAM_INT, 'Selected entries skipped as ineligible'),
            'ignorednames' => new external_multiple_structure(new external_value(PARAM_TEXT, 'Student full name')),
            'entries' => new external_multiple_structure(new external_single_structure([
                'studentid' => new external_value(PARAM_INT, 'local_kid_student.id'),
                'published' => new external_value(PARAM_BOOL, 'New published state'),
            ])),
        ]);
    }
}
