<?php
/**
 * API: Get Circuit Members
 * GHAMECC Choir Management Platform
 * 
 * This API endpoint retrieves members from a specific circuit.
 */

// Include authentication functions
require_once '../includes/auth.php';

// Require login
requireLogin();

// Set content type to JSON
header('Content-Type: application/json');

// Check if circuit_id is provided
if (!isset($_GET['circuit_id']) || empty($_GET['circuit_id'])) {
    echo json_encode(['error' => 'Circuit ID is required']);
    exit;
}

$circuitId = (int)$_GET['circuit_id'];

// Validate circuit exists
$circuit = fetchRow("SELECT * FROM circuits WHERE id = $circuitId");
if (!$circuit) {
    echo json_encode(['error' => 'Circuit not found']);
    exit;
}

// Get user's information
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);

// Check if user has access to this circuit
if (!$isAdmin) {
    $userCircuit = fetchRow("SELECT c.id 
                            FROM circuits c
                            JOIN users u ON u.circuit_id = c.id
                            WHERE u.id = $userId");
    
    $userDiocese = fetchRow("SELECT d.id 
                            FROM dioceses d
                            JOIN users u ON u.diocese_id = d.id
                            WHERE u.id = $userId");
    
    $circuitDiocese = fetchRow("SELECT diocese_id FROM circuits WHERE id = $circuitId");
    
    // User must be from the same circuit or from the parent diocese
    $hasAccess = false;
    
    if ($userCircuit && $userCircuit['id'] == $circuitId) {
        $hasAccess = true; // User is from this circuit
    } elseif ($userDiocese && $circuitDiocese && $userDiocese['id'] == $circuitDiocese['diocese_id']) {
        $hasAccess = true; // User is from the parent diocese
    }
    
    if (!$hasAccess) {
        echo json_encode(['error' => 'You do not have access to this circuit']);
        exit;
    }
}

// Get all members from societies in this circuit
$members = fetchRows("SELECT m.id, m.first_name, m.surname, s.name as society_name
                     FROM members m
                     JOIN societies s ON m.society_id = s.id
                     WHERE s.circuit_id = $circuitId
                     ORDER BY m.surname, m.first_name");

// Return the members as JSON
echo json_encode($members);
exit;
