<?php
/**
 * Diocese Conference Delegates List
 * GHAMECC Choir Management Platform
 * 
 * This page displays all registered society members for a selected conference at diocese level.
 */

require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set base path for includes
$basePath = '..';

// Basic variables
$pageTitle = "Diocese Conference Delegates List";
$userId = $_SESSION['user_id'];
$isDioceseRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_music_director']);

// Check if user has appropriate permissions (only diocese roles or admin)
if (!hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_music_director', 'admin'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's diocese
$userDioceseId = 0;
if ($isDioceseRole) {
    $userDioceseQuery = "SELECT diocese_id FROM users WHERE id = $userId";
    $userDioceseResult = fetchRow($userDioceseQuery);
    if ($userDioceseResult && isset($userDioceseResult['diocese_id'])) {
        $userDioceseId = $userDioceseResult['diocese_id'];
    }
}

// If no diocese ID found and not admin, redirect to index
if (!$userDioceseId && !hasRole(['admin'])) {
    header("Location: ../index.php");
    exit("No diocese assigned to your account");
}

// Get conference ID from URL
$conferenceId = isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0;

// If no conference ID provided, redirect to conferences list
if (!$conferenceId) {
    header("Location: index.php");
    exit("No conference selected");
}

// Get conference details - check for diocese conferences
$conference = fetchRow("SELECT c.*, d.name as diocese_name
                       FROM conferences c
                       LEFT JOIN dioceses d ON (c.entity_id = d.id AND c.type = 'diocese')
                       WHERE c.id = $conferenceId AND c.type = 'diocese'");

// If conference not found, redirect
if (!$conference) {
    header("Location: index.php");
    exit("Conference not found or not a diocese conference");
}

// Get diocese information if user is diocese role
$diocese = null;
if ($isDioceseRole) {
    $diocese = fetchRow("SELECT * FROM dioceses WHERE id = $userDioceseId");

    if (!$diocese) {
        header("Location: ../index.php");
        exit("Diocese information not found");
    }
}

// Check if diocese has access to this conference
$hasAccess = false;

// Admin has access to all conferences
if (hasRole(['admin'])) {
    $hasAccess = true;
    // If admin, get the diocese from the conference
    $userDioceseId = $conference['entity_id'];
}
// For diocese conferences, check if user belongs to the conference's diocese
elseif ($userDioceseId == $conference['entity_id']) {
    $hasAccess = true;
}

// Redirect if no access
if (!$hasAccess) {
    header("Location: index.php");
    exit("You don't have access to this conference");
}

// Get search parameters
$searchName = isset($_GET['search_name']) ? trim($_GET['search_name']) : '';
$filterCircuit = isset($_GET['filter_circuit']) ? (int)$_GET['filter_circuit'] : 0;
$filterSociety = isset($_GET['filter_society']) ? (int)$_GET['filter_society'] : 0;

// Build WHERE conditions for filtering
$whereConditions = ["cr.conference_id = $conferenceId", "d.id = $userDioceseId"];

if (!empty($searchName)) {
    $searchName = mysqli_real_escape_string($conn, $searchName);
    $whereConditions[] = "(m.first_name LIKE '%$searchName%' OR m.last_name LIKE '%$searchName%' OR CONCAT(m.first_name, ' ', m.last_name) LIKE '%$searchName%')";
}

if ($filterCircuit > 0) {
    $whereConditions[] = "c.id = $filterCircuit";
}

if ($filterSociety > 0) {
    $whereConditions[] = "s.id = $filterSociety";
}

$whereClause = implode(' AND ', $whereConditions);

// Get all registered delegates for this conference from societies in circuits in this diocese
$delegates = fetchRows("SELECT cr.id, cr.payment_status, cr.registration_date, cr.notes, 
                      m.id as member_id, m.first_name, m.last_name as surname, m.email, m.contact_number as phone, 
                      m.sex as gender, m.part as voice_part, m.dob as date_of_birth,
                      s.name as society_name, s.id as society_id,
                      c.name as circuit_name, c.id as circuit_id
                      FROM conference_registrations cr
                      JOIN members m ON cr.member_id = m.id
                      JOIN societies s ON m.society_id = s.id
                      JOIN circuits c ON s.circuit_id = c.id
                      JOIN dioceses d ON c.diocese_id = d.id
                      WHERE $whereClause
                      ORDER BY c.name, s.name, m.last_name, m.first_name");

// Group delegates by circuit and society
$delegatesByCircuit = [];
foreach ($delegates as $delegate) {
    $circuitId = $delegate['circuit_id'];
    $circuitName = $delegate['circuit_name'];
    $societyId = $delegate['society_id'];
    $societyName = $delegate['society_name'];
    
    if (!isset($delegatesByCircuit[$circuitId])) {
        $delegatesByCircuit[$circuitId] = [
            'name' => $circuitName,
            'societies' => []
        ];
    }
    
    if (!isset($delegatesByCircuit[$circuitId]['societies'][$societyId])) {
        $delegatesByCircuit[$circuitId]['societies'][$societyId] = [
            'name' => $societyName,
            'delegates' => []
        ];
    }
    
    $delegatesByCircuit[$circuitId]['societies'][$societyId]['delegates'][] = $delegate;
}

// Calculate statistics
$totalDelegates = count($delegates);
$genderStats = [
    'male' => 0,
    'female' => 0,
    'other' => 0
];

$voicePartStats = [
    'soprano' => 0,
    'alto' => 0,
    'tenor' => 0,
    'bass' => 0,
    'other' => 0
];

foreach ($delegates as $delegate) {
    // Gender stats
    $gender = strtolower($delegate['gender'] ?? '');
    if ($gender == 'male') {
        $genderStats['male']++;
    } elseif ($gender == 'female') {
        $genderStats['female']++;
    } else {
        $genderStats['other']++;
    }
    
    // Voice part stats
    $voicePart = strtolower($delegate['voice_part'] ?? '');
    if (in_array($voicePart, ['soprano', 'alto', 'tenor', 'bass'])) {
        $voicePartStats[$voicePart]++;
    } else {
        $voicePartStats['other']++;
    }
}

// Get circuits in this diocese for filter dropdown
$circuits = fetchRows("SELECT id, name FROM circuits WHERE diocese_id = $userDioceseId ORDER BY name");

// Get societies in this diocese for filter dropdown
$societies = fetchRows("SELECT s.id, s.name, c.name as circuit_name 
                       FROM societies s 
                       JOIN circuits c ON s.circuit_id = c.id 
                       WHERE c.diocese_id = $userDioceseId 
                       ORDER BY c.name, s.name");

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
    <style type="text/css" media="print">
        @page { size: landscape; }
        .no-print { display: none !important; }
        .container-fluid { width: 100%; }
        .card { break-inside: avoid; }
        .card-header { background-color: #f8f9fc !important; color: #000 !important; }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include_once '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include_once '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Diocese Conference Delegates List</h1>
                    <div class="btn-toolbar mb-2 mb-md-0 no-print">
                        <a href="index.php" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back to Conferences
                        </a>
                        <a href="export_delegates.php?conference_id=<?php echo $conferenceId; ?>&level=diocese" class="btn btn-sm btn-success me-2">
                            <i class="fas fa-file-excel"></i> Export to Excel
                        </a>
                        <button onclick="window.print()" class="btn btn-sm btn-primary">
                            <i class="fas fa-print"></i> Print
                        </button>
                    </div>
                </div>
                
                <div class="alert alert-info">
                    <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?><br>
                    <strong>Date:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> to <?php echo date('M d, Y', strtotime($conference['end_date'])); ?><br>
                    <strong>Type:</strong> Diocese Conference<br>
                    <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?><br>
                    <strong>Total Delegates:</strong> <?php echo $totalDelegates; ?>
                </div>

                <!-- Search and Filter Section -->
                <div class="card shadow mb-4 no-print">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-search me-2"></i>Search & Filter Delegates
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="GET" action="" id="filterForm">
                            <input type="hidden" name="conference_id" value="<?php echo $conferenceId; ?>">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="search_name" class="form-label">Search by Name</label>
                                    <input type="text" class="form-control" id="search_name" name="search_name" 
                                           value="<?php echo htmlspecialchars($searchName); ?>" 
                                           placeholder="Enter first name or last name">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="filter_circuit" class="form-label">Filter by Circuit</label>
                                    <select class="form-select" id="filter_circuit" name="filter_circuit">
                                        <option value="0">All Circuits</option>
                                        <?php foreach ($circuits as $circuit): ?>
                                        <option value="<?php echo $circuit['id']; ?>" <?php echo $filterCircuit == $circuit['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($circuit['name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="filter_society" class="form-label">Filter by Society</label>
                                    <select class="form-select" id="filter_society" name="filter_society">
                                        <option value="0">All Societies</option>
                                        <?php foreach ($societies as $society): ?>
                                        <option value="<?php echo $society['id']; ?>" <?php echo $filterSociety == $society['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($society['name'] . ' (' . $society['circuit_name'] . ')'); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary me-2">
                                        <i class="fas fa-search me-1"></i> Search
                                    </button>
                                    <a href="?conference_id=<?php echo $conferenceId; ?>" class="btn btn-secondary">
                                        <i class="fas fa-times me-1"></i> Clear Filters
                                    </a>
                                    <span class="text-muted ms-3">
                                        <strong><?php echo $totalDelegates; ?></strong> delegate(s) found
                                    </span>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="row mb-4">
                    <!-- Gender Statistics -->
                    <div class="col-md-6">
                        <div class="card shadow">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Gender Distribution</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>Gender</th>
                                                <th>Count</th>
                                                <th>Percentage</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>Male</td>
                                                <td><?php echo $genderStats['male']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($genderStats['male'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Female</td>
                                                <td><?php echo $genderStats['female']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($genderStats['female'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Other/Not Specified</td>
                                                <td><?php echo $genderStats['other']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($genderStats['other'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Voice Part Statistics -->
                    <div class="col-md-6">
                        <div class="card shadow">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Voice Part Distribution</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>Voice Part</th>
                                                <th>Count</th>
                                                <th>Percentage</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>Soprano</td>
                                                <td><?php echo $voicePartStats['soprano']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voicePartStats['soprano'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Alto</td>
                                                <td><?php echo $voicePartStats['alto']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voicePartStats['alto'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Tenor</td>
                                                <td><?php echo $voicePartStats['tenor']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voicePartStats['tenor'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Bass</td>
                                                <td><?php echo $voicePartStats['bass']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voicePartStats['bass'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Other/Not Specified</td>
                                                <td><?php echo $voicePartStats['other']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voicePartStats['other'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if (empty($delegates)): ?>
                <div class="alert alert-info">
                    <?php if (!empty($searchName) || $filterCircuit > 0 || $filterSociety > 0): ?>
                        No delegates found matching your search criteria. <a href="?conference_id=<?php echo $conferenceId; ?>">Clear filters</a> to see all delegates.
                    <?php else: ?>
                        No delegates have been registered for this conference yet from societies in your diocese.
                    <?php endif; ?>
                </div>
                <?php else: ?>
                
                <!-- Delegates by Circuit and Society -->
                <?php foreach ($delegatesByCircuit as $circuitId => $circuitData): ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3 bg-primary text-white">
                        <h5 class="m-0 font-weight-bold">
                            <?php echo htmlspecialchars($circuitData['name']); ?> Circuit
                        </h5>
                    </div>
                    
                    <?php foreach ($circuitData['societies'] as $societyId => $societyData): ?>
                    <div class="card-body border-bottom">
                        <h6 class="font-weight-bold text-primary mb-3">
                            <?php echo htmlspecialchars($societyData['name']); ?> Society
                            <span class="badge bg-secondary"><?php echo count($societyData['delegates']); ?> delegates</span>
                        </h6>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Contact</th>
                                        <th>Gender</th>
                                        <th>Voice Part</th>
                                        <th>Payment Status</th>
                                        <th>Accommodation</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $counter = 1; ?>
                                    <?php foreach ($societyData['delegates'] as $delegate): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?></td>
                                        <td>
                                            <?php if (!empty($delegate['phone'])): ?>
                                            <i class="fas fa-phone me-1"></i> <?php echo htmlspecialchars($delegate['phone']); ?><br>
                                            <?php endif; ?>
                                            <?php if (!empty($delegate['email'])): ?>
                                            <i class="fas fa-envelope me-1"></i> <?php echo htmlspecialchars($delegate['email']); ?>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars(ucfirst($delegate['gender'] ?? 'Not specified')); ?></td>
                                        <td><?php echo htmlspecialchars(ucfirst($delegate['voice_part'] ?? 'Not specified')); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $delegate['payment_status'] === 'paid' ? 'success' : ($delegate['payment_status'] === 'waived' ? 'info' : 'warning'); ?>">
                                                <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $delegate['payment_status']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="delegate_accommodation.php?conference_id=<?php echo $conferenceId; ?>&registration_id=<?php echo $delegate['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-bed me-1"></i> Manage
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
                
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Auto-submit form on filter change
        $('#filter_circuit, #filter_society').change(function() {
            $('#filterForm').submit();
        });
        
        // Real-time search with debounce
        let searchTimeout;
        $('#search_name').on('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(function() {
                $('#filterForm').submit();
            }, 500); // Wait 500ms after user stops typing
        });
    });
    </script>
</body>
</html>
