<?php

if ($user->has_authority(1)) {
    $trainingAssocArray = $sql->assoc_array("
        SELECT
            tr_id id,
            substring(tr_date,1,16) 'date',
            trt_name 'name',
            tr_duration 'duration',
            GROUP_CONCAT(DISTINCT uc1.ua_name) 'coaches',
            GROUP_CONCAT(DISTINCT uc2.ua_name) 'helpers',
            COUNT(DISTINCT pr_id) 'count'
        FROM
            training
                JOIN
            training_type ON trt_id = tr_training_type_trt_id
                JOIN
            training_coach tc1 ON tc1.trc_training_tr_id = tr_id AND tc1.trc_helper = 0
                LEFT JOIN
            training_coach tc2 ON tc2.trc_training_tr_id = tr_id AND tc2.trc_helper = 1
                JOIN
            user_coach uc1 ON uc1.ua_id = tc1.trc_coach_uc_id
                LEFT JOIN
            user_coach uc2 ON uc2.ua_id = tc2.trc_coach_uc_id
                JOIN
            presence ON pr_training_tr_id = tr_id
        WHERE
            tr_deleted = 0
        GROUP BY tr_id
        ORDER BY tr_date ASC;
    ");
}
else {
    $trainingAssocArray = $sql->assoc_array("
        SELECT
            tr_id id,
            substring(tr_date,1,16) 'date',
            trt_name 'name',
            tr_duration 'duration',
            GROUP_CONCAT(DISTINCT ua_name) 'coaches',
            GROUP_CONCAT(DISTINCT uc2.ua_name) 'helpers',
            COUNT(DISTINCT pr_id) 'count'
        FROM
            training
                JOIN
            training_type ON trt_id = tr_training_type_trt_id
                JOIN
            training_coach tc1 ON tc1.trc_training_tr_id = tr_id AND tc1.trc_helper = 0
                LEFT JOIN
            training_coach tc2 ON tc2.trc_training_tr_id = tr_id AND tc2.trc_helper = 1
                JOIN
            user_coach uc1 ON uc1.ua_id = tc1.trc_coach_uc_id
                LEFT JOIN
            user_coach uc2 ON uc2.ua_id = tc2.trc_coach_uc_id
                JOIN
            presence ON pr_training_tr_id = tr_id
        WHERE
            tr_deleted = 0 AND trc2.trc_coach_uc_id = {$user->get_ua_id()}
        GROUP BY tr_id
        ORDER BY tr_date ASC;
    ");
}

$smarty->assign("trainings", $trainingAssocArray);
$smarty->display("training_export_list.tpl");
