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

use local_kid\local\stage_repository;

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

class stages_admin_page implements \renderable, \templatable {

    protected int $promotionid;

    public function __construct(int $promotionid) {
        $this->promotionid = $promotionid;
    }

    public function export_for_template(\renderer_base $output): array {
        $stages = stage_repository::get_for_promotion($this->promotionid);

        $rows = [];
        foreach ($stages as $stage) {
            $periode = trim(
                ($stage->datedebut ? userdate($stage->datedebut, get_string('strftimedatefullshort')) : '?')
                . ' – ' .
                ($stage->datefin ? userdate($stage->datefin, get_string('strftimedatefullshort')) : '?')
            );
            $rows[] = [
                'id' => (int) $stage->id,
                'libelle' => format_string($stage->libelle),
                'periode' => ($stage->datedebut || $stage->datefin) ? $periode : '',
                'scopelabel' => $stage->competencyscope === 'all'
                    ? get_string('stage_competencyscope_all', 'local_kid')
                    : get_string('stage_competencyscope_custom', 'local_kid'),
                'statuslabel' => $stage->active ? get_string('promotion_status_active', 'local_kid') : get_string('promotion_status_inactive', 'local_kid'),
                'statusclass' => $stage->active ? 'fr-badge fr-badge--success' : 'fr-badge',
                'editurl' => (new \moodle_url('/local/kid/pages/stage_edit.php', ['id' => $stage->id, 'promotionid' => $this->promotionid]))->out(false),
                'toggleurl' => (new \moodle_url('/local/kid/pages/stage_action.php',
                    ['id' => $stage->id, 'promotionid' => $this->promotionid, 'action' => 'toggle', 'sesskey' => sesskey()]))->out(false),
                'deleteurl' => (new \moodle_url('/local/kid/pages/stage_action.php',
                    ['id' => $stage->id, 'promotionid' => $this->promotionid, 'action' => 'delete']))->out(false),
                'openurl' => (new \moodle_url('/local/kid/pages/stages.php', ['promotionid' => $this->promotionid, 'stageid' => $stage->id]))->out(false),
            ];
        }

        return [
            'promotionid' => $this->promotionid,
            'addurl' => (new \moodle_url('/local/kid/pages/stage_edit.php', ['promotionid' => $this->promotionid]))->out(false),
            'hasstages' => !empty($rows),
            'stages' => $rows,
            'sesskey' => sesskey(),
        ];
    }
}
