<?php
// pages/attendance_manual.php
requireRole('roster_manager');

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Handle Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $date = $_POST['date'];
    $updates = $_POST['status']; // array [member_id => status]
    
    // We are now updating the 'attendance' table.
    // Logic:
    // Present/Late -> Ensure a record exists.
    // Absent -> Ensure NO record exists (delete if exists).
    
    $default_in_time = "$date 09:00:00"; // Default start time for manual bulk entry
    
    foreach ($updates as $mid => $status) {
        if ($status === 'absent') {
            // Delete any attendance for this day
            $pdo->prepare("DELETE FROM attendance WHERE member_id = ? AND DATE(in_time) = ?")
                ->execute([$mid, $date]);
        } else {
            // Check if exists
            $stmt = $pdo->prepare("SELECT id FROM attendance WHERE member_id = ? AND DATE(in_time) = ?");
            $stmt->execute([$mid, $date]);
            $exists = $stmt->fetch();
            
            $is_late = ($status === 'late') ? 1 : 0;
            
            if ($exists) {
                // Update Late Status
                $pdo->prepare("UPDATE attendance SET was_late = ? WHERE id = ?")
                    ->execute([$is_late, $exists['id']]);
            } else {
                // Insert New
                $pdo->prepare("INSERT INTO attendance (member_id, in_time, was_late) VALUES (?, ?, ?)")
                    ->execute([$mid, $default_in_time, $is_late]);
            }
        }
    }
    $success = "Attendance saved.";
}

// Fetch Members - EXCLUDING Visitors
$members = $pdo->query("SELECT * FROM members WHERE status='Available' AND unit != 'Visitor' ORDER BY full_name ASC")->fetchAll();

// Fetch existing records for date
// Map member_id => status
$existing = [];
$e_stmt = $pdo->prepare("SELECT member_id, was_late FROM attendance WHERE DATE(in_time) = ?");
$e_stmt->execute([$date]);
while ($row = $e_stmt->fetch()) {
    $status = $row['was_late'] ? 'late' : 'present';
    $existing[$row['member_id']] = $status;
}
?>

<h1>Manual Attendance Review</h1>

<?php if (isset($success)): ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card">
    <form method="GET" style="margin-bottom: 20px;">
        <input type="hidden" name="page" value="attendance_manual">
        <label>Select Date: </label>
        <input type="date" name="date" value="<?php echo $date; ?>" class="form-control" style="width: auto; display: inline-block;">
        <button type="submit" class="btn">Load</button>
    </form>
    
    <form method="POST">
        <input type="hidden" name="date" value="<?php echo $date; ?>">
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Member</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $m): 
                        // Logic for default: If record exists, use it. If not, default to 'absent'.
                        $curr = $existing[$m['id']] ?? 'absent';
                    ?>
                    <tr>
                        <td>
                            <div style="font-weight: bold;"><?php echo htmlspecialchars($m['full_name']); ?></div>
                            <small style="color: #666;"><?php echo htmlspecialchars($m['unit']); ?></small>
                        </td>
                        <td>
                            <select name="status[<?php echo $m['id']; ?>]" class="form-control" style="width: 150px; <?php if($curr=='absent') echo 'opacity: 0.7;'; else echo 'font-weight:bold;'; ?>">
                                <option value="present" <?php if($curr == 'present') echo 'selected'; ?>>Present</option>
                                <option value="late" <?php if($curr == 'late') echo 'selected'; ?>>Late</option>
                                <option value="absent" <?php if($curr == 'absent') echo 'selected'; ?>>Absent</option>
                            </select>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div style="margin-top: 20px;">
            <button type="submit" class="btn">Save Changes</button>
        </div>
    </form>
</div>
