<?php
// Include required files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

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

// Basic variables
$pageTitle = "Society Diocese Conference 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 society_id FROM users WHERE id = $userId";
    $userSocietyResult = fetchRow($userSocietyQuery);
    if ($userSocietyResult && isset($userSocietyResult['society_id'])) {
        $userSocietyId = $userSocietyResult['society_id'];
    }
}

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

// 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");
}

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

// Initialize variables
$conference = null;
$conferenceError = "";
$successMessage = "";
$errorMessage = "";

// If conference ID is provided, get conference details
if ($conferenceId) {
    $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'
                          AND c.entity_id = {$society['diocese_id']}");
    
    if (!$conference) {
        $conferenceError = "Conference not found or not accessible";
    }
}

// Process form submission for adding delegates
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($action === 'add_delegate') {
        $memberId = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
        $conferenceId = isset($_POST['conference_id']) ? (int)$_POST['conference_id'] : 0;
        $role = isset($_POST['role']) ? mysqli_real_escape_string($conn, $_POST['role']) : 'delegate';
        $notes = isset($_POST['notes']) ? mysqli_real_escape_string($conn, $_POST['notes']) : '';
        
        if (!$memberId || !$conferenceId) {
            $errorMessage = "Please select both conference 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, notes, created_by) 
                          VALUES ($conferenceId, $memberId, NOW(), 'registered', '$notes', $userId)";
                $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) {
            // Ensure the registration belongs to this society
            $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";
            } else {
                $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 available diocese conferences
$availableConferences = fetchRows("SELECT c.*, d.name as diocese_name 
                                  FROM conferences c
                                  JOIN dioceses d ON c.entity_id = d.id
                                  WHERE c.type = 'diocese' 
                                  AND c.entity_id = {$society['diocese_id']}
                                  AND c.status = 'upcoming'
                                  ORDER BY c.start_date");

// Get current delegates for the selected conference
$delegates = [];
if ($conferenceId && !$conferenceError) {
    $delegates = fetchRows("SELECT cr.id, cr.payment_status, cr.registration_date, cr.notes,
                          m.id as member_id, m.first_name, m.last_name as surname, m.email, m.contact_number as phone, 
                          m.sex as gender, m.part
                          FROM conference_registrations cr
                          JOIN members m ON cr.member_id = m.id
                          WHERE cr.conference_id = $conferenceId
                          AND m.society_id = $userSocietyId
                          ORDER BY m.last_name, m.first_name");
}

// Debug: Check total members in this society
$totalMembersQuery = "SELECT COUNT(*) as total FROM members WHERE society_id = $userSocietyId";
$totalMembersResult = fetchRow($totalMembersQuery);
$totalMembers = $totalMembersResult ? $totalMembersResult['total'] : 0;

// Debug: Check total registrations for this conference from this society
$totalRegistrationsQuery = "SELECT COUNT(*) as total FROM conference_registrations cr
                          JOIN members m ON cr.member_id = m.id
                          WHERE cr.conference_id = $conferenceId AND m.society_id = $userSocietyId";
$totalRegistrationsResult = fetchRow($totalRegistrationsQuery);
$totalRegistrations = $totalRegistrationsResult ? $totalRegistrationsResult['total'] : 0;

// Debug: Get all members from this society to check their data
$allMembersQuery = "SELECT * FROM members WHERE society_id = $userSocietyId ORDER BY last_name, first_name";
$allMembers = fetchRows($allMembersQuery);

// Always get all members first
$availableMembers = $allMembers;

// If a conference is selected, filter out already registered members
if ($conferenceId && !$conferenceError && !empty($availableMembers)) {
    $filteredMembers = [];
    foreach ($availableMembers as $member) {
        // Check if this member is already registered for this conference
        $isRegistered = fetchRow("SELECT id FROM conference_registrations 
                                WHERE conference_id = $conferenceId 
                                AND member_id = {$member['id']}");
        if (!$isRegistered) {
            $filteredMembers[] = $member;
        }
    }
    $availableMembers = $filteredMembers;
}

// Debug: Store the counts for display
$debugInfo = [
    'totalMembers' => $totalMembers,
    'totalRegistrations' => $totalRegistrations,
    'availableMembersCount' => count($availableMembers),
    'delegatesCount' => count($delegates),
    'allMembersData' => $allMembers,
    'conferenceId' => $conferenceId,
    'conferenceError' => $conferenceError ? 'Yes' : 'No',
    'availableMembersEmpty' => empty($availableMembers) ? 'Yes' : 'No',
    'availableMembersType' => gettype($availableMembers),
    'availableMembersData' => $availableMembers
];

?>

<!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 Choir Management Platform</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.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">Register Society Members for Diocese 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>
                
                <div class="alert alert-info">
                    <strong>Society:</strong> <?php echo htmlspecialchars($society['name']); ?> <br>
                    <strong>Circuit:</strong> <?php echo htmlspecialchars($society['circuit_name']); ?> <br>
                    <strong>Diocese:</strong> <?php echo htmlspecialchars($society['diocese_name']); ?>
                </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; ?>
                
                <?php if ($conferenceError): ?>
                <div class="alert alert-danger">
                    <?php echo $conferenceError; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($debugInfo)): ?>
                <div class="alert alert-info">
                   
                    <?php if (!empty($debugInfo['allMembersData'])): ?>
                    <hr>
                    <strong>All Society Members:</strong>
                    <table class="table table-sm table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Part</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($debugInfo['allMembersData'] as $member): ?>
                            <tr>
                                <td><?php echo $member['id']; ?></td>
                                <td><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></td>
                                <td><?php echo $member['email']; ?></td>
                                <td><?php echo isset($member['contact_number']) ? $member['contact_number'] : 'N/A'; ?></td>
                                <td><?php echo $member['part']; ?></td>
                                <td><?php echo isset($member['status']) ? $member['status'] : 'N/A'; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                    
                    <?php if (!empty($debugInfo['availableMembersData'])): ?>
                    <hr>
                    <strong>Available Members:</strong>
                    <table class="table table-sm table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Part</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($debugInfo['availableMembersData'] as $member): ?>
                            <tr>
                                <td><?php echo $member['id']; ?></td>
                                <td><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></td>
                                <td><?php echo $member['email']; ?></td>
                                <td><?php echo isset($member['contact_number']) ? $member['contact_number'] : 'N/A'; ?></td>
                                <td><?php echo $member['part']; ?></td>
                                <td><?php echo isset($member['status']) ? $member['status'] : 'N/A'; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <?php if (empty($availableConferences)): ?>
                <div class="alert alert-warning">
                    There are no upcoming diocese conferences available for registration.
                </div>
                <?php else: ?>
                
                <!-- Conference Selection -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Select Diocese Conference</h6>
                    </div>
                    <div class="card-body">
                        <form method="get" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                            <div class="row">
                                <div class="col-md-8">
                                    <select class="form-select" name="conference_id" required>
                                        <option value="">Select Conference</option>
                                        <?php foreach ($availableConferences as $conf): ?>
                                        <option value="<?php echo $conf['id']; ?>" <?php echo ($conferenceId == $conf['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($conf['name']); ?> 
                                            (<?php echo date('M d, Y', strtotime($conf['start_date'])); ?> - 
                                            <?php echo date('M d, Y', strtotime($conf['end_date'])); ?>)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-filter me-1"></i> Select Conference
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($conference): ?>
                <div class="alert alert-info">
                    <strong>Selected Conference:</strong> <?php echo htmlspecialchars($conference['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'])); ?> <br>
                    <strong>Registration Deadline:</strong> <?php echo date('F d, Y', strtotime($conference['registration_deadline'])); ?> <br>
                    <strong>Fee:</strong> GHS <?php echo number_format($conference['fee_amount'], 2); ?>
                </div>
                
                <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">Register Member as Delegate</h6>
                            </div>
                            <div class="card-body">
                              
                                
                                <?php if ($debugInfo['totalMembers'] > 0): ?>
                                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>">
                                    <input type="hidden" name="action" value="add_delegate">
                                    <input type="hidden" name="conference_id" value="<?php echo $conferenceId; ?>">
                                    
                                    <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>
                                            <option value="">Select Member</option>
                                            <?php foreach ($allMembers as $member): ?>
                                            <option value="<?php echo $member['id']; ?>">
                                                <?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?> 
                                                (<?php echo htmlspecialchars($member['part']); ?>)
                                            </option>
                                            <?php endforeach; ?>
                                        </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="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> Register Member
                                        </button>
                                    </div>
                                </form>
                                <?php else: ?>
                                <div class="alert alert-warning">
                                    Your society has no members. Please add members to your society first.
                                </div>
                                <?php endif; ?>
                            </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">Registered Delegates</h6>
                            </div>
                            <div class="card-body">
                                <?php if (empty($delegates)): ?>
                                <div class="alert alert-info">
                                    No delegates have been registered yet from your society.
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>Part</th>
                                                <th>Role</th>
                                                <th>Registration Date</th>
                                                <th>Actions</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['part']); ?></td>
                                                <td><?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $delegate['payment_status'] ?? 'pending'))); ?></td>
                                                <td><?php echo date('M d, Y', strtotime($delegate['registration_date'])); ?></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; ?>
                <?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>
