<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php require 'includes/db_connect.php';
date_default_timezone_set('Africa/Lagos');

// Get selected month or default to current
$month = $_GET['month'] ?? date('Y-m');

// Calculate working days (Mon–Fri only) for selected month
function getWorkingDays($month) {
    $start = new DateTime("$month-01");
    $end = clone $start;
    $end->modify('last day of this month');

    $workDays = [];
    while ($start <= $end) {
        if (!in_array($start->format('N'), [6, 7])) { // 6=Sat, 7=Sun
            $workDays[] = $start->format('Y-m-d');
        }
        $start->modify('+1 day');
    }
    return $workDays;
}

$workingDays = getWorkingDays($month);
$totalWorkingDays = count($workingDays);

// Fetch all staff
$staffQuery = $conn->query("SELECT id, fullname, department FROM staff ORDER BY fullname");

$attendanceData = [];
while ($staff = $staffQuery->fetch_assoc()) {
    $staffId = $staff['id'];

    // Count present days in selected month for this staff
    $result = $conn->query("SELECT COUNT(*) as present_days 
        FROM attendance 
        WHERE staff_id = $staffId 
        AND status = 'Present' 
        AND attendance_date BETWEEN '{$workingDays[0]}' AND '{$workingDays[$totalWorkingDays - 1]}'");

    $present = $result->fetch_assoc()['present_days'] ?? 0;
    $percentage = ($totalWorkingDays > 0) ? round(($present / $totalWorkingDays) * 100, 2) : 0;

    $attendanceData[] = [
        'fullname' => $staff['fullname'],
        'department' => $staff['department'],
        'present' => $present,
        'total' => $totalWorkingDays,
        'percentage' => $percentage
    ];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Monthly Attendance Analysis</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
    <h3 class="mb-4 text-orange">Monthly Attendance Report & Performance</h3>

    <form class="row mb-4" method="GET">
        <div class="col-md-4">
            <label for="month" class="form-label">Select Month</label>
            <input type="month" name="month" id="month" class="form-control" value="<?= htmlspecialchars($month) ?>">
        </div>
        <div class="col-md-2 align-self-end">
            <button type="submit" class="btn btn-primary w-100">View</button>
        </div>
    </form>

    <div class="card shadow">
        <div class="card-body">
            <?php if (count($attendanceData) > 0): ?>
                <table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>Staff Name</th>
                            <th>Department</th>
                            <th>Days Present</th>
                            <th>Total Working Days</th>
                            <th>Attendance %</th>
                            <th>Performance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($attendanceData as $data): ?>
                            <tr>
                                <td><?= htmlspecialchars($data['fullname']) ?></td>
                                <td><?= htmlspecialchars($data['department']) ?></td>
                                <td><?= $data['present'] ?></td>
                                <td><?= $data['total'] ?></td>
                                <td><?= $data['percentage'] ?>%</td>
                                <td>
                                    <?php
                                        if ($data['percentage'] >= 90) echo "<span class='badge bg-success'>Excellent</span>";
                                        elseif ($data['percentage'] >= 70) echo "<span class='badge bg-info'>Good</span>";
                                        elseif ($data['percentage'] >= 50) echo "<span class='badge bg-warning text-dark'>Average</span>";
                                        else echo "<span class='badge bg-danger'>Poor</span>";
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="alert alert-warning">No attendance data found for this month.</div>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
