<?php

require_once '../includes/auth.php';

require_login();

header('Content-Type: text/csv; charset=utf-8');

header('Content-Disposition: attachment; filename=Corps_Members_Report_'.date('Ymd_His').'.csv');

$output = fopen('php://output','w');

/*
|--------------------------------------------------------------------------
| CSV HEADERS
|--------------------------------------------------------------------------
*/

fputcsv($output,[

'S/N',

'State Code',

'Call-Up Number',

'Full Name',

'Gender',

'Phone',

'Email',

'Institution',

'Course',

'Platoon',

'Hostel',

'CDS Group',

'Status'

]);

/*
|--------------------------------------------------------------------------
| FETCH DATA
|--------------------------------------------------------------------------
*/

$stmt=$db->query("

SELECT

cm.*,

p.platoon_name,

h.hostel_name,

cg.group_name

FROM corps_members cm

LEFT JOIN platoons p

ON p.id=cm.platoon_id

LEFT JOIN hostels h

ON h.id=cm.hostel_id

LEFT JOIN cds_group_members cgm

ON cgm.corps_member_id=cm.id

LEFT JOIN cds_groups cg

ON cg.id=cgm.cds_group_id

ORDER BY

cm.firstname,
cm.lastname

");

$count=1;

while($row=$stmt->fetch(PDO::FETCH_ASSOC)){

    fputcsv($output,[

        $count++,

        $row['state_code'],

        $row['call_up_number'],

        $row['firstname'].' '.$row['lastname'],

        $row['gender'],

        $row['phone'],

        $row['email'],

        $row['institution'],

        $row['course_of_study'],

        $row['platoon_name'],

        $row['hostel_name'],

        $row['group_name'],

        $row['status']

    ]);

}

fclose($output);

exit;