<?php
/**
 * View Conference
 * GHAMECC Choir Management Platform
 * 
 * This page displays conference details and manages registrations.
 */

// Include authentication functions
require_once '../includes/auth.php';

// Require login
requireLogin();

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

// Check if conference ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit("Invalid conference ID");
}

$conferenceId = (int)$_GET['id'];

// Get conference details
$conference = fetchRow("SELECT c.*, 
                        CASE 
                            WHEN c.type = 'circuit' THEN (SELECT name FROM circuits WHERE id = c.entity_id)
                            WHEN c.type = 'diocese' THEN (SELECT name FROM dioceses WHERE id = c.entity_id)
                            WHEN c.type = 'connexional' THEN 'Connexional Office'
                        END AS entity_name,
                        u.full_name AS created_by_name
                        FROM conferences c
                        LEFT JOIN users u ON c.created_by = u.id
                        WHERE c.id = $conferenceId");

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

// Check if user has permission to view this conference
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);
$hasAccess = false;

if ($isAdmin) {
    $hasAccess = true;
} else {
    // Check if user is associated with the conference's circuit/diocese
    if ($conference['type'] === 'circuit') {
        $hasAccess = (bool)fetchRow("SELECT 1 FROM circuit_roles WHERE user_id = $userId AND circuit_id = {$conference['entity_id']}");
    } else if ($conference['type'] === 'diocese') {
        $hasAccess = (bool)fetchRow("SELECT 1 FROM diocese_roles WHERE user_id = $userId AND diocese_id = {$conference['entity_id']}");
    } else if ($conference['type'] === 'connexional') {
        $hasAccess = (bool)fetchRow("SELECT 1 FROM users WHERE id = $userId AND role_key = 'admin'");
    }
    
    // Check if user is registered for this conference
    if (!$hasAccess) {
        $hasAccess = (bool)fetchRow("SELECT 1 FROM conference_registrations WHERE conference_id = $conferenceId AND member_id IN (SELECT id FROM members WHERE user_id = $userId)");
    }
}

if (!$hasAccess) {
    header("Location: index.php");
    exit("You do not have permission to view this conference");
}

// Get registration count
$registrationCount = fetchValue("SELECT COUNT(*) FROM conference_registrations WHERE conference_id = $conferenceId");

// Get session count
$sessionCount = fetchValue("SELECT COUNT(*) FROM conference_sessions WHERE conference_id = $conferenceId");

// Check if user can edit/delete this conference
$canEdit = $isAdmin || 
           ($conference['type'] === 'circuit' && fetchRow("SELECT 1 FROM circuit_roles WHERE user_id = $userId AND circuit_id = {$conference['entity_id']} AND role IN ('chairman', 'secretary')")) ||
           ($conference['type'] === 'diocese' && fetchRow("SELECT 1 FROM diocese_roles WHERE user_id = $userId AND diocese_id = {$conference['entity_id']} AND role IN ('chairman', 'secretary')"));

// Check if user can manage registrations
$canManageRegistrations = $canEdit;

// Check if user can manage sessions
$canManageSessions = $canEdit;

// Check if current user is registered
$memberId = fetchValue("SELECT id FROM members WHERE user_id = $userId");
$isRegistered = $memberId ? (bool)fetchRow("SELECT 1 FROM conference_registrations WHERE conference_id = $conferenceId AND member_id = $memberId") : false;

// Get registration status message
$registrationMessage = '';
$registrationBtnText = 'Register Now';
$registrationBtnClass = 'btn-primary';
$registrationBtnIcon = 'fa-user-plus';
$canRegister = false;

if ($isRegistered) {
    $registrationMessage = '<div class="alert alert-success mb-3"><i class="fas fa-check-circle me-2"></i> You are registered for this conference.</div>';
    $registrationBtnText = 'View My Registration';
    $registrationBtnClass = 'btn-success';
    $registrationBtnIcon = 'fa-id-card';
} else {
    $today = date('Y-m-d');
    if ($conference['registration_deadline'] < $today) {
        $registrationMessage = '<div class="alert alert-warning mb-3"><i class="fas fa-exclamation-triangle me-2"></i> Registration deadline has passed.</div>';
    } else if ($conference['status'] === 'cancelled') {
        $registrationMessage = '<div class="alert alert-danger mb-3"><i class="fas fa-ban me-2"></i> This conference has been cancelled.</div>';
    } else if ($conference['status'] === 'completed') {
        $registrationMessage = '<div class="alert alert-info mb-3"><i class="fas fa-info-circle me-2"></i> This conference has already taken place.</div>';
    } else {
        $canRegister = true;
        if ($conference['max_participants'] && $registrationCount >= $conference['max_participants']) {
            $registrationMessage = '<div class="alert alert-warning mb-3"><i class="fas fa-exclamation-triangle me-2"></i> Registration is full. Maximum participants reached.</div>';
            $canRegister = false;
        }
    }
}

// Success message for creation/update
$successMessage = '';
if (isset($_GET['created']) && $_GET['created'] == 1) {
    $successMessage = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> Conference created successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                      </div>';
} else if (isset($_GET['updated']) && $_GET['updated'] == 1) {
    $successMessage = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> Conference updated successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                      </div>';
}

// Format dates for display
$startDate = date('F j, Y', strtotime($conference['start_date']));
$endDate = date('F j, Y', strtotime($conference['end_date']));
$registrationDeadline = date('F j, Y', strtotime($conference['registration_deadline']));

// Get status badge
$statusBadge = '';
switch ($conference['status']) {
    case 'upcoming':
        $statusBadge = '<span class="badge bg-primary">Upcoming</span>';
        break;
    case 'ongoing':
        $statusBadge = '<span class="badge bg-success">Ongoing</span>';
        break;
    case 'completed':
        $statusBadge = '<span class="badge bg-secondary">Completed</span>';
        break;
    case 'cancelled':
        $statusBadge = '<span class="badge bg-danger">Cancelled</span>';
        break;
    default:
        $statusBadge = '<span class="badge bg-info">Unknown</span>';
}

// Get type badge
$typeBadge = '';
switch ($conference['type']) {
    case 'circuit':
        $typeBadge = '<span class="badge bg-info">Circuit</span>';
        break;
    case 'diocese':
        $typeBadge = '<span class="badge bg-warning text-dark">Diocese</span>';
        break;
    case 'connexional':
        $typeBadge = '<span class="badge bg-danger">Connexional</span>';
        break;
    default:
        $typeBadge = '<span class="badge bg-secondary">Unknown</span>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($conference['name']); ?> - GHAMECC Choir Management</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.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</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"><?php echo htmlspecialchars($conference['name']); ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <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>
                        <?php if ($canEdit): ?>
                        <a href="edit.php?id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-2">
                            <i class="fas fa-edit me-1"></i> Edit Conference
                        </a>
                        <?php endif; ?>
                        <?php if ($canManageSessions): ?>
                        <a href="sessions.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-info me-2">
                            <i class="fas fa-calendar-alt me-1"></i> Manage Sessions
                        </a>
                        <?php endif; ?>
                        <?php if ($canManageRegistrations): ?>
                        <a href="registrations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-success">
                            <i class="fas fa-users me-1"></i> Manage Registrations
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php echo $successMessage; ?>
                
                <div class="row mb-4">
                    <div class="col-md-8">
                        <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">Conference Details</h6>
                                <div>
                                    <?php echo $statusBadge; ?> <?php echo $typeBadge; ?>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="mb-4">
                                    <h5><?php echo htmlspecialchars($conference['name']); ?></h5>
                                    <p class="text-muted">
                                        <i class="fas fa-map-marker-alt me-2"></i> <?php echo htmlspecialchars($conference['venue']); ?>
                                    </p>
                                </div>
                                
                                <div class="mb-4">
                                    <h6 class="text-primary">Description</h6>
                                    <p><?php echo nl2br(htmlspecialchars($conference['description'])); ?></p>
                                </div>
                                
                                <div class="row mb-4">
                                    <div class="col-md-4">
                                        <h6 class="text-primary">Start Date</h6>
                                        <p><i class="far fa-calendar-alt me-2"></i> <?php echo $startDate; ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <h6 class="text-primary">End Date</h6>
                                        <p><i class="far fa-calendar-alt me-2"></i> <?php echo $endDate; ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <h6 class="text-primary">Registration Deadline</h6>
                                        <p><i class="far fa-clock me-2"></i> <?php echo $registrationDeadline; ?></p>
                                    </div>
                                </div>
                                
                                <div class="row mb-4">
                                    <div class="col-md-4">
                                        <h6 class="text-primary">Entity</h6>
                                        <p><i class="fas fa-sitemap me-2"></i> <?php echo htmlspecialchars($conference['entity_name']); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <h6 class="text-primary">Registration Fee</h6>
                                        <p><i class="fas fa-money-bill-wave me-2"></i> GH₵<?php echo number_format($conference['fee_amount'], 2); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <h6 class="text-primary">Maximum Participants</h6>
                                        <p><i class="fas fa-users me-2"></i> <?php echo $conference['max_participants'] ? number_format($conference['max_participants']) : 'Unlimited'; ?></p>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6 class="text-primary">Created By</h6>
                                        <p><i class="fas fa-user me-2"></i> <?php echo htmlspecialchars($conference['created_by_name']); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($sessionCount > 0): ?>
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Conference Sessions</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="sessionsTable" width="100%" cellspacing="0">
                                        <thead>
                                            <tr>
                                                <th>Session Name</th>
                                                <th>Date</th>
                                                <th>Start Time</th>
                                                <th>End Time</th>
                                                <th>Location</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $sessions = fetchRows("SELECT * FROM conference_sessions WHERE conference_id = $conferenceId ORDER BY session_date, start_time");
                                            if ($sessions) {
                                                foreach ($sessions as $session) {
                                                    $sessionDate = date('F j, Y', strtotime($session['session_date']));
                                                    $startTime = date('h:i A', strtotime($session['start_time']));
                                                    $endTime = date('h:i A', strtotime($session['end_time']));
                                                    echo "<tr>
                                                            <td>" . htmlspecialchars($session['name']) . "</td>
                                                            <td>$sessionDate</td>
                                                            <td>$startTime</td>
                                                            <td>$endTime</td>
                                                            <td>" . htmlspecialchars($session['location']) . "</td>
                                                          </tr>";
                                                }
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Registration</h6>
                            </div>
                            <div class="card-body">
                                <div class="text-center mb-4">
                                    <h4 class="font-weight-bold text-primary"><?php echo number_format($registrationCount); ?></h4>
                                    <p class="text-muted">Registered Participants</p>
                                    <?php if ($conference['max_participants']): ?>
                                    <div class="progress mb-2">
                                        <?php $percentage = min(100, ($registrationCount / $conference['max_participants']) * 100); ?>
                                        <div class="progress-bar bg-primary" role="progressbar" style="width: <?php echo $percentage; ?>%" 
                                             aria-valuenow="<?php echo $percentage; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                    </div>
                                    <p class="text-muted small"><?php echo $registrationCount; ?> of <?php echo $conference['max_participants']; ?> spots filled</p>
                                    <?php endif; ?>
                                </div>
                                
                                <?php echo $registrationMessage; ?>
                                
                                <div class="d-grid gap-2">
                                    <?php if ($isRegistered): ?>
                                    <a href="my_registration.php?conference_id=<?php echo $conferenceId; ?>" class="btn <?php echo $registrationBtnClass; ?>">
                                        <i class="fas <?php echo $registrationBtnIcon; ?> me-2"></i> <?php echo $registrationBtnText; ?>
                                    </a>
                                    <?php elseif ($canRegister): ?>
                                    <a href="register.php?conference_id=<?php echo $conferenceId; ?>" class="btn <?php echo $registrationBtnClass; ?>">
                                        <i class="fas <?php echo $registrationBtnIcon; ?> me-2"></i> <?php echo $registrationBtnText; ?>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Quick Info</h6>
                            </div>
                            <div class="card-body">
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Status
                                        <span><?php echo $statusBadge; ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Type
                                        <span><?php echo $typeBadge; ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Duration
                                        <?php
                                        $start = new DateTime($conference['start_date']);
                                        $end = new DateTime($conference['end_date']);
                                        $interval = $start->diff($end);
                                        $days = $interval->days + 1;
                                        ?>
                                        <span class="badge bg-secondary rounded-pill"><?php echo $days; ?> day<?php echo $days > 1 ? 's' : ''; ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Sessions
                                        <span class="badge bg-secondary rounded-pill"><?php echo $sessionCount; ?></span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Days Until Start
                                        <?php
                                        $today = new DateTime();
                                        $start = new DateTime($conference['start_date']);
                                        $daysUntil = $today > $start ? 0 : $today->diff($start)->days;
                                        $badgeClass = $daysUntil <= 7 ? 'bg-danger' : ($daysUntil <= 30 ? 'bg-warning text-dark' : 'bg-info');
                                        ?>
                                        <span class="badge <?php echo $badgeClass; ?> rounded-pill"><?php echo $daysUntil; ?> day<?php echo $daysUntil != 1 ? 's' : ''; ?></span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </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>
    <!-- DataTables JS -->
    <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() {
            // Initialize DataTables
            $('#sessionsTable').DataTable({
                responsive: true,
                order: [[1, 'asc'], [2, 'asc']]
            });
        });
    </script>
</body>
</html>
