<?php
/**
 * Conference Role Switcher
 * GHAMECC Choir Management Platform
 * 
 * This file handles switching between different conference roles (diocese/circuit)
 * for the conference management menu
 */

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

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

// Require user to be logged in
requireLogin();

// Check if the user has permission to switch roles
$canSwitchRole = false;

// Admin can always switch roles
if (hasRole(['admin'])) {
    $canSwitchRole = true;
}

// Users with diocese_id can switch to diocese role
if (isset($_SESSION['diocese_id']) && $_SESSION['diocese_id'] > 0) {
    $canSwitchRole = true;
}

// Users with circuit_id can switch to circuit role
if (isset($_SESSION['circuit_id']) && $_SESSION['circuit_id'] > 0) {
    $canSwitchRole = true;
}

// If user can't switch roles, redirect to dashboard
if (!$canSwitchRole) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Process role switch
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['conference_role'])) {
    $role = $_POST['conference_role'];
    
    // Validate role
    if ($role === 'diocese' || $role === 'circuit' || $role === '') {
        // Set the conference view role in session
        $_SESSION['conference_view_as'] = $role;
        
        // Log the role switch
        if (function_exists('logInfo')) {
            logInfo("User switched conference view role", [
                'user_id' => $_SESSION['user_id'],
                'new_role' => $role
            ]);
        }
    }
    
    // Redirect back to the referring page
    $returnUrl = isset($_POST['return_url']) ? $_POST['return_url'] : '../conferences/index.php';
    header("Location: $returnUrl");
    exit;
} else {
    // If accessed directly without POST data, redirect to conferences page
    header("Location: ../conferences/index.php");
    exit;
}
