<?php
// Ensure the user is logged in
if (!isset($_SESSION['user_id'])) {
    
header('Location: index.php?page=login');
    exit;
}

$current_user_id $_SESSION['user_id'];
$supervised_plages_by_plan = [];

// 1. Fetch all active plans (or all plans, depending on requirements)
// We will use pk_Plan as the display identifier.
// We fetch fromDate and weeks to calculate the plan's period.
$sql_plans "SELECT pk_Plan, fromDate, weeks FROM CINE_Plan WHERE isActive = TRUE ORDER BY fromDate DESC";
// If you want to show all plans, not just active ones, remove "WHERE isActive = TRUE"

$result_plans mysqli_query($dbc$sql_plans);

if (!
$result_plans) {
    
error_log("SQL Error in supervisedplages.php (fetching plans): " mysqli_error($dbc));
    
// Consider displaying a user-friendly error message here
} else {
    if (
mysqli_num_rows($result_plans) > 0) {
        while (
$plan_row mysqli_fetch_assoc($result_plans)) {
            
$plan_id $plan_row['pk_Plan'];
            
$plan_pk_display htmlspecialchars($plan_row['pk_Plan']); // Using pk_Plan for display
            
            
$plan_date_start_obj = new DateTime($plan_row['fromDate']);
            
$plan_date_end_obj = new DateTime($plan_row['fromDate']);
            
// Calculate end date: fromDate + (weeks * 7 days) - 1 day
            // For example, if weeks = 1, it's fromDate to fromDate + 6 days.
            
$days_to_add = ($plan_row['weeks'] * 7) - 1;
            
$plan_date_end_obj->modify("+" $days_to_add " days");

            
// 2. For each plan, fetch plages supervised by the current user within that plan's timeframe
            
$sql_plages "
                SELECT 
                    P.pk_Plage, 
                    P.date, 
                    P.fromTime, -- Corrected column name
                    P.toTime,   -- Corrected column name
                    F.name AS film_name, -- Corrected column name (was film_title)
                    E.name AS extra_name,
                    E.defaultTime AS extra_duration -- Corrected column name (was extra_duration)
                FROM CINE_Plage P
                LEFT JOIN CINE_Film F ON P.fk_Film = F.pk_Film
                LEFT JOIN CINE_Extra E ON P.fk_Extra = E.pk_Extra
                WHERE P.fk_Person_supervises = ? 
                AND P.date BETWEEN ? AND ?
                ORDER BY P.date ASC, P.fromTime ASC
            "
;

            
$stmt_plages mysqli_prepare($dbc$sql_plages);
            if (
$stmt_plages) {
                
$formatted_plan_start_date $plan_date_start_obj->format('Y-m-d');
                
$formatted_plan_end_date $plan_date_end_obj->format('Y-m-d');
                
                
mysqli_stmt_bind_param($stmt_plages"iss"$current_user_id$formatted_plan_start_date$formatted_plan_end_date);
                
mysqli_stmt_execute($stmt_plages);
                
$result_plages_for_plan mysqli_stmt_get_result($stmt_plages);

                
$plages_in_plan = [];
                if (
$result_plages_for_plan && mysqli_num_rows($result_plages_for_plan) > 0) {
                    while (
$plage_row mysqli_fetch_assoc($result_plages_for_plan)) {
                        
$plages_in_plan[] = $plage_row;
                    }
                }
                
mysqli_stmt_close($stmt_plages);

                if (!empty(
$plages_in_plan)) {
                     
$supervised_plages_by_plan[] = [
                        
'plan_id' => $plan_id,
                        
'plan_pk_display' => $plan_pk_display,
                        
'plan_date_start_display' => $plan_date_start_obj->format('d M Y'),
                        
'plan_date_end_display' => $plan_date_end_obj->format('d M Y'),
                        
'plages' => $plages_in_plan
                    
];
                }
            } else {
                
error_log("Failed to prepare statement for fetching plages: " mysqli_error($dbc));
            }
        }
    } else {
        
// No active plans found, or no plans at all if WHERE clause was removed
        // error_log("No plans found or error fetching plans: " . mysqli_error($dbc)); // This might be redundant if $result_plans is false
    
}
}
?>

<head>
<title>My Supervised Shifts - CinĂ© Le Paris</title>
<link rel="stylesheet" href="assets/css/volunteer.css"> 
<link rel="stylesheet" href="assets/css/supervised_plages.css">
</head>

<div class="supervised-plages-container">
<h1>My Supervised Shifts</h1>

<?php if (isset($_SESSION['user_id'])): ?>
    <div class="action-buttons">
        <a href="index.php?page=dashboard" class="btn btn-secondary">Back to Dashboard</a>
    </div>

    <?php if (!empty($supervised_plages_by_plan)): ?>
        <?php foreach ($supervised_plages_by_plan as $plan_data): ?>
            <div class="plan-card">
                <div class="plan-header">
                    <h2>
                        Plan #<?php echo $plan_data['plan_pk_display']; ?>
                        (<?php echo $plan_data['plan_date_start_display']; ?> - <?php echo $plan_data['plan_date_end_display']; ?>)
                        - <?php echo count($plan_data['plages']); ?> Supervised Shift(s)
                    </h2>
                </div>
                <div class="plages-table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Time</th>
                                <th>Film</th>
                                <th>Extra</th>
                                <th>Extra Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($plan_data['plages'] as $plage): ?>
                                <tr>
                                    <td><?php echo (new DateTime($plage['date']))->format('D, d M Y'); ?></td>
                                    <td><?php echo (new DateTime($plage['fromTime']))->format('H:i'); ?> - <?php echo (new DateTime($plage['toTime']))->format('H:i'); ?></td>
                                    <td><?php echo $plage['film_name'] ? htmlspecialchars($plage['film_name']) : '<span class="text-muted">N/A</span>'?></td>
                                    <td><?php echo $plage['extra_name'] ? htmlspecialchars($plage['extra_name']) : '<span class="text-muted">N/A</span>'?></td>
                                    <td><?php echo $plage['extra_duration'] ? htmlspecialchars($plage['extra_duration']) . ' min' '<span class="text-muted">N/A</span>'?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p class="no-shifts-message">You are not currently assigned to supervise any shifts for the active plan periods, or no active plans with shifts were found.</p>
    <?php endif; ?>

<?php else: ?>
    <p>Please <a href="index.php?page=login">login</a> to view your supervised shifts.</p>
<?php endif; ?>
</div>