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

require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../includes/sms_functions.php';

// Require login
requireLogin();

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

// Basic variables
$pageTitle = "Manage Society Delegates";
$userId = $_SESSION['user_id'];
$isSocietyRole = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);

// Check if user has appropriate permissions (only society roles)
if (!hasRole(['choirmaster', 'society_secretary', 'society_treasurer'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's society
$userSocietyId = 0;
if ($isSocietyRole) {
    $userSocietyQuery = "SELECT u.society_id, s.circuit_id, c.diocese_id 
                        FROM users u
                        LEFT JOIN societies s ON u.society_id = s.id
                        LEFT JOIN circuits c ON s.circuit_id = c.id
                        WHERE u.id = $userId";
    $userSocietyResult = fetchRow($userSocietyQuery);
    if ($userSocietyResult && isset($userSocietyResult['society_id'])) {
        $userSocietyId = $userSocietyResult['society_id'];
        $_SESSION['society_id'] = $userSocietyId;
        
        // Set circuit and diocese IDs in session if available
        if (isset($userSocietyResult['circuit_id'])) {
            $_SESSION['circuit_id'] = $userSocietyResult['circuit_id'];
        }
        
        if (isset($userSocietyResult['diocese_id'])) {
            $_SESSION['diocese_id'] = $userSocietyResult['diocese_id'];
        }
    }
}

// If no society ID found, redirect to index
if (!$userSocietyId) {
    header("Location: ../index.php");
    exit("No society assigned to your account");
}

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

// If no conference ID provided, redirect to conferences list
if (!$conferenceId) {
    header("Location: index.php");
    exit("No conference selected");
}

// Get conference details - check for both circuit and diocese conferences
$conference = fetchRow("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.id = $conferenceId AND (c.type = 'circuit' OR c.type = 'diocese')");

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

// Get society information
$society = fetchRow("SELECT s.*, c.name as circuit_name, d.name as diocese_name, d.id as diocese_id 
                    FROM societies s 
                    JOIN circuits c ON s.circuit_id = c.id
                    JOIN dioceses d ON c.diocese_id = d.id
                    WHERE s.id = $userSocietyId");

if (!$society) {
    header("Location: ../index.php");
    exit("Society information not found");
}

// Check if society has access to this conference
$hasAccess = false;

// For circuit conferences, check if society belongs to the conference's circuit
if ($conference['conference_type'] == 'circuit' && $society['circuit_id'] == $conference['entity_id']) {
    $hasAccess = true;
}
// For diocese conferences, check if society belongs to the conference's diocese
elseif ($conference['conference_type'] == 'diocese' && $society['diocese_id'] == $conference['entity_id']) {
    $hasAccess = true;
}

// Redirect if no access
if (!$hasAccess) {
    header("Location: index.php");
    exit("You don't have access to this conference");
}

// Get all societies in this circuit or diocese based on user role
if (hasRole(['admin', 'manager'])) {
    // Admin and manager can see all societies
    $societies = fetchRows("SELECT id, name FROM societies ORDER BY name");
} else {
    $userRole = $_SESSION['role'] ?? '';
    $userSocietyId = $_SESSION['society_id'] ?? null;
    $userCircuitId = $_SESSION['circuit_id'] ?? null;
    $userDioceseId = $_SESSION['diocese_id'] ?? null;
    
    $societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
    $circuitRoles = ['circuit_secretary', 'circuit_treasurer'];
    $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    
    if (in_array($userRole, $societyRoles) && !empty($userSocietyId)) {
        // Society-level roles can only see their society
        $societies = fetchRows("SELECT id, name FROM societies WHERE id = ? ORDER BY name", [$userSocietyId]);
    } elseif (in_array($userRole, $circuitRoles) && !empty($userCircuitId)) {
        // Circuit-level roles can see societies in their circuit
        $societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name", [$userCircuitId]);
    } elseif (in_array($userRole, $dioceseRoles) && !empty($userDioceseId)) {
        // Diocese-level roles can see societies in their diocese
        $societies = fetchRows("SELECT s.id, s.name 
                              FROM societies s 
                              JOIN circuits c ON s.circuit_id = c.id 
                              WHERE c.diocese_id = ? 
                              ORDER BY s.name", [$userDioceseId]);
    } else {
        // If no specific role or missing IDs, fall back to conference-based filtering
        if ($conference['conference_type'] == 'circuit') {
            $societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name", [$conference['entity_id']]);
        } elseif ($conference['conference_type'] == 'diocese') {
            $societies = fetchRows("SELECT s.id, s.name 
                                  FROM societies s 
                                  JOIN circuits c ON s.circuit_id = c.id 
                                  WHERE c.diocese_id = ? 
                                  ORDER BY s.name", [$conference['entity_id']]);
        } else {
            $societies = [];
        }
    }
}

// Process form submission for adding delegates
$successMessage = '';
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($action === 'add_delegate') {
        $societyId = isset($_POST['society_id']) ? (int)$_POST['society_id'] : 0;
        $memberId = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
        
        // For society roles, override the society ID with their own society ID
        if ($isSocietyRole && $userSocietyId > 0) {
            $societyId = $userSocietyId;
        }
        
        if (!$societyId || !$memberId) {
            $errorMessage = "Please select both society 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, attendance_status, created_by) 
                          VALUES ($conferenceId, $memberId, NOW(), 'confirmed', $userId)";
                $result = mysqli_query($conn, $query);
                
                if ($result) {
                    $successMessage = "Delegate added successfully";
                    
                    // Send SMS notification to the delegate
                    $conferenceDetails = fetchRow("SELECT title, start_date FROM conferences WHERE id = $conferenceId");
                    if ($conferenceDetails) {
                        $conferenceName = $conferenceDetails['title'];
                        $conferenceDate = date('j M Y', strtotime($conferenceDetails['start_date']));
                        
                        // Send SMS notification
                        $smsResult = sendDelegateNotificationSMS($memberId, $conferenceId, $conferenceName, $conferenceDate);
                        
                        // Add SMS status to success message
                        if (isset($smsResult['status']) && $smsResult['status'] === 'success') {
                            $successMessage .= " and SMS notification sent to delegate";
                        } else {
                            $successMessage .= " but SMS notification failed";
                            // Log the error but don't show to user
                            logError('SMS notification failed', [
                                'member_id' => $memberId,
                                'conference_id' => $conferenceId,
                                'response' => $smsResult
                            ]);
                        }
                    }
                } else {
                    $errorMessage = "Error adding delegate: " . mysqli_error($conn);
                }
            }
        }
    } elseif ($action === 'remove_delegate') {
        $registrationId = isset($_POST['registration_id']) ? (int)$_POST['registration_id'] : 0;
        
        if ($registrationId) {
            // For society roles, ensure they can only remove delegates from their own society
            if ($isSocietyRole && $userSocietyId > 0) {
                $canRemove = fetchRow("SELECT cr.id 
                                      FROM conference_registrations cr
                                      JOIN members m ON cr.member_id = m.id
                                      WHERE cr.id = $registrationId 
                                      AND m.society_id = $userSocietyId");
                
                if (!$canRemove) {
                    $errorMessage = "You can only remove delegates from your own society";
                    $registrationId = 0;
                }
            }
            
            if ($registrationId) {
                $query = "DELETE FROM conference_registrations WHERE id = $registrationId";
                $result = mysqli_query($conn, $query);
                
                if ($result) {
                    $successMessage = "Delegate removed successfully";
                } else {
                    $errorMessage = "Error removing delegate: " . mysqli_error($conn);
                }
            }
        }
    }
}

// Get current delegates
$delegates = [];
if ($isSocietyRole && $userSocietyId > 0) {
    // Society roles can only see delegates from their own society
    $delegates = fetchRows("SELECT cr.id, cr.registration_date, cr.notes, 
                          m.first_name, m.last_name, m.email, m.contact_number as phone, 
                          s.name as society_name
                          FROM conference_registrations cr
                          JOIN members m ON cr.member_id = m.id
                          JOIN societies s ON m.society_id = s.id
                          WHERE cr.conference_id = $conferenceId
                          AND m.society_id = $userSocietyId
                          ORDER BY m.last_name, m.first_name");
} else {
    // Circuit roles and admins can see all delegates for the conference
    $delegates = fetchRows("SELECT cr.id, cr.registration_date, cr.notes, 
                          m.first_name, m.last_name, m.email, m.contact_number as phone, 
                          s.name as society_name
                          FROM conference_registrations cr
                          JOIN members m ON cr.member_id = m.id
                          JOIN societies s ON m.society_id = s.id
                          WHERE cr.conference_id = $conferenceId
                          ORDER BY s.name, m.last_name, m.first_name");
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Society Delegates - 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">
    <!-- 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">Manage Society 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>
                
                <div class="alert alert-info">
                    <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> <br>
                    <strong><?php echo ucfirst($conference['conference_type']); ?>:</strong> <?php echo htmlspecialchars($conference['entity_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'])); ?>
                </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 Society 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="society_id" class="form-label">Society <span class="text-danger">*</span></label>
                                        <?php if ($isSocietyRole && $userSocietyId > 0): ?>
                                            <?php 
                                            // Get society name for display
                                            $societyName = '';
                                            foreach ($societies as $s) {
                                                if ($s['id'] == $userSocietyId) {
                                                    $societyName = $s['name'];
                                                    break;
                                                }
                                            }
                                            ?>
                                            <select class="form-select" id="society_id" name="society_id" required>
                                                <option value="<?php echo $userSocietyId; ?>" selected>
                                                    <?php echo htmlspecialchars($societyName); ?>
                                                </option>
                                            </select>
                                        <?php else: ?>
                                        <select class="form-select" id="society_id" name="society_id" required>
                                            <option value="">Select Society</option>
                                            <?php foreach ($societies as $society): ?>
                                            <option value="<?php echo $society['id']; ?>">
                                                <?php echo htmlspecialchars($society['name']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php endif; ?>
                                    </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 <?php echo (!$isSocietyRole) ? 'disabled' : ''; ?>>
                                            <option value="">
                                                <?php echo ($isSocietyRole) ? 'Loading members...' : 'Select Society First'; ?>
                                            </option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="role" class="form-label">Role <span class="text-danger">*</span></label>
                                        <select class="form-select" id="role" name="role" required>
                                            <option value="">Select Role</option>
                                            <option value="delegate">Delegate</option>
                                            <option value="chairman">Chairman</option>
                                            <option value="secretary">Secretary</option>
                                            <option value="treasurer">Treasurer</option>
                                            <option value="music_director">Music Director</option>
                                            <option value="organist">Organist</option>
                                            <option value="chorister">Chorister</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Notes</label>
                                        <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                                    </div>
                                    
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-plus me-1"></i> Add Delegate
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-7">
                        <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">Registered Conference Delegates</h6>
                                <div>
                                    <button class="btn btn-sm btn-outline-primary" onclick="window.print()">
                                        <i class="fas fa-print me-1"></i> Print List
                                    </button>
                                    <a href="export_delegates.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-outline-success">
                                        <i class="fas fa-file-excel me-1"></i> Export to Excel
                                    </a>
                                </div>
                            </div>
                            <div class="card-body">
                                <?php if (empty($delegates)): ?>
                                <div class="alert alert-info">
                                    No delegates have been registered for this conference yet.
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped" id="delegatesTable">
                                        <thead>
                                            <tr>
                                                <th>Society</th>
                                                <th>Name</th>
                                                <th>Contact</th>
                                                <th>Registration Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($delegates as $delegate): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($delegate['society_name']); ?></td>
                                                <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['last_name']); ?></td>
                                                <td>
                                                    <?php if (!empty($delegate['phone'])): ?>
                                                    <i class="fas fa-phone-alt me-1"></i> <?php echo htmlspecialchars($delegate['phone']); ?><br>
                                                    <?php endif; ?>
                                                    <?php if (!empty($delegate['email'])): ?>
                                                    <i class="fas fa-envelope me-1"></i> <?php echo htmlspecialchars($delegate['email']); ?>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo date('M d, Y', strtotime($delegate['registration_date'])); ?></td>
                                                <td>
                                                    <div class="btn-group" role="group">
                                                        <button type="button" class="btn btn-sm btn-info view-notes" data-bs-toggle="modal" data-bs-target="#notesModal" 
                                                            data-name="<?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['last_name']); ?>"
                                                            data-notes="<?php echo htmlspecialchars($delegate['notes'] ?? 'No notes available'); ?>">
                                                            <i class="fas fa-sticky-note"></i>
                                                        </button>
                                                        <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>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="mt-3">
                                    <div class="alert alert-info">
                                        <strong>Total Delegates:</strong> <?php echo count($delegates); ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Notes Modal -->
                <div class="modal fade" id="notesModal" tabindex="-1" aria-labelledby="notesModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="notesModalLabel">Delegate Notes</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p id="delegateNameDisplay"></p>
                                <div class="card">
                                    <div class="card-body" id="delegateNotesDisplay">
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </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>
    
    <script>
    $(document).ready(function() {
        // Initial load of members if society is already selected
        const initialSocietyId = $('#society_id').val();
        if (initialSocietyId) {
            loadSocietyMembers(initialSocietyId);
        }
        
        // Handle society change event
        $('#society_id').change(function() {
            const societyId = $(this).val();
            loadSocietyMembers(societyId);
        });
        
        // Function to load society members
        function loadSocietyMembers(societyId) {
            const memberSelect = $('#member_id');
            
            console.log("Loading members for society ID: " + societyId);
            
            // Reset member dropdown
            memberSelect.empty().append('<option value="">Loading members...</option>').prop('disabled', true);
            
            if (societyId) {
                // Fetch members from the selected society
                $.ajax({
                    url: '../ajax/get_society_members.php',
                    type: 'POST',
                    data: { 
                        society_id: societyId,
                        conference_id: <?php echo $conferenceId; ?>
                    },
                    dataType: 'json',
                    success: function(data) {
                        console.log("API response:", data);
                        memberSelect.empty();
                        
                        // Check for debug information
                        if (data.debug) {
                            console.log("Debug info:", data.debug);
                            memberSelect.append('<option value="">No members found in this society</option>');
                            return;
                        }
                        
                        if (data.error) {
                            console.error("API error:", data.error);
                            memberSelect.append('<option value="">Error: ' + data.error + '</option>');
                            return;
                        }
                        
                        if (Array.isArray(data) && data.length > 0) {
                            memberSelect.append('<option value="">Select Member</option>');
                            $.each(data, function(index, member) {
                                memberSelect.append(
                                    $('<option></option>')
                                        .attr('value', member.id)
                                        .text(member.first_name + ' ' + member.last_name)
                                );
                            });
                            memberSelect.prop('disabled', false);
                        } else {
                            memberSelect.append('<option value="">No members available for selection</option>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX error:", status, error);
                        memberSelect.empty().append('<option value="">Error loading members</option>');
                    }
                });
            } else {
                memberSelect.empty().append('<option value="">Select a society first</option>');
            }
        }
        
        // Display delegate notes in modal
        $('.view-notes').click(function() {
            const delegateName = $(this).data('name');
            const delegateNotes = $(this).data('notes');
            
            $('#delegateNameDisplay').text(delegateName);
            $('#delegateNotesDisplay').text(delegateNotes);
        });
    });
    </script>
</body>
</html>
