<?php
/**
 * Conference Management
 * GHAMECC Choir Management Platform
 * 
 * This page lists all conferences and allows administrators to manage them.
 */

// Include necessary files
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Require login
requireLogin();

// Check if user has appropriate permissions
if (!hasRole(['admin', 'diocesan_chairman', 'diocesan_secretary']) && 
    !fetchRow("SELECT * FROM circuit_roles WHERE user_id = {$_SESSION['user_id']} AND role IN ('chairman', 'secretary')") &&
    !fetchRow("SELECT * FROM diocese_roles WHERE user_id = {$_SESSION['user_id']} AND role IN ('chairman', 'secretary')")) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

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

// Process conference deletion if requested
if (isset($_POST['delete_conference']) && isset($_POST['conference_id'])) {
    $conferenceId = (int)$_POST['conference_id'];
    
    // Check if user has permission to delete this conference
    $conference = fetchRow("SELECT * FROM conferences WHERE id = $conferenceId");
    if ($conference) {
        $canDelete = false;
        
        if (hasRole(['admin'])) {
            $canDelete = true;
        } else if ($conference['type'] == 'circuit') {
            $circuitRole = fetchRow("SELECT * FROM circuit_roles WHERE user_id = {$_SESSION['user_id']} AND circuit_id = {$conference['entity_id']} AND role IN ('chairman', 'secretary')");
            $canDelete = !empty($circuitRole);
        } else if ($conference['type'] == 'diocese') {
            $dioceseRole = fetchRow("SELECT * FROM diocese_roles WHERE user_id = {$_SESSION['user_id']} AND diocese_id = {$conference['entity_id']} AND role IN ('chairman', 'secretary')");
            $canDelete = !empty($dioceseRole);
        }
        
        if ($canDelete) {
            // Check if there are registrations
            $registrations = fetchRow("SELECT COUNT(*) as count FROM conference_registrations WHERE conference_id = $conferenceId");
            
            if ($registrations && $registrations['count'] > 0) {
                $deleteMessage = "Cannot delete conference. There are {$registrations['count']} registrations associated with it.";
                $deleteStatus = "error";
            } else {
                // Delete conference sessions first (cascade will handle attendance)
                executeQuery("DELETE FROM conference_sessions WHERE conference_id = $conferenceId");
                
                // Delete the conference
                $result = executeQuery("DELETE FROM conferences WHERE id = $conferenceId");
                
                if ($result) {
                    $deleteMessage = "Conference deleted successfully.";
                    $deleteStatus = "success";
                } else {
                    $deleteMessage = "Error deleting conference.";
                    $deleteStatus = "error";
                }
            }
        } else {
            $deleteMessage = "You do not have permission to delete this conference.";
            $deleteStatus = "error";
        }
    } else {
        $deleteMessage = "Conference not found.";
        $deleteStatus = "error";
    }
}

// Get user's roles and associated entities
$userId = $_SESSION['user_id'];
$userCircuits = [];
$userDioceses = [];

// Get user's circuit roles
$userCircuits = [];
if (hasRole('admin')) {
    // Admin can see all circuits
    $circuitRoles = fetchRows("SELECT c.id as circuit_id, c.name 
                              FROM circuits c");
} elseif (hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'])) {
    // Circuit-level users can see their own circuit
    $circuitRoles = fetchRows("SELECT c.id as circuit_id, c.name 
                              FROM circuits c 
                              JOIN users u ON u.circuit_id = c.id 
                              WHERE u.id = $userId");
} else {
    $circuitRoles = [];
}

if ($circuitRoles) {
    foreach ($circuitRoles as $role) {
        $userCircuits[$role['circuit_id']] = $role['name'];
    }
}

// Get user's diocese roles
$userDioceses = [];
if (hasRole('admin')) {
    // Admin can see all dioceses
    $dioceseRoles = fetchRows("SELECT d.id as diocese_id, d.name 
                              FROM dioceses d");
} elseif (hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer'])) {
    // Diocese-level users can see their own diocese
    $dioceseRoles = fetchRows("SELECT d.id as diocese_id, d.name 
                              FROM dioceses d 
                              JOIN users u ON u.diocese_id = d.id 
                              WHERE u.id = $userId");
} else {
    $dioceseRoles = [];
}

if ($dioceseRoles) {
    foreach ($dioceseRoles as $role) {
        $userDioceses[$role['diocese_id']] = $role['name'];
    }
}

// Build query based on user's roles
$query = "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 creator_name,
          (SELECT COUNT(*) FROM conference_registrations WHERE conference_id = c.id) as registration_count
          FROM conferences c
          JOIN users u ON c.created_by = u.id
          WHERE 1=1";

// Filter by user's permissions unless they're an admin
if (!hasRole(['admin'])) {
    $circuitIds = array_keys($userCircuits);
    $dioceseIds = array_keys($userDioceses);
    
    $conditions = [];
    
    if (!empty($circuitIds)) {
        $circuitIdsStr = implode(',', $circuitIds);
        $conditions[] = "(c.type = 'circuit' AND c.entity_id IN ($circuitIdsStr))";
    }
    
    if (!empty($dioceseIds)) {
        $dioceseIdsStr = implode(',', $dioceseIds);
        $conditions[] = "(c.type = 'diocese' AND c.entity_id IN ($dioceseIdsStr))";
    }
    
    if (!empty($conditions)) {
        $query .= " AND (" . implode(' OR ', $conditions) . ")";
    } else {
        // If user has no circuit or diocese roles, they shouldn't see any conferences
        $query .= " AND 0=1";
    }
}

$query .= " ORDER BY c.start_date DESC";

// Get conferences
$conferences = fetchRows($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conferences - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- 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 rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- 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">Conference Management</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="create.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus me-1"></i> Create New Conference
                        </a>
                    </div>
                </div>
                
                <?php if (isset($deleteMessage)): ?>
                    <div class="alert alert-<?php echo $deleteStatus === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                        <?php echo $deleteMessage; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <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">All Conferences</h6>
                    </div>
                    <div class="card-body">
                        <?php if (empty($conferences)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-alt fa-3x mb-3"></i>
                                <p>No conferences found. Click "Create New Conference" to add one.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-bordered" id="conferencesTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Type</th>
                                            <th>Entity</th>
                                            <th>Dates</th>
                                            <th>Registration Deadline</th>
                                            <th>Status</th>
                                            <th>Registrations</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($conferences as $conference): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($conference['name']); ?></td>
                                                <td><?php echo ucfirst($conference['type']); ?></td>
                                                <td><?php echo htmlspecialchars($conference['entity_name']); ?></td>
                                                <td>
                                                    <?php 
                                                    echo date('M d, Y', strtotime($conference['start_date'])); 
                                                    echo ' to '; 
                                                    echo date('M d, Y', strtotime($conference['end_date'])); 
                                                    ?>
                                                </td>
                                                <td><?php echo date('M d, Y', strtotime($conference['registration_deadline'])); ?></td>
                                                <td>
                                                    <?php
                                                    $statusClass = '';
                                                    switch ($conference['status']) {
                                                        case 'upcoming':
                                                            $statusClass = 'bg-info';
                                                            break;
                                                        case 'ongoing':
                                                            $statusClass = 'bg-primary';
                                                            break;
                                                        case 'completed':
                                                            $statusClass = 'bg-success';
                                                            break;
                                                        case 'cancelled':
                                                            $statusClass = 'bg-danger';
                                                            break;
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $statusClass; ?>">
                                                        <?php echo ucfirst($conference['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <a href="registrations.php?id=<?php echo $conference['id']; ?>">
                                                        <?php echo $conference['registration_count']; ?> registrations
                                                    </a>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="view.php?id=<?php echo $conference['id']; ?>" class="btn btn-info">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="edit.php?id=<?php echo $conference['id']; ?>" class="btn btn-primary">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="sessions.php?conference_id=<?php echo $conference['id']; ?>" class="btn btn-secondary">
                                                            <i class="fas fa-list"></i> Sessions
                                                        </a>
                                                        <?php if ($conference['registration_count'] == 0): ?>
                                                            <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $conference['id']; ?>">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- Delete Modal -->
                                                    <div class="modal fade" id="deleteModal<?php echo $conference['id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $conference['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="deleteModalLabel<?php echo $conference['id']; ?>">Confirm Deletion</h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <div class="modal-body">
                                                                    Are you sure you want to delete the conference "<?php echo htmlspecialchars($conference['name']); ?>"?
                                                                    This action cannot be undone.
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                    <form method="post">
                                                                        <input type="hidden" name="conference_id" value="<?php echo $conference['id']; ?>">
                                                                        <button type="submit" name="delete_conference" class="btn btn-danger">Delete</button>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </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() {
            $('#conferencesTable').DataTable({
                order: [[3, 'desc']], // Sort by date column by default
                language: {
                    search: "Search conferences:",
                    lengthMenu: "Show _MENU_ conferences per page",
                    info: "Showing _START_ to _END_ of _TOTAL_ conferences",
                    infoEmpty: "Showing 0 to 0 of 0 conferences",
                    infoFiltered: "(filtered from _MAX_ total conferences)"
                }
            });
        });
    </script>
</body>
</html>
