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

/**
 * Simulatore contabilità
 *
 * @package    mod_mtcontabilita
 * @copyright  2026 Mediatouch 2000 Srl <https://www.mediatouch.it>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @author     Marco Cappuccio <m.cappuccio@mediatouch.it>
 */

require_once('../../../config.php');
require_once('locallib.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/lib.php');
require_once("{$CFG->dirroot}/mod/mtcontabilita/locallib.php"); // PATCH.

$id = required_param('id', PARAM_INT);

$sort    = optional_param('sort', 'name', PARAM_ALPHANUMEXT);
$dir     = optional_param('dir', 'ASC', PARAM_ALPHA);

$course = get_course($id);
require_course_login($course, false);
$context = context_course::instance($course->id);
if (!has_capability('mod/mtcontabilita:addinstance', $context)) {
    throw new \moodle_exception('nopermissions', 'error', '', get_string('nopermissions', 'mod_mtcontabilita'));
}
/**
 * Normalize Moodle/current account language codes to the values used by the account import templates.
 *
 * @param string|null $lang
 * @return string
 */
function mtcontabilita_manage_csv_normalize_lang($lang) {
    $lang = strtolower(trim((string)$lang));
    if (strpos($lang, 'en') === 0) {
        return 'en';
    }
    if (strpos($lang, 'it') === 0) {
        return 'it';
    }
    return $lang;
}

/**
 * Choose the template layout language for this export.
 *
 * @param array $records
 * @return string
 */
function mtcontabilita_manage_csv_export_lang(array $records) {
    $langs = [];
    foreach ($records as $record) {
        $lang = mtcontabilita_manage_csv_normalize_lang($record->lang ?? '');
        if ($lang !== '') {
            $langs[$lang] = true;
        }
    }

    if (count($langs) === 1) {
        return array_key_first($langs);
    }

    $currentlang = mtcontabilita_manage_csv_normalize_lang(current_language());
    return ($currentlang === 'en') ? 'en' : 'it';
}

/**
 * Decide whether the civil classification column is needed.
 *
 * @param array $records
 * @param string $exportlang
 * @return bool
 */
function mtcontabilita_manage_csv_include_macroclasse(array $records, $exportlang) {
    if ($exportlang !== 'en') {
        return true;
    }

    foreach ($records as $record) {
        $lang = mtcontabilita_manage_csv_normalize_lang($record->lang ?? '');
        if ($lang === 'it') {
            return true;
        }
    }

    return false;
}

/**
 * Return CSV column headers aligned with the import templates.
 *
 * @param string $exportlang
 * @param bool $includemacroclasse
 * @return array
 */
function mtcontabilita_manage_csv_headers($exportlang, $includemacroclasse) {
    if ($exportlang === 'en') {
        $headers = ['description', 'scheme', 'typology'];
        if ($includemacroclasse) {
            $headers[] = 'grouping';
        }
        $headers[] = 'lang';
        return $headers;
    }

    $headers = ['nome conto', 'schema', 'tipologia'];
    if ($includemacroclasse) {
        $headers[] = 'classif. civ.';
    }
    $headers[] = 'lang';
    return $headers;
}

/**
 * Convert the stored scheme to the value expected by the import template.
 *
 * @param string|null $scheme
 * @param string $lang
 * @return string
 */
function mtcontabilita_manage_csv_scheme($scheme, $lang) {
    $scheme = strtolower(trim((string)$scheme));
    if ($lang === 'en') {
        $map = ['sp' => 'BS', 'ce' => 'IS'];
        return $map[$scheme] ?? strtoupper($scheme);
    }

    $map = ['sp' => 'SP', 'ce' => 'CE'];
    return $map[$scheme] ?? strtoupper($scheme);
}

/**
 * Convert the stored typology id to the value expected by the import template.
 *
 * @param int|string|null $nature
 * @param string $lang
 * @return string
 */
function mtcontabilita_manage_csv_nature($nature, $lang) {
    $nature = (int)$nature;
    $values = [
        'en' => [
            1 => 'expenses',
            2 => 'revenues',
            3 => 'assets',
            4 => 'liabilities',
            5 => 'equity',
        ],
        'it' => [
            1 => 'costo di esercizio',
            2 => 'ricavo di esercizio',
            3 => 'attivo',
            4 => 'passivita',
            5 => 'patrimonio netto',
        ],
    ];

    return $values[$lang][$nature] ?? '';
}
$ufiltering = new mtmanage_filtering(null, $CFG->wwwroot."/mod/mtcontabilita/manage/?id=".$id);
list($extrasql, $params) = $ufiltering->get_sql_filter();

$users = mtcontabilita_manage::get_users_listing($id, $sort, $dir, 0, 0, '', '', '', $extrasql, $params, $context);
$exportlang = mtcontabilita_manage_csv_export_lang($users);
$includemacroclasse = mtcontabilita_manage_csv_include_macroclasse($users, $exportlang);

$namefile = "list_".time();
header('Content-Type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=\"{$namefile}.csv\"");

$output = fopen('php://output', 'w');
fwrite($output, "\xEF\xBB\xBF");

// Column headers.
fputcsv($output, mtcontabilita_manage_csv_headers($exportlang, $includemacroclasse), ';');

// Data rows.
foreach ($users as $user) {
    $rowlang = mtcontabilita_manage_csv_normalize_lang($user->lang ?? $exportlang);
    if ($rowlang !== 'en' && $rowlang !== 'it') {
        $rowlang = $exportlang;
    }

    $row = [
        $user->name,
        mtcontabilita_manage_csv_scheme($user->scheme ?? '', $rowlang),
        mtcontabilita_manage_csv_nature($user->nature ?? 0, $rowlang),
    ];

    if ($includemacroclasse) {
        $row[] = ($rowlang === 'it') ? ($user->macroclasse ?? '') : '';
    }

    $row[] = $rowlang;
    fputcsv($output, $row, ';');
}
fclose($output);
exit;
