<?php
/**
 * Diocese Conference Delegates Management
 * GHAMECC Choir Management Platform
 * 
 * This page allows diocese administrators to manage circuit delegates for diocese conferences.
 */

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

// Include database functions
require_once '../config/database.php';

// Require login
requireLogin();

// FIX: Set session role from database if it's empty
if (empty($_SESSION['role']) && isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
    $roleQuery = "SELECT r.role_key FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = $userId";
    $roleResult = fetchRow($roleQuery);
    
    if ($roleResult && isset($roleResult['role_key'])) {
        $_SESSION['role'] = $roleResult['role_key'];
        // Log the role fix
        echo "<div style='background: #d4edda; padding: 10px; margin: 10px; border: 1px solid #c3e6cb;'>";
        echo "<strong>Role Fix Applied:</strong> Session role was empty and has been set to: " . $_SESSION['role'];
        echo "</div>";
    }
}



// Check if user has appropriate permissions
$accessDenied = false;
$accessError = "";
$conferenceError = "";
$successMessage = "";
$errorMessage = "";

// Add circuit roles to the allowed roles
if (!hasRole(['admin', 'diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_dom', 'diocesan_treasurer', 
              'circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer'])) {
    $accessDenied = true;
    $accessError = "You don't have permission to access this page. This page is restricted to diocesan and circuit administrators.";
}

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

// Get conference ID from URL
$conferenceId = isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0;

// Get user's diocese information
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_dom', 'diocesan_treasurer']);
$isCircuitRole = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer']);

// If no conference ID provided, show all diocesan conferences instead of redirecting
if (!$conferenceId) {
    // Continue without redirection - will show a list or empty state
    $conference = null;
} else {
    // Get conference details
    $conference = fetchRow("SELECT c.*, d.name as diocese_name 
                        FROM conferences c
                        JOIN dioceses d ON c.entity_id = d.id
                        WHERE c.id = $conferenceId AND c.type = 'diocese'");

    // If conference not found or not a diocese conference, show message but don't redirect
    if (!$conference) {
        $conferenceError = "Conference not found or not a diocese conference";
    }
}

// Check if user has access to this diocese conference - only if we have a valid conference
if ($conferenceId && $conference && !$isAdmin && !$isDiocesanRole && !$isCircuitRole) {
    $userDiocese = fetchRow("SELECT d.id 
                            FROM dioceses d
                            JOIN users u ON u.diocese_id = d.id
                            WHERE u.id = $userId");
    
    if (!$userDiocese || $userDiocese['id'] != $conference['entity_id']) {
        $accessError = "You don't have access to this diocese conference";
    }
}

// Get circuits for the diocese
$circuits = [];
if ($conference) {
    $dioceseId = $conference['entity_id'];
    $circuits = fetchRows("SELECT * FROM circuits WHERE diocese_id = $dioceseId ORDER BY name");
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$accessDenied) {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($action === 'add_delegate') {
        // Validate inputs
        $circuitId = isset($_POST['circuit_id']) ? (int)$_POST['circuit_id'] : 0;
        $memberId = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
        
        if (!$circuitId || !$memberId) {
            $errorMessage = "Please select both circuit and member";
        } else {
            // Check if member is already registered
            $existingRegistration = fetchRow("SELECT id FROM conference_registrations 
                                            WHERE conference_id = $conferenceId 
                                            AND member_id = $memberId");
            
            if ($existingRegistration) {
                $errorMessage = "This member is already registered as a delegate";
            } else {
                // Register the delegate
                $query = "INSERT INTO conference_registrations (conference_id, member_id, registration_date, status) 
                          VALUES ($conferenceId, $memberId, NOW(), 'confirmed')";
                $result = mysqli_query($conn, $query);
                
                if ($result) {
                    $successMessage = "Delegate added successfully";
                } else {
                    $errorMessage = "Error adding delegate: " . mysqli_error($conn);
                }
            }
        }
    } elseif ($action === 'remove_delegate') {
        $registrationId = isset($_POST['registration_id']) ? (int)$_POST['registration_id'] : 0;
        
        if ($registrationId) {
            $query = "DELETE FROM conference_registrations WHERE id = $registrationId AND conference_id = $conferenceId";
            $result = mysqli_query($conn, $query);
            
            if ($result) {
                $successMessage = "Delegate removed successfully";
            } else {
                $errorMessage = "Error removing delegate: " . mysqli_error($conn);
            }
        }
    }
}

// Get current delegates
$delegates = [];
if ($conferenceId && !$conferenceError) {
    $delegates = fetchRows("SELECT cr.id, m.first_name, m.surname, m.email, m.phone, c.name as circuit_name
                          FROM conference_registrations cr
                          JOIN members m ON cr.member_id = m.id
                          JOIN circuits c ON m.circuit_id = c.id
                          WHERE cr.conference_id = $conferenceId
                          ORDER BY c.name, m.surname, m.first_name");
}

// Page title
$pageTitle = "Manage Diocese Delegates";
?>
<!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>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <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">Manage Diocese Delegates</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>
                        <a href="view.php?id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-eye me-1"></i> View Conference Details
                        </a>
                    </div>
                </div>
                
                <?php if ($accessDenied): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $accessError; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php else: ?>
                    <?php if ($conferenceError): ?>
                    <div class="alert alert-danger">
                        <?php echo $conferenceError; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($accessError): ?>
                    <div class="alert alert-danger">
                        <?php echo $accessError; ?>
                    </div>
                    <?php endif; ?>
                    
                    <div class="alert alert-info">
                        <?php if ($conference): ?>
                        <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> <br>
                        <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?> <br>
                        <strong>Date:</strong> <?php echo date('F d, Y', strtotime($conference['start_date'])); ?> to <?php echo date('F d, Y', strtotime($conference['end_date'])); ?>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($successMessage): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $successMessage; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($errorMessage): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $errorMessage; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-5">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">Add Circuit Delegate</h6>
                                </div>
                                <div class="card-body">
                                    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>">
                                        <input type="hidden" name="action" value="add_delegate">
                                        
                                        <div class="mb-3">
                                            <label for="circuit_id" class="form-label">Circuit <span class="text-danger">*</span></label>
                                            <select class="form-select" id="circuit_id" name="circuit_id" required>
                                                <option value="">Select Circuit</option>
                                                <?php foreach ($circuits as $circuit): ?>
                                                <option value="<?php echo $circuit['id']; ?>">
                                                    <?php echo htmlspecialchars($circuit['name']); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="member_id" class="form-label">Member <span class="text-danger">*</span></label>
                                            <select class="form-select" id="member_id" name="member_id" required disabled>
                                                <option value="">Select Circuit First</option>
                                            </select>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-plus-circle me-1"></i> Add Delegate
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-7">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">Current Delegates</h6>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($delegates)): ?>
                                    <div class="alert alert-info">
                                        No delegates registered yet.
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Circuit</th>
                                                    <th>Contact</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($delegates as $delegate): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?></td>
                                                    <td><?php echo htmlspecialchars($delegate['circuit_name']); ?></td>
                                                    <td>
                                                        <small>
                                                            <i class="fas fa-envelope me-1"></i> <?php echo htmlspecialchars($delegate['email']); ?><br>
                                                            <i class="fas fa-phone me-1"></i> <?php echo htmlspecialchars($delegate['phone']); ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>" class="d-inline" onsubmit="return confirm('Are you sure you want to remove this delegate?');">
                                                            <input type="hidden" name="action" value="remove_delegate">
                                                            <input type="hidden" name="registration_id" value="<?php echo $delegate['id']; ?>">
                                                            <button type="submit" class="btn btn-sm btn-danger">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </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>
    
    <script>
    $(document).ready(function() {
        // Load members when circuit is selected
        $('#circuit_id').change(function() {
            const circuitId = $(this).val();
            const memberSelect = $('#member_id');
            
            // Reset member dropdown
            memberSelect.empty().append('<option value="">Select Member</option>').prop('disabled', true);
            
            if (circuitId) {
                // Fetch members from the selected circuit
                $.ajax({
                    url: '../api/get_circuit_members.php',
                    type: 'GET',
                    data: { circuit_id: circuitId },
                    dataType: 'json',
                    success: function(data) {
                        if (data.length > 0) {
                            $.each(data, function(index, member) {
                                memberSelect.append(
                                    $('<option></option>')
                                        .attr('value', member.id)
                                        .text(member.first_name + ' ' + member.surname)
                                );
                            });
                            memberSelect.prop('disabled', false);
                        } else {
                            memberSelect.append('<option value="">No members found</option>');
                        }
                    },
                    error: function() {
                        memberSelect.append('<option value="">Error loading members</option>');
                    }
                });
            }
        });
    });
    </script>
</body>
</html>
