<?php

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

require_login();

$activityId = (int)($_GET['activity'] ?? 0);

if ($activityId <= 0) {
    die("Invalid Activity.");
}

/*
|--------------------------------------------------------------------------
| GET ACTIVITY
|--------------------------------------------------------------------------
*/

$stmt = $db->prepare("
SELECT *
FROM camp_activities
WHERE id=?
");

$stmt->execute([$activityId]);

$activity = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$activity) {
    die("Activity not found.");
}

/*
|--------------------------------------------------------------------------
| GET ATTENDANCE
|--------------------------------------------------------------------------
*/

$stmt = $db->prepare("
SELECT

cm.state_code,
cm.firstname,
cm.lastname,
cm.phone,

caa.attendance_status,
caa.attendance_time,
caa.remarks

FROM camp_activity_attendance caa

INNER JOIN corps_members cm

ON cm.id=caa.corps_member_id

WHERE caa.activity_id=?

ORDER BY cm.lastname,
cm.firstname
");

$stmt->execute([$activityId]);

$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| EXCEL HEADERS
|--------------------------------------------------------------------------
*/

$fileName = str_replace(' ', '_', $activity['activity_name']) . "_Attendance.xls";

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Pragma: no-cache");
header("Expires: 0");

?>

<table border="1">

    <tr>
        <th colspan="7" style="font-size:18px;">
            NYSC CAMP ACTIVITY ATTENDANCE REPORT
        </th>
    </tr>

    <tr>
        <td colspan="7">

            <strong>Activity:</strong>

            <?= htmlspecialchars($activity['activity_name']) ?>

        </td>
    </tr>

    <tr>
        <td colspan="7">

            <strong>Date:</strong>

            <?= date('d M Y', strtotime($activity['activity_date'])) ?>

        </td>
    </tr>

    <tr>
        <td colspan="7">

            <strong>Venue:</strong>

            <?= htmlspecialchars($activity['venue']) ?>

        </td>
    </tr>

    <tr>
        <td colspan="7"></td>
    </tr>

    <tr style="background:#dddddd;">

        <th>S/N</th>

        <th>State Code</th>

        <th>Name</th>

        <th>Phone</th>

        <th>Status</th>

        <th>Attendance Time</th>

        <th>Remarks</th>

    </tr>

    <?php

$i = 1;

foreach($records as $row):

?>

    <tr>

        <td><?= $i++ ?></td>

        <td><?= $row['state_code'] ?></td>

        <td><?= $row['lastname']." ".$row['firstname'] ?></td>

        <td><?= $row['phone'] ?></td>

        <td><?= $row['attendance_status'] ?></td>

        <td><?= $row['attendance_time'] ?></td>

        <td><?= $row['remarks'] ?></td>

    </tr>

    <?php endforeach; ?>

</table>