<?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\annuaire_repository;
use local_kid\local\promotion_repository;

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

class annuaire_page implements \renderable, \templatable {

    private const PERPAGE = 30;

    private array $filters;
    private string $sort;
    private string $dir;
    private int $page;

    /**
     * @param array $filters raw GET values, already PARAM_*-cleaned by the controller:
     *   sifirst, silast (string, 'all' = unfiltered), studentquery (string),
     *   promotionid (int, 0 = all)
     */
    public function __construct(array $filters, string $sort, string $dir, int $page) {
        $this->filters = $filters;
        $this->sort = $sort;
        $this->dir = $dir;
        $this->page = max(0, $page);
    }

    public function export_for_template(\renderer_base $output): array {
        $result = annuaire_repository::search($this->filters, $this->sort, $this->dir, $this->page, self::PERPAGE);

        $rows = array_map([$this, 'export_row'], $result['rows']);

        $baseurl = new \moodle_url('/local/kid/pages/annuaire.php', array_filter([
            'sifirst' => $this->filters['sifirst'] ?? '',
            'silast' => $this->filters['silast'] ?? '',
            'studentquery' => $this->filters['studentquery'] ?? '',
            'promotionid' => $this->filters['promotionid'] ?? 0,
            'sort' => $this->sort,
            'dir' => $this->dir,
        ]));

        $firstinitialsurl = new \moodle_url($baseurl, ['sifirst' => '']);
        $lastinitialsurl = new \moodle_url($baseurl, ['silast' => '']);

        return [
            'filterform' => [
                'action' => (new \moodle_url('/local/kid/pages/annuaire.php'))->out(false),
                'promotionoptions' => $this->build_promotion_options(),
                'studentquery' => $this->filters['studentquery'] ?? '',
                'sort' => $this->sort,
                'dir' => $this->dir,
                'sifirst' => $this->filters['sifirst'] ?? 'all',
                'silast' => $this->filters['silast'] ?? 'all',
            ],
            'firstinitialbar' => $output->initials_bar(
                $this->filters['sifirst'] ?? 'all', 'firstinitial',
                get_string('firstname'), 'sifirst', $firstinitialsurl
            ),
            'lastinitialbar' => $output->initials_bar(
                $this->filters['silast'] ?? 'all', 'lastinitial',
                get_string('lastname'), 'silast', $lastinitialsurl
            ),
            'sortheaders' => $this->build_sort_headers($baseurl),
            'hasrows' => !empty($rows),
            'message' => get_string('annuaire_empty', 'local_kid'),
            'rows' => $rows,
            'pagingbar' => $output->render(new \paging_bar($result['total'], $this->page, self::PERPAGE, $baseurl, 'page')),
            'total' => $result['total'],
        ];
    }

    private function export_row(\stdClass $row): array {
        return [
            'id' => (int) $row->studentid,
            'firstname' => $row->firstname,
            'lastname' => $row->lastname,
            'promotionname' => format_string($row->promotionname),
            'studenturl' => (new \moodle_url('/local/kid/pages/student.php', ['studentid' => (int) $row->studentid]))->out(false),
            'promotionurl' => (new \moodle_url('/local/kid/pages/dashboard.php', [
                'promotionid' => (int) $row->promotionid, 'tab' => 'apercu',
            ]))->out(false),
        ];
    }

    private function build_promotion_options(): array {
        $selected = (int) ($this->filters['promotionid'] ?? 0);
        $options = [];
        foreach (promotion_repository::get_all() as $promotion) {
            $options[] = [
                'id' => (int) $promotion->id,
                'label' => format_string($promotion->name),
                'selected' => (int) $promotion->id === $selected,
            ];
        }
        return $options;
    }

    private function build_sort_headers(\moodle_url $baseurl): array {
        $columns = [
            'lastname' => 'annuaire_col_lastname',
            'firstname' => 'annuaire_col_firstname',
            'promotionname' => 'annuaire_col_promotion',
        ];

        $headers = [];
        foreach ($columns as $field => $stringid) {
            $isactive = $this->sort === $field;
            $nextdir = $isactive && $this->dir === 'ASC' ? 'DESC' : 'ASC';
            $url = new \moodle_url($baseurl, ['sort' => $field, 'dir' => $nextdir]);
            $headers[$field] = [
                'label' => get_string($stringid, 'local_kid'),
                'url' => $url->out(false),
                'indicator' => $isactive ? ($this->dir === 'ASC' ? '▲' : '▼') : '',
            ];
        }
        return $headers;
    }
}
