<?php
/**
 * Conference Selection Page
 * GHAMECC Choir Management Platform
 */

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit("Please log in");
}

// Include database connection
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

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

// Get target page from URL
$targetPage = isset($_GET['target']) ? $_GET['target'] : 'society_conference_delegates';

// Get user's information
$userId = $_SESSION['user_id'];
$userRole = $_SESSION['role'];



// Check user roles
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_treasurer']);
$isCircuitRole = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer']);
$isSocietyRole = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);


// Get user's society if they have a society role
$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'];
    }

}

// Get user's circuit if they have a circuit role
$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'];
    }
 
}

// Get user's diocese if they have a diocesan role
$userDioceseId = 0;
if ($isDiocesanRole) {
    $userDioceseQuery = "SELECT diocese_id FROM users WHERE id = $userId";
    $userDioceseResult = fetchRow($userDioceseQuery);
    if ($userDioceseResult && isset($userDioceseResult['diocese_id'])) {
        $userDioceseId = $userDioceseResult['diocese_id'];
    }
 
}

// Get available conferences based on user role
$conferences = [];

if ($isAdmin) {
    // Admin can see all conferences
    $conferencesQuery = "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.type = 'circuit' OR c.type = 'diocese')
                           ORDER BY c.start_date DESC";
    $conferences = fetchRows($conferencesQuery);
 
} elseif ($isDiocesanRole && $userDioceseId > 0) {
    // Diocesan roles can see diocese conferences for their diocese
    $conferencesQuery = "SELECT c.*, 
                           d.name as entity_name,
                           c.type as conference_type
                           FROM conferences c
                           JOIN dioceses d ON c.entity_id = d.id
                           WHERE c.type = 'diocese' AND c.entity_id = $userDioceseId
                           ORDER BY c.start_date DESC";
    $conferences = fetchRows($conferencesQuery);

} elseif ($isCircuitRole && $userCircuitId > 0) {
    // Circuit roles can see circuit conferences for their circuit
    // Also get the diocese ID for this circuit to show diocese conferences
    $circuitInfo = fetchRow("SELECT c.id, c.diocese_id 
                            FROM circuits c 
                            WHERE c.id = $userCircuitId");
    
    if ($circuitInfo) {
        $dioceseId = $circuitInfo['diocese_id'];
        
        // Modified query to show circuit conferences for user's circuit
        // and diocese conferences for user's diocese
        $conferencesQuery = "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.type = 'circuit' AND c.entity_id = $userCircuitId)
                                  OR (c.type = 'diocese' AND c.entity_id = $dioceseId)
                               ORDER BY c.start_date DESC";
        $conferences = fetchRows($conferencesQuery);
    }

} elseif ($isSocietyRole && $userSocietyId > 0) {
    // Society roles can see conferences for their circuit and diocese
    $societyInfo = fetchRow("SELECT s.circuit_id, c.diocese_id 
                            FROM societies s 
                            JOIN circuits c ON s.circuit_id = c.id 
                            WHERE s.id = $userSocietyId");
    
   
    
    if ($societyInfo) {
        $circuitId = $societyInfo['circuit_id'];
        $dioceseId = $societyInfo['diocese_id'];
        
      
        
        // Check if the diocese conference exists
        $dioceseConfCheck = fetchRow("SELECT COUNT(*) as count FROM conferences 
                                     WHERE type = 'diocese' AND entity_id = $dioceseId");
     
        // Modified query to show circuit conferences for user's circuit
        // and diocese conferences for user's diocese
        $conferencesQuery = "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.type = 'circuit' AND c.entity_id = $circuitId)
                                  OR (c.type = 'diocese' AND c.entity_id = $dioceseId)
                               ORDER BY c.start_date DESC";
        $conferences = fetchRows($conferencesQuery);
     
    }
}





// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['conference_id'])) {
    $conferenceId = (int)$_POST['conference_id'];
    
    if ($conferenceId > 0) {
        // Get the target page from URL parameter
        $targetPage = isset($_POST['target']) ? $_POST['target'] : 'society_conference_delegates';
        
        // Validate the target page to prevent open redirect
        $allowedTargets = [
            'society_delegates', 
            'society_conference_delegates', 
            'conference_attendance', 
            'conference_registrations',
            'circuit_conference_delegates',
            'diocese_conference_delegates',
            'accommodations',
            'delegate_accommodation',
            'room_assignments',
            'accommodation_types',
            'check_in_out'
        ];
        
        if (!in_array($targetPage, $allowedTargets)) {
            $targetPage = 'society_conference_delegates';
        }
        
        // Map society_delegates to society_conference_delegates
        if ($targetPage === 'society_delegates') {
            $targetPage = 'society_conference_delegates';
        }
        
        // Special handling for accommodations target
        if ($targetPage === 'accommodations') {
            header("Location: conference_accommodations.php?conference_id=$conferenceId");
            exit;
        }
        
        // Special handling for delegate accommodation target
        if ($targetPage === 'delegate_accommodation') {
            error_log("Redirecting to delegate_accommodations_list.php with conference_id=$conferenceId");
            header("Location: delegate_accommodations_list.php?conference_id=$conferenceId");
            exit;
        }
        
        // Special handling for room assignments target
        if ($targetPage === 'room_assignments') {
            header("Location: room_assignments.php?conference_id=$conferenceId");
            exit;
        }
        
        // Special handling for accommodation types target
        if ($targetPage === 'accommodation_types') {
            header("Location: accommodation_types.php?conference_id=$conferenceId");
            exit;
        }
        
        // Special handling for check-in/out target
        if ($targetPage === 'check_in_out') {
            header("Location: check_in_out.php?conference_id=$conferenceId");
            exit;
        }
        
        // Redirect to the target page with the selected conference ID
        // Since we're already in the conferences directory, we don't need to add it
        header("Location: $targetPage.php?conference_id=$conferenceId");
        exit;
    }
}

// Page title
$pageTitle = "Select Conference";
?>

<!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>
    
    <?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">Select Conference</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>
                    </div>
                </div>
                
                <?php if (empty($conferences)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i> No conferences available for your role.
                </div>
                <?php else: ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Select a Conference</h6>
                    </div>
                    <div class="card-body">
                        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>?target=<?php echo htmlspecialchars($targetPage); ?>">
                            <input type="hidden" name="target" value="<?php echo htmlspecialchars($targetPage); ?>">
                            <div class="mb-3">
                                <label for="conference_id" class="form-label">Conference <span class="text-danger">*</span></label>
                                <select class="form-select" id="conference_id" name="conference_id" required>
                                    <option value="">Select Conference</option>
                                    <?php foreach ($conferences as $conf): ?>
                                    <option value="<?php echo $conf['id']; ?>">
                                        <?php echo htmlspecialchars($conf['name'] . ' (' . ucfirst($conf['conference_type']) . ': ' . $conf['entity_name'] . ')'); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-check me-1"></i> Continue
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <?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>
