<?php

if ($user->has_authority(1)) {
    $trainingAssocArray = $sql->assoc_array("
        SELECT
            tr_id id,
            substring(tr_date,1,16) 'date',
            trt_name 'name',
            GROUP_CONCAT(DISTINCT ua_name) 'coaches',
            COUNT(DISTINCT pr_id) 'count'
        FROM
            training
                JOIN
            training_type ON trt_id = tr_training_type_trt_id
                JOIN
            training_coach ON trc_training_tr_id = tr_id
                JOIN
            user_coach ON ua_id = 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',
            GROUP_CONCAT(DISTINCT ua_name) 'coaches',
            COUNT(DISTINCT pr_id) 'count'
        FROM
            training
                JOIN
            training_type ON trt_id = tr_training_type_trt_id
                JOIN
            training_coach trc1 ON trc1.trc_training_tr_id = tr_id
                JOIN
            training_coach trc2 ON trc2.trc_training_tr_id = tr_id
                JOIN
            user_coach ON ua_id = trc1.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;
    ");
}

$filename = "edzeslista.csv";
$fp = fopen('php://output', 'w');

fputcsv($fp, array_keys(reset($trainingAssocArray)), ';');
ob_end_clean();

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

foreach($trainingAssocArray as $row) {
    fputcsv($fp, $row, ';');
}
exit(1);
