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

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

// Require login
requireLogin();

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

// Basic variables
$pageTitle = "Conference Delegates List";
$userId = $_SESSION['user_id'];
$isSocietyRole = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);

// Check if user has appropriate permissions (only society roles)
if (!hasRole(['choirmaster', 'society_secretary', 'society_treasurer'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's society
$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'];
    }
}

// If no society ID found, redirect to index
if (!$userSocietyId) {
    header("Location: ../index.php");
    exit("No society 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 both circuit and diocese conferences
$conference = fetchRow("SELECT c.*, 
                       CASE 
                           WHEN c.type = 'circuit' THEN ct.name 
                           WHEN c.type = 'diocese' THEN d.name 
                       END as entity_name,
                       c.type as conference_type
                       FROM conferences c
                       LEFT JOIN circuits ct ON (c.entity_id = ct.id AND c.type = 'circuit')
                       LEFT JOIN dioceses d ON (c.entity_id = d.id AND c.type = 'diocese')
                       WHERE c.id = $conferenceId AND (c.type = 'circuit' OR c.type = 'diocese')");

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

// Get society information
$society = fetchRow("SELECT s.*, c.name as circuit_name, d.name as diocese_name, d.id as diocese_id 
                    FROM societies s 
                    JOIN circuits c ON s.circuit_id = c.id
                    JOIN dioceses d ON c.diocese_id = d.id
                    WHERE s.id = $userSocietyId");

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

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

// For circuit conferences, check if society belongs to the conference's circuit
if ($conference['conference_type'] == 'circuit' && $society['circuit_id'] == $conference['entity_id']) {
    $hasAccess = true;
}
// For diocese conferences, check if society belongs to the conference's diocese
elseif ($conference['conference_type'] == 'diocese' && $society['diocese_id'] == $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 all registered delegates for this conference
$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
                      FROM conference_registrations cr
                      JOIN members m ON cr.member_id = m.id
                      JOIN societies s ON m.society_id = s.id
                      WHERE cr.conference_id = $conferenceId
                      ORDER BY s.name, m.last_name, m.first_name");

// Group delegates by society
$delegatesBySociety = [];
foreach ($delegates as $delegate) {
    $societyId = $delegate['society_id'];
    if (!isset($delegatesBySociety[$societyId])) {
        $delegatesBySociety[$societyId] = [
            'name' => $delegate['society_name'],
            'delegates' => []
        ];
    }
    $delegatesBySociety[$societyId]['delegates'][] = $delegate;
}

// Get statistics
$totalDelegates = count($delegates);
$totalSocieties = count($delegatesBySociety);
$genderStats = [
    'male' => 0,
    'female' => 0,
    'other' => 0
];
$voiceStats = [
    '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 ($voicePart == 'soprano') {
        $voiceStats['soprano']++;
    } elseif ($voicePart == 'alto') {
        $voiceStats['alto']++;
    } elseif ($voicePart == 'tenor') {
        $voiceStats['tenor']++;
    } elseif ($voicePart == 'bass') {
        $voiceStats['bass']++;
    } else {
        $voiceStats['other']++;
    }
}

?>

<!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; ?> - GHAMECC</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    
    <!-- Custom styles -->
    <link rel="stylesheet" href="<?php echo $basePath; ?>/css/style.css">
    
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            .print-only {
                display: block !important;
            }
            .container-fluid {
                width: 100% !important;
            }
            .card {
                break-inside: avoid;
            }
        }
        .print-only {
            display: none;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../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">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 me-1"></i> Back to Conferences
                        </a>
                        <a href="society_delegates.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-2">
                            <i class="fas fa-user-plus me-1"></i> Manage Delegates
                        </a>
                        <button class="btn btn-sm btn-outline-primary me-2" onclick="window.print()">
                            <i class="fas fa-print me-1"></i> Print List
                        </button>
                        <a href="export_delegates.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-outline-success">
                            <i class="fas fa-file-excel me-1"></i> Export to Excel
                        </a>
                    </div>
                </div>
                
                <!-- Print Header -->
                <div class="print-only mb-4">
                    <h2 class="text-center">GHAMECC Choir Management Platform</h2>
                    <h3 class="text-center">Conference Delegates List</h3>
                </div>
                
                <div class="alert alert-info">
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> <br>
                            <strong><?php echo ucfirst($conference['conference_type']); ?>:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?> <br>
                            <strong>Date:</strong> <?php echo date('F d, Y', strtotime($conference['start_date'])); ?> to <?php echo date('F d, Y', strtotime($conference['end_date'])); ?>
                        </div>
                        <div class="col-md-6">
                            <strong>Total Delegates:</strong> <?php echo $totalDelegates; ?> <br>
                            <strong>Societies Represented:</strong> <?php echo $totalSocieties; ?> <br>
                            <strong>Generated On:</strong> <?php echo date('F d, Y H:i'); ?>
                        </div>
                    </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 $voiceStats['soprano']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voiceStats['soprano'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Alto</td>
                                                <td><?php echo $voiceStats['alto']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voiceStats['alto'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Tenor</td>
                                                <td><?php echo $voiceStats['tenor']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voiceStats['tenor'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Bass</td>
                                                <td><?php echo $voiceStats['bass']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voiceStats['bass'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                            <tr>
                                                <td>Other/Not Specified</td>
                                                <td><?php echo $voiceStats['other']; ?></td>
                                                <td><?php echo $totalDelegates > 0 ? round(($voiceStats['other'] / $totalDelegates) * 100, 1) : 0; ?>%</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if (empty($delegates)): ?>
                <div class="alert alert-info">
                    No delegates have been registered for this conference yet.
                </div>
                <?php else: ?>
                
                <!-- Delegates List -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">All Registered Delegates</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="delegatesTable">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Society</th>
                                        <th>Name</th>
                                        <th>Contact</th>
                                        <th>Gender</th>
                                        <th>Voice Part</th>
                                        <th>Payment Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $count = 1;
                                    foreach ($delegates as $delegate): 
                                    ?>
                                    <tr>
                                        <td><?php echo $count++; ?></td>
                                        <td><?php echo htmlspecialchars($delegate['society_name']); ?></td>
                                        <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?></td>
                                        <td>
                                            <?php if (!empty($delegate['phone'])): ?>
                                            <i class="fas fa-phone-alt 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-info">
                                                <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $delegate['payment_status']))); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Delegates By Society -->
                <h3 class="mb-3">Delegates By Society</h3>
                <?php foreach ($delegatesBySociety as $societyId => $societyData): ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <?php echo htmlspecialchars($societyData['name']); ?> 
                            <span class="badge bg-secondary"><?php echo count($societyData['delegates']); ?> delegates</span>
                        </h6>
                    </div>
                    <div class="card-body">
                        <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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $count = 1;
                                    foreach ($societyData['delegates'] as $delegate): 
                                    ?>
                                    <tr>
                                        <td><?php echo $count++; ?></td>
                                        <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?></td>
                                        <td>
                                            <?php if (!empty($delegate['phone'])): ?>
                                            <i class="fas fa-phone-alt 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-info">
                                                <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $delegate['payment_status']))); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php endif; ?>
                
                <div class="mt-4 mb-5 text-center print-only">
                    <p>Generated from GHAMECC Choir Management Platform</p>
                    <p><?php echo date('F d, Y H:i'); ?></p>
                </div>
            </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() {
        // Initialize DataTable for delegates table
        if ($.fn.DataTable) {
            $('#delegatesTable').DataTable({
                "pageLength": 25,
                "ordering": true,
                "responsive": true
            });
        }
    });
    </script>
</body>
</html>
