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

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

// Require login
requireLogin();

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

// Basic variables
$pageTitle = "Circuit Conference Delegates List";
$userId = $_SESSION['user_id'];
$isCircuitRole = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_treasurer', 'circuit_music_director']);

// Check if user has appropriate permissions (only circuit roles or admin)
if (!hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_treasurer', 'circuit_music_director', 'admin'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

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

// If no circuit ID found and not admin, redirect to index
if (!$userCircuitId && !hasRole(['admin'])) {
    header("Location: ../index.php");
    exit("No circuit 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 circuit or 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 circuit information if user is circuit role
$circuit = null;
if ($isCircuitRole) {
    $circuit = fetchRow("SELECT * FROM circuits WHERE id = $userCircuitId");

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

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

// Admin has access to all conferences
if (hasRole(['admin'])) {
    $hasAccess = true;
    // If admin, get the circuit from the conference if it's a circuit conference
    if ($conference['type'] === 'circuit') {
        $userCircuitId = $conference['entity_id'];
    } else {
        // For diocese conferences, admin needs to specify which circuit to view
        // Default to the first circuit in that diocese
        $firstCircuit = fetchRow("SELECT id FROM circuits WHERE diocese_id = {$conference['entity_id']} LIMIT 1");
        if ($firstCircuit) {
            $userCircuitId = $firstCircuit['id'];
        }
    }
}
// For circuit conferences, check if user belongs to the conference's circuit
elseif ($conference['type'] === 'circuit' && $userCircuitId == $conference['entity_id']) {
    $hasAccess = true;
}
// For diocese conferences, check if user's circuit belongs to the conference's diocese
elseif ($conference['type'] === 'diocese') {
    $circuitDiocese = fetchRow("SELECT diocese_id FROM circuits WHERE id = $userCircuitId");
    if ($circuitDiocese && $circuitDiocese['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 from societies in this circuit
$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
                      AND s.circuit_id = $userCircuitId
                      ORDER BY s.name, m.last_name, m.first_name");

// Group delegates by society
$delegatesBySociety = [];
foreach ($delegates as $delegate) {
    $societyId = $delegate['society_id'];
    $societyName = $delegate['society_name'];
    
    if (!isset($delegatesBySociety[$societyId])) {
        $delegatesBySociety[$societyId] = [
            'name' => $societyName,
            'delegates' => []
        ];
    }
    
    $delegatesBySociety[$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 societies in this circuit
$societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = $userCircuitId ORDER BY 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">Circuit 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=circuit" 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> <?php echo ucfirst($conference['type']); ?> Conference<br>
                    <strong>Entity:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?><br>
                    <strong>Total Delegates:</strong> <?php echo $totalDelegates; ?>
                </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">
                    No delegates have been registered for this conference yet from societies in your circuit.
                </div>
                <?php else: ?>
                
                <!-- Delegates by Society -->
                <?php foreach ($delegatesBySociety as $societyId => $societyData): ?>
                <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($societyData['name']); ?> Society
                            <span class="badge bg-secondary"><?php echo count($societyData['delegates']); ?> delegates</span>
                        </h5>
                    </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 $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>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </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>
</body>
</html>
