<?php
// includes/member_status_check.php

function updateMemberInactivity($pdo) {
    try {
        // Configuration
        $cutoff_date = '2026-02-11';
        $weeks_threshold = 4;
        
        // 1. Get current date
        $today = new DateTime();
        $start_date = new DateTime($cutoff_date);
        
        // If we haven't reached 4 weeks past Feb 11, we can't enforce the rule yet?
        // Actually, the rule is "if a member doesn't have this score for 4 consecutive weeks".
        // So we need look back 4 weeks. If the lookback window overlaps with < Feb 11, we explicitly ignore those earlier weeks?
        // Or simply: check assignments in the last 4 weeks. If the window start is < Feb 11, clamp it.
        
        $four_weeks_ago = (new DateTime())->modify("-{$weeks_threshold} weeks");
        
        // Ensure effective start date is not before Feb 11
        if ($four_weeks_ago < $start_date) {
            $effective_start = $start_date;
        } else {
            $effective_start = $four_weeks_ago;
        }
        
        // Re-check: If effective start is > today, it means we are essentially before Feb 11.
        if ($effective_start > $today) return; // Should not happen given logic above
        
        // Calculates weeks passed since Feb 11 to see if we even have enough data
        $interval = $start_date->diff($today);
        $weeks_since_start = floor($interval->days / 7);
        
        if ($weeks_since_start < $weeks_threshold) {
            // Not enough time has passed from Feb 11 to determine 4 weeks of inactivity
            return;
        }
        
        // LOGIC:
        // Find members who are currently 'Available' or 'Active' (assuming 'Available' is the status to change)
        // AND have ZERO assignments in rosters that are 'Closed' 
        // AND the service_date is between $effective_start and $today.
        
        // However, we must ensure there WAS strictly an opportunity to be assigned.
        // If there were no services in that period, everyone would be marked inactive?
        // The requirement implies "if a member doesn't have this score". Score comes from closed roster.
        // So if 4 weeks pass and they have 0 score.
        
        // We need to check if there have been services in the last 4 weeks.
        $stmt_services = $pdo->prepare("SELECT COUNT(*) FROM rosters JOIN services ON rosters.service_id = services.id WHERE rosters.status = 'Closed' AND services.service_date >= ? AND services.service_date <= ?");
        $stmt_services->execute([$effective_start->format('Y-m-d'), $today->format('Y-m-d')]);
        $roster_count = $stmt_services->fetchColumn();
        
        if ($roster_count == 0) {
            // No rosters closed in the window, so no one could have a score. Do not penalize.
            return;
        }

        // Fetch candidate members (Status = Available)
        // Adjust status name based on DB (typically 'Available')
        $sql = "
            UPDATE members m
            SET m.status = 'Not Available'
            WHERE m.status = 'Available'
            AND m.unit != 'Visitor'
            AND m.id NOT IN (
                SELECT ra.member_id 
                FROM roster_assignments ra
                JOIN rosters r ON ra.roster_id = r.id
                JOIN services s ON r.service_id = s.id
                WHERE r.status = 'Closed'
                AND s.service_date >= :start_date
                AND s.service_date <= :end_date
                AND ra.member_id IS NOT NULL
            )
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':start_date' => $effective_start->format('Y-m-d'),
            ':end_date' => $today->format('Y-m-d')
        ]);
        
        $affected = $stmt->rowCount();
        
        if ($affected > 0 && function_exists('logActivity')) {
            logActivity(null, 'AUTOMATION', "Marked $affected members as 'Not Available' due to 4 weeks inactivity.");
        }
        
    } catch (Exception $e) {
        error_log("Member Status Check Error: " . $e->getMessage());
    }
}
?>
