<?php
/**
 * AJAX Handler - Get Society Members
 * GHAMECC Choir Management Platform
 * 
 * This script returns members from societies who are not already 
 * registered for a specific conference. Supports both circuit and society level roles.
 */

// Include required files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set default response
$response = [];

// Check if user has appropriate permissions
if (!hasRole(['admin', 'diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_dom', 'diocesan_treasurer', 
              'circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer',
              'choirmaster', 'society_secretary', 'society_treasurer'])) {
    // Return empty response for unauthorized users
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Get parameters
$circuitId = isset($_POST['circuit_id']) ? (int)$_POST['circuit_id'] : 0;
$societyId = isset($_POST['society_id']) ? (int)$_POST['society_id'] : 0;
$conferenceId = isset($_POST['conference_id']) ? (int)$_POST['conference_id'] : 0;

// Get user's role information
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_dom', 'diocesan_treasurer']);
$isCircuitRole = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer']);
$isSocietyRole = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);

// Get user's circuit if they have a circuit role
$userCircuitId = 0;
if ($isCircuitRole) {
    $userCircuitQuery = "SELECT circuit_id FROM users WHERE id = $userId";
    $userCircuitResult = fetchRow($userCircuitQuery);
    if ($userCircuitResult && isset($userCircuitResult['circuit_id'])) {
        $userCircuitId = $userCircuitResult['circuit_id'];
    }
}

// Get user's society if they have a society role
$userSocietyId = 0;
if ($isSocietyRole) {
    $userSocietyQuery = "SELECT society_id FROM users WHERE id = $userId";
    $userSocietyResult = fetchRow($userSocietyQuery);
    if ($userSocietyResult && isset($userSocietyResult['society_id'])) {
        $userSocietyId = $userSocietyResult['society_id'];
    }
}

// Validate access and parameters
if ($conferenceId) {
    // For circuit roles, only allow access to their own circuit
    if ($isCircuitRole && $circuitId && $userCircuitId != $circuitId) {
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    
    // For society roles, only allow access to their own society
    if ($isSocietyRole) {
        // Override societyId with user's society ID for security
        $societyId = $userSocietyId;
        
        if (!$societyId) {
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }
    }
    
    // Build query based on role
    if ($societyId > 0) {
        // First check if any members exist for this society
        $checkQuery = "SELECT COUNT(*) as count FROM members WHERE society_id = $societyId";
        $checkResult = fetchRow($checkQuery);
        
        if ($checkResult && $checkResult['count'] > 0) {
            // Get members from a specific society who are not already registered
            $query = "SELECT m.id, m.first_name, m.last_name, m.contact_number as phone, s.name as society_name
                      FROM members m
                      JOIN societies s ON m.society_id = s.id
                      WHERE m.society_id = $societyId
                      AND m.id NOT IN (
                          SELECT cr.member_id 
                          FROM conference_registrations cr
                          WHERE cr.conference_id = $conferenceId
                      )
                      ORDER BY m.last_name, m.first_name";
                      
            // Get the list of members for debugging
            $allMembersQuery = "SELECT m.id, m.first_name, m.last_name 
                               FROM members m 
                               WHERE m.society_id = $societyId";
            $allMembers = fetchRows($allMembersQuery);
            
            // Get the list of registered members for debugging
            $registeredQuery = "SELECT cr.member_id, m.first_name, m.last_name 
                               FROM conference_registrations cr
                               JOIN members m ON cr.member_id = m.id
                               WHERE cr.conference_id = $conferenceId
                               AND m.society_id = $societyId";
            $registeredMembers = fetchRows($registeredQuery);
            
            $response = fetchRows($query);
            
            // If no members are available after filtering, provide debug info
            if (empty($response)) {
                $response = [
                    'debug' => [
                        'query' => $query,
                        'society_id' => $societyId,
                        'conference_id' => $conferenceId,
                        'all_members' => $allMembers,
                        'registered_members' => $registeredMembers,
                        'message' => 'All members from this society are already registered for the conference'
                    ]
                ];
            }
        } else {
            // No members exist for this society
            $response = [
                'debug' => [
                    'society_id' => $societyId,
                    'message' => 'No members found in this society'
                ]
            ];
        }
    } elseif ($circuitId > 0) {
        // Get members from societies in the circuit
        $query = "SELECT m.id, m.first_name, m.last_name, m.contact_number as phone, s.name as society_name
                  FROM members m
                  JOIN societies s ON m.society_id = s.id
                  WHERE s.circuit_id = $circuitId
                  AND m.id NOT IN (
                      SELECT cr.member_id 
                      FROM conference_registrations cr
                      WHERE cr.conference_id = $conferenceId
                  )
                  ORDER BY s.name, m.last_name, m.first_name";
        $response = fetchRows($query);
    }
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
