<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();

$pdo = db();
$activities = $pdo->query('SELECT id, name FROM activities ORDER BY date DESC')->fetchAll();

$filters = [
    'start_date' => $_GET['start_date'] ?? date('Y-m-01'),
    'end_date' => $_GET['end_date'] ?? date('Y-m-d'),
    'activity_id' => $_GET['activity_id'] ?? '',
    'status' => $_GET['status'] ?? '',
];

$conditions = [];
$params = [];

if ($filters['start_date']) {
    $conditions[] = 'DATE(att.time_in) >= :start_date';
    $params['start_date'] = $filters['start_date'];
}

if ($filters['end_date']) {
    $conditions[] = 'DATE(att.time_in) <= :end_date';
    $params['end_date'] = $filters['end_date'];
}

if ($filters['activity_id']) {
    $conditions[] = 'att.activity_id = :activity_id';
    $params['activity_id'] = (int) $filters['activity_id'];
}

if ($filters['status']) {
    $conditions[] = 'att.status = :status';
    $params['status'] = $filters['status'];
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';
$stmt = $pdo->prepare(
    "SELECT att.*, s.full_name, s.student_id, act.name AS activity_name
     FROM attendance att
     INNER JOIN students s ON att.student_id = s.id
     INNER JOIN activities act ON att.activity_id = act.id
     $where
     ORDER BY att.time_in DESC"
);
$stmt->execute($params);
$records = $stmt->fetchAll();

render_header('Reports', ['active' => 'reports']);
?>
<div class="card shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0">Attendance Filters</h5>
    </div>
    <div class="card-body">
        <form method="get" class="row gy-3">
            <div class="col-md-3">
                <label class="form-label">Start Date</label>
                <input type="date" name="start_date" class="form-control"
                       value="<?= sanitize($filters['start_date']) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">End Date</label>
                <input type="date" name="end_date" class="form-control"
                       value="<?= sanitize($filters['end_date']) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Activity</label>
                <select name="activity_id" class="form-select">
                    <option value="">All activities</option>
                    <?php foreach ($activities as $activity): ?>
                        <option value="<?= $activity['id'] ?>" <?= selected($filters['activity_id'], $activity['id']) ?>>
                            <?= sanitize($activity['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
                <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">Any status</option>
                    <option value="present" <?= selected($filters['status'], 'present') ?>>Present</option>
                    <option value="late" <?= selected($filters['status'], 'late') ?>>Late</option>
                    <option value="absent" <?= selected($filters['status'], 'absent') ?>>Absent</option>
                    <option value="excused" <?= selected($filters['status'], 'excused') ?>>Excused</option>
                </select>
            </div>
            <div class="col-md-1 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">Apply</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Attendance Records</h5>
        <a href="<?= url_for('api/manual_entry.php?'.http_build_query($filters)) ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
            Export JSON
        </a>
    </div>
    <div class="card-body">
        <?php if (!$records): ?>
            <p class="text-muted text-center mb-0">No records match the filters.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>Student</th>
                        <th>Activity</th>
                        <th>Status</th>
                        <th>In</th>
                        <th>Out</th>
                        <th>Notes</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($records as $row): ?>
                        <tr>
                            <td>
                                <strong><?= sanitize($row['full_name']) ?></strong><br>
                                <span class="text-muted-sm"><?= sanitize($row['student_id']) ?></span>
                            </td>
                            <td><?= sanitize($row['activity_name']) ?></td>
                            <td>
                                <span class="badge <?= $row['status'] === 'present'
                                    ? 'bg-success-subtle text-success'
                                    : 'bg-warning-subtle text-warning' ?>">
                                    <?= strtoupper(sanitize($row['status'])) ?>
                                </span>
                            </td>
                            <td><?= format_datetime($row['time_in']) ?></td>
                            <td><?= format_datetime($row['time_out']) ?></td>
                            <td><?= sanitize($row['notes'] ?? '') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php
render_footer();
