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

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

// Require login
requireLogin();

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

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

$societyId = (int)$_GET['society_id'];

// Validate society exists
$society = fetchRow("SELECT s.*, c.name as circuit_name, c.diocese_id 
                    FROM societies s
                    JOIN circuits c ON s.circuit_id = c.id
                    WHERE s.id = $societyId");
if (!$society) {
    echo json_encode(['error' => 'Society not found']);
    exit;
}

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

// Check if user has access to this society
if (!$isAdmin) {
    $userSociety = fetchRow("SELECT s.id 
                            FROM societies s
                            JOIN users u ON u.society_id = s.id
                            WHERE u.id = $userId");
    
    $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");
    
    // User must be from the same society, parent circuit, or parent diocese
    $hasAccess = false;
    
    if ($userSociety && $userSociety['id'] == $societyId) {
        $hasAccess = true; // User is from this society
    } elseif ($userCircuit && $userCircuit['id'] == $society['circuit_id']) {
        $hasAccess = true; // User is from the parent circuit
    } elseif ($userDiocese && $userDiocese['id'] == $society['diocese_id']) {
        $hasAccess = true; // User is from the parent diocese
    }
    
    if (!$hasAccess) {
        echo json_encode(['error' => 'You do not have access to this society']);
        exit;
    }
}

// Get all members from this society
$members = fetchRows("SELECT m.id, m.first_name, m.surname, m.position
                     FROM members m
                     WHERE m.society_id = $societyId
                     ORDER BY m.surname, m.first_name");

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