<?php
// api/roster_action.php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/role_config.php';

// Check Auth
if (!isLoggedIn()) {
    redirect('../index.php?page=login');
}

$roles = $all_roles_flat;
$service_id = isset($_POST['service_id']) ? (int)$_POST['service_id'] : (isset($_GET['service_id']) ? (int)$_GET['service_id'] : 0);
$roster_id = isset($_POST['roster_id']) ? (int)$_POST['roster_id'] : 0;

// Re-fetch roster_id if not strictly passed but service_id gives us context?
// Actually roster.php passed plain assigns. We need roster_id.
// The existing logic used $roster_id which was fetched from DB based on $service_id.
// So we should do the same lookup if $roster_id is passed or just rely on service_id?
// Ideally we pass service_id and find the roster for it.

// Let's rely on service_id to find the roster, similar to roster.php logic, to be safe.
if ($service_id) {
    if (!$roster_id) {
        $stmt = $pdo->prepare("SELECT id FROM rosters WHERE service_id = ?");
        $stmt->execute([$service_id]);
        $roster_id = $stmt->fetchColumn();
    }
}

if (!$roster_id) {
    // If usage of this API implies Creating one, we might need to.
    // roster.php auto-creates it on view. So if we save, it should exist. 
    // If not, error.
    header("Location: ../index.php?page=roster&service_id=$service_id&error=Roster not found");
    exit;
}

// HANDLE SAVE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_roster'])) {
    $assignments_json = $_POST['assignments_json'] ?? []; 
    
    // Save Checklist
    $checklist = $_POST['checklist'] ?? [];
    $checklist_json = json_encode($checklist);
    $pdo->prepare("UPDATE rosters SET checklist_json = ? WHERE id = ?")->execute([$checklist_json, $roster_id]); 
    
    foreach ($assignments_json as $encoded_role => $json_str) {
        $role_name = base64_decode($encoded_role);
        
        // Validation: Ensure role exists in config? 
        // Optional but good for security.
        // if (!in_array($role_name, $roles)) continue;
        
        $entries = json_decode($json_str, true);
        
        if (!is_array($entries)) $entries = [];
        
        // Delete existing
        $pdo->prepare("DELETE FROM roster_assignments WHERE roster_id=? AND role_name=?")->execute([$roster_id, $role_name]);
        
        // Insert new
        foreach ($entries as $entry) {
            $name = trim($entry['name'] ?? '');
            $member_id = !empty($entry['id']) ? (int)$entry['id'] : null;
            
            if (!empty($name)) {
                $pdo->prepare("INSERT INTO roster_assignments (roster_id, role_name, person_name, member_id) VALUES (?, ?, ?, ?)")
                    ->execute([$roster_id, $role_name, $name, $member_id]);
            }
        }
    }
    
    // Reset status to Draft if edited by non-coordinator
    if (isset($_SESSION['user_role']) && ($_SESSION['user_role'] === 'roster_manager' || $_SESSION['user_role'] === 'roster_admin')) {
        $pdo->prepare("UPDATE rosters SET status = 'Draft' WHERE id = ?")->execute([$roster_id]);
    }
    
    if (function_exists('logActivity')) {
        logActivity($_SESSION['user_id'], 'UPDATE', "Updated Roster for Service ID $service_id");
    }

    header("Location: ../index.php?page=roster&service_id=$service_id&msg=Saved");
    exit;
}

// HANDLE APPROVE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_roster'])) {
    if (hasRole('coordinator')) {
        $pdo->prepare("UPDATE rosters SET status = 'Approved', approved_by = ?, approved_at = NOW() WHERE id = ?")
            ->execute([$_SESSION['member_id'] ?? null, $roster_id]);
            
        if (function_exists('logActivity')) {
            logActivity($_SESSION['user_id'], 'APPROVE', "Approved Roster for Service ID $service_id");
        }
        
        header("Location: ../index.php?page=roster&service_id=$service_id&msg=Approved");
        exit;
    } else {
        header("Location: ../index.php?page=roster&service_id=$service_id&error=Unauthorized");
        exit;
    }
}

// HANDLE CLOSE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_roster'])) {
    if (hasRole('admin')) {
        $pdo->prepare("UPDATE rosters SET status = 'Closed', closed_by = ?, closed_at = NOW() WHERE id = ?")
            ->execute([$_SESSION['member_id'] ?? null, $roster_id]);
            
        // Trigger Member Status Automation
        require_once '../includes/member_status_check.php';
        updateMemberInactivity($pdo);
            
        if (function_exists('logActivity')) {
            logActivity($_SESSION['user_id'], 'CLOSE', "Closed Roster for Service ID $service_id");
        }
        
        header("Location: ../index.php?page=roster&service_id=$service_id&msg=Roster Closed");
        exit;
    } else {
        header("Location: ../index.php?page=roster&service_id=$service_id&error=Unauthorized");
        exit;
    }
}

// Fallback
header("Location: ../index.php?page=roster&service_id=$service_id");
exit;
