<?php
/**
 * Conference Registrations
 * GHAMECC Choir Management Platform
 */

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

// Require login
requireLogin();

// Base path for includes
$basePath = '..';

// Read conference id (accept both id and conference_id)
$conferenceId = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0);
if ($conferenceId <= 0) {
    header('Location: index.php');
    exit('No conference selected');
}

// Who am I
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer']);
$isCircuitRole  = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer']);
$isSocietyRole  = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);

// Load conference details
$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");

if (!$conference) {
    header('Location: index.php');
    exit('Conference not found');
}

// Determine user entity ids
$userSocietyId = 0; $userCircuitId = 0; $userDioceseId = 0;
if ($isSocietyRole) {
    $row = fetchRow("SELECT society_id FROM users WHERE id = $userId");
    if ($row) $userSocietyId = (int)$row['society_id'];
}
if ($isCircuitRole) {
    $row = fetchRow("SELECT circuit_id FROM users WHERE id = $userId");
    if ($row) $userCircuitId = (int)$row['circuit_id'];
}
if ($isDiocesanRole) {
    $row = fetchRow("SELECT diocese_id FROM users WHERE id = $userId");
    if ($row) $userDioceseId = (int)$row['diocese_id'];
}

// For circuit/society roles, derive diocese via circuit if needed
if (($isCircuitRole || $isSocietyRole) && $userDioceseId === 0) {
    if ($isSocietyRole && $userSocietyId) {
        $tmp = fetchRow("SELECT c.diocese_id FROM societies s JOIN circuits c ON s.circuit_id = c.id WHERE s.id = $userSocietyId");
        if ($tmp) $userDioceseId = (int)$tmp['diocese_id'];
    } elseif ($isCircuitRole && $userCircuitId) {
        $tmp = fetchRow("SELECT diocese_id FROM circuits WHERE id = $userCircuitId");
        if ($tmp) $userDioceseId = (int)$tmp['diocese_id'];
    }
}

// Access control
$allowed = false;
if ($isAdmin) {
    $allowed = true;
} else {
    if ($conference['conference_type'] === 'diocese') {
        if ($isDiocesanRole && $userDioceseId === (int)$conference['entity_id']) {
            $allowed = true;
        }
        if ($isCircuitRole && $userDioceseId === (int)$conference['entity_id']) {
            $allowed = true; // circuit roles can view diocese conference for their diocese
        }
        if ($isSocietyRole && $userDioceseId === (int)$conference['entity_id']) {
            $allowed = true; // society roles can view but will be restricted to their society in data
        }
    } elseif ($conference['conference_type'] === 'circuit') {
        if ($isCircuitRole && $userCircuitId === (int)$conference['entity_id']) {
            $allowed = true;
        }
        if ($isSocietyRole) {
            // society belongs to circuit?
            $tmp = fetchRow("SELECT circuit_id FROM societies WHERE id = $userSocietyId");
            if ($tmp && (int)$tmp['circuit_id'] === (int)$conference['entity_id']) {
                $allowed = true;
            }
        }
    }
}

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

// Build registrations query with role-based restrictions
$where = " WHERE cr.conference_id = $conferenceId ";
if ($isSocietyRole && $userSocietyId) {
    $where .= " AND m.society_id = $userSocietyId ";
} elseif ($isCircuitRole && $userCircuitId) {
    $where .= " AND s.circuit_id = $userCircuitId ";
}

$registrations = fetchRows("SELECT cr.id as registration_id,
                                   cr.payment_status,
                                   cr.accommodation_required,
                                   cr.registration_date,
                                   cr.notes,
                                   m.id as member_id,
                                   m.first_name,
                                   m.last_name as surname,
                                   m.sex as gender,
                                   m.part as voice_part,
                                   m.contact_number as phone,
                                   m.email,
                                   s.id as society_id,
                                   s.name as society_name,
                                   c.id as circuit_id,
                                   c.name as circuit_name
                            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
                            $where
                            ORDER BY s.name, m.last_name, m.first_name");

// Compute simple stats
$total = $registrations ? count($registrations) : 0;
$male = 0; $female = 0; $other = 0;
$requireAcc = 0;
foreach ($registrations as $r) {
    $g = strtolower($r['gender'] ?? '');
    if ($g === 'male') $male++; elseif ($g === 'female') $female++; else $other++;
    if (!empty($r['accommodation_required'])) $requireAcc++;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conference Registrations - GHAMECC</title>

    <?php include '../includes/favicon.php'; ?>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <?php include '../includes/navbar.php'; ?>

    <div class="container-fluid">
        <div class="row">
            <?php include '../includes/sidebar.php'; ?>

            <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 Registrations</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="view.php?id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Back to Conference
                        </a>
                        <?php if ($isDiocesanRole || $isAdmin): ?>
                        <a href="select_conference.php?target=room_assignments" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-door-open me-1"></i> Room Assignments
                        </a>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="alert alert-info">
                    <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> |
                    <strong>Type:</strong> <?php echo ucfirst($conference['conference_type']); ?> |
                    <strong>Entity:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?> |
                    <strong>Dates:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> - <?php echo date('M d, Y', strtotime($conference['end_date'])); ?>
                </div>

                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-primary shadow h-100 py-2">
                            <div class="card-body">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Registrations</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $total; ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-success shadow h-100 py-2">
                            <div class="card-body">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Accommodation Required</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $requireAcc; ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-info shadow h-100 py-2">
                            <div class="card-body">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Male</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $male; ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-warning shadow h-100 py-2">
                            <div class="card-body">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Female</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $female; ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (empty($registrations)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>No registrations found for this conference.
                    </div>
                <?php else: ?>
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">Registered Delegates</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped" id="registrationsTable">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Name</th>
                                            <th>Gender</th>
                                            <th>Voice Part</th>
                                            <th>Phone</th>
                                            <th>Email</th>
                                            <th>Society</th>
                                            <th>Circuit</th>
                                            <th>Accommodation</th>
                                            <th>Payment Status</th>
                                            <th>Registration Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $i = 1; foreach ($registrations as $row): ?>
                                        <tr>
                                            <td><?php echo $i++; ?></td>
                                            <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['surname']); ?></td>
                                            <td><?php echo htmlspecialchars(ucfirst($row['gender'] ?? '')); ?></td>
                                            <td><?php echo htmlspecialchars(ucfirst($row['voice_part'] ?? '')); ?></td>
                                            <td><?php echo htmlspecialchars($row['phone'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($row['email'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($row['society_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['circuit_name']); ?></td>
                                            <td>
                                                <?php if (!empty($row['accommodation_required'])): ?>
                                                    <span class="badge bg-warning text-dark">Required</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">No</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><span class="badge bg-info"><?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $row['payment_status']))); ?></span></td>
                                            <td><?php echo date('M d, Y', strtotime($row['registration_date'])); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            if ($.fn.DataTable) {
                $('#registrationsTable').DataTable({
                    pageLength: 25,
                    order: [[10, 'desc']],
                    language: {
                        search: 'Search registrations:',
                        lengthMenu: 'Show _MENU_ entries per page',
                        info: 'Showing _START_ to _END_ of _TOTAL_ registrations'
                    }
                });
            }
        });
    </script>
</body>
</html>
