<?php
/**
 * Members List Page
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Ensure user is logged in
requireLogin();

// Initialize variables
$search = isset($_GET['search']) ? $_GET['search'] : '';
$society = isset($_GET['society']) ? $_GET['society'] : '';
$circuitFilter = isset($_GET['circuit']) ? $_GET['circuit'] : '';
$voicePart = isset($_GET['voice_part']) ? $_GET['voice_part'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPageParam = isset($_GET['per_page']) ? $_GET['per_page'] : '10'; // can be 'all'
// Normalize per page
if ($perPageParam === 'all') {
    $perPage = 'all';
    $offset = 0;
} else {
    $perPage = max(1, (int)$perPageParam);
    $offset = ($page - 1) * $perPage;
}

// Handle messages and errors
$message = '';
$error = '';
$alertType = '';

if (isset($_GET['message'])) {
    $alertType = 'success';
    $name = isset($_GET['name']) ? htmlspecialchars($_GET['name']) : 'Member';
    
    switch ($_GET['message']) {
        case 'member_deleted':
            $message = "<i class='bi bi-check-circle-fill me-2'></i> $name has been successfully deleted.";
            break;
        case 'member_deactivated':
            $message = "<i class='bi bi-check-circle-fill me-2'></i> $name has been deactivated because they have related records in the system.";
            break;
        default:
            $message = "<i class='bi bi-check-circle-fill me-2'></i> Operation completed successfully.";
    }
}

if (isset($_GET['error'])) {
    $alertType = 'danger';
    
    switch ($_GET['error']) {
        case 'permission_denied':
            $error = "<i class='bi bi-exclamation-triangle-fill me-2'></i> You don't have permission to perform this action.";
            break;
        case 'member_not_found':
            $error = "<i class='bi bi-exclamation-triangle-fill me-2'></i> Member not found.";
            break;
        case 'invalid_id':
            $error = "<i class='bi bi-exclamation-triangle-fill me-2'></i> Invalid member ID.";
            break;
        default:
            $error = "<i class='bi bi-exclamation-triangle-fill me-2'></i> An error occurred.";
    }
}

// Build query conditions
$conditions = [];
$params = [];

if (!empty($search)) {
    $conditions[] = "(m.first_name LIKE ? OR m.middle_name LIKE ? OR m.last_name LIKE ? OR m.contact_number LIKE ? OR m.email LIKE ?)";
    $searchParam = "%$search%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam, $searchParam]);
}

if (!empty($society)) {
    $conditions[] = "m.society_id = ?";
    $params[] = $society;
}

// Optional circuit filter (when user is diocese-level or provided explicitly)
if (!empty($circuitFilter)) {
    $conditions[] = "s.circuit_id = ?";
    $params[] = $circuitFilter;
}

if (!empty($voicePart)) {
    $conditions[] = "m.part = ?";
    $params[] = $voicePart;
}

if (!empty($status)) {
    $conditions[] = "m.membership_status = ?";
    $params[] = $status;
}

// Apply entity-based access control for non-admin/manager users
if (!hasRole(['admin', 'manager'])) {
    $userRole = $_SESSION['role'] ?? '';
    $userSocietyId = $_SESSION['society_id'] ?? null;
    $userCircuitId = $_SESSION['circuit_id'] ?? null;
    $userDioceseId = $_SESSION['diocese_id'] ?? null;
    
    // Define role-entity mappings
    $societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
    $circuitRoles = ['circuit_secretary', 'circuit_treasurer'];
    $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    
    // Society-level roles can only see members in their society
    if (in_array($userRole, $societyRoles) && !empty($userSocietyId)) {
        $conditions[] = "m.society_id = ?";
        $params[] = $userSocietyId;
    }
    
    // Circuit-level roles can see members in societies within their circuit
    elseif (in_array($userRole, $circuitRoles) && !empty($userCircuitId)) {
        $conditions[] = "s.circuit_id = ?";
        $params[] = $userCircuitId;
    }
    
    // Diocese-level roles can see members in societies within their diocese
    elseif (in_array($userRole, $dioceseRoles) && !empty($userDioceseId)) {
        $conditions[] = "c.diocese_id = ?";
        $params[] = $userDioceseId;
    }
}

// Build the WHERE clause
$whereClause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Get total count for pagination
$countQuery = "SELECT COUNT(*) as total 
               FROM members m 
               LEFT JOIN societies s ON m.society_id = s.id
               LEFT JOIN circuits c ON s.circuit_id = c.id
               $whereClause";
$filterParams = $params; // preserve filter-only params
$totalResult = fetchRows($countQuery, $filterParams);
$total = $totalResult[0]['total'];
if ($perPage === 'all') {
    $totalPages = 1;
    $page = 1;
} else {
    $totalPages = ceil($total / $perPage);
}

// Ensure page is within valid range
if ($page < 1) $page = 1;
if ($page > $totalPages && $totalPages > 0) $page = $totalPages;

// Get members with pagination (ordered by circuit and society for grouping)
$query = "SELECT m.*, s.id as society_id, s.name as society_name, c.id as circuit_id, c.name as circuit_name, d.name as diocese_name
          FROM members m 
          LEFT JOIN societies s ON m.society_id = s.id 
          LEFT JOIN circuits c ON s.circuit_id = c.id
          LEFT JOIN dioceses d ON c.diocese_id = d.id
          $whereClause 
          ORDER BY c.name, s.name, m.last_name, m.first_name";
// Apply pagination only if not 'all'
$queryParams = $filterParams;
if ($perPage !== 'all') {
    $query .= " LIMIT ? OFFSET ?";
    $queryParams[] = $perPage;
    $queryParams[] = $offset;
}

$members = fetchRows($query, $queryParams);

// Get counts per society for current filters (without pagination)
$countBySocietyQuery = "SELECT s.id as society_id, s.name as society_name, c.id as circuit_id, c.name as circuit_name, COUNT(m.id) as cnt
                        FROM members m
                        LEFT JOIN societies s ON m.society_id = s.id
                        LEFT JOIN circuits c ON s.circuit_id = c.id
                        $whereClause
                        GROUP BY s.id, s.name, c.id, c.name
                        ORDER BY c.name, s.name";
$societyCountsRows = fetchRows($countBySocietyQuery, $filterParams);
$societyCounts = [];
foreach ($societyCountsRows as $row) {
    $societyCounts[$row['society_id']] = (int)$row['cnt'];
}

// Get societies for filter dropdown - filtered by user's access level
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 {
        // Default - no societies
        $societies = [];
    }
}

// If user is diocese-level, load circuits for circuit filter
$circuits = [];
if (!hasRole(['admin','manager'])) {
    $userRole = $_SESSION['role'] ?? '';
    $userDioceseId = $_SESSION['diocese_id'] ?? null;
    $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    if (in_array($userRole, $dioceseRoles) && !empty($userDioceseId)) {
        $circuits = fetchRows("SELECT id, name FROM circuits WHERE diocese_id = ? ORDER BY name", [$userDioceseId]);
    }
}

// Voice parts for filter dropdown
$voiceParts = ['Soprano', 'Alto', 'Tenor', 'Bass'];

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Members List - GHAMECC Choir Management Platform</title>
    <?php include '../includes/favicon.php'; ?>
    <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">
    <style>
        .table-responsive {
            overflow-x: auto;
        }
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .filters {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .pagination .page-link {
            color: #0d6efd;
        }
        .pagination .active .page-link {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
        }
        .group-header { background: #f1f5ff; border-left: 4px solid #0d6efd; padding: 10px 12px; margin-top: 20px; font-weight: 600; }
        .subgroup-header { background: #e9ecef; padding: 8px 12px; display: flex; justify-content: space-between; align-items: center; }
        .subgroup-header .badge { font-size: 0.85rem; }
    </style>
</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">Members List</h1>
                    <?php if (hasRole(['admin', 'manager', 'secretary', 'society_secretary', 'circuit_secretary', 'diocesan_secretary', 'choirmaster', 'society_treasurer'])): ?>
                    <a href="register.php" class="btn btn-primary">
                        <i class="bi bi-person-plus-fill"></i> Register New Member
                    </a>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $alertType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($error)): ?>
                <div class="alert alert-<?php echo $alertType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="filters">
                    <form method="get" action="" class="row g-3">
                        <div class="col-md-3">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search members..." name="search" value="<?php echo htmlspecialchars($search); ?>">
                                <button class="btn btn-outline-secondary" type="submit">
                                    <i class="bi bi-search"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="society" onchange="this.form.submit()">
                                <option value="">All Societies</option>
                                <?php foreach ($societies as $s): ?>
                                <option value="<?php echo $s['id']; ?>" <?php echo $society == $s['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($s['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php 
                        // Show circuit filter if user is diocese-level
                        $userRole = $_SESSION['role'] ?? '';
                        $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
                        if (in_array($userRole, $dioceseRoles) && !empty($circuits)) : ?>
                        <div class="col-md-3">
                            <select class="form-select" name="circuit" onchange="this.form.submit()">
                                <option value="">All Circuits</option>
                                <?php foreach ($circuits as $c): ?>
                                <option value="<?php echo $c['id']; ?>" <?php echo $circuitFilter == $c['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($c['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        <div class="col-md-3">
                            <select class="form-select" name="voice_part" onchange="this.form.submit()">
                                <option value="">All Voice Parts</option>
                                <?php foreach ($voiceParts as $vp): ?>
                                <option value="<?php echo $vp; ?>" <?php echo $voicePart == $vp ? 'selected' : ''; ?>>
                                    <?php echo $vp; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="status" onchange="this.form.submit()">
                                <option value="">All Status</option>
                                <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="per_page" onchange="this.form.submit()">
                                <option value="10" <?php echo ($perPageParam=='10')?'selected':''; ?>>10 per page</option>
                                <option value="25" <?php echo ($perPageParam=='25')?'selected':''; ?>>25 per page</option>
                                <option value="50" <?php echo ($perPageParam=='50')?'selected':''; ?>>50 per page</option>
                                <option value="100" <?php echo ($perPageParam=='100')?'selected':''; ?>>100 per page</option>
                                <option value="all" <?php echo ($perPageParam=='all')?'selected':''; ?>>All</option>
                            </select>
                        </div>
                    </form>
                </div>
                
                <div class="card shadow mb-4">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Members Directory</h5>
                            <span>Total: <?php echo $total; ?> member<?php echo $total != 1 ? 's' : ''; ?></span>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (empty($members)): ?>
                            <div class="alert alert-info">
                                No members found. <?php if (hasRole(['admin', 'manager', 'secretary', 'society_secretary', 'circuit_secretary', 'diocesan_secretary', 'choirmaster', 'society_treasurer'])): ?>
                                <a href="register.php">Register a new member</a>.
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <?php 
                            $currentCircuit = null; 
                            $currentSociety = null; 
                            $openedTable = false;
                            foreach ($members as $member):
                                // Close previous table when society changes
                                if ($currentSociety !== null && $currentSociety !== $member['society_id'] && $openedTable) {
                                    echo '</tbody></table></div>';
                                    $openedTable = false;
                                }
                                // New circuit header
                                if ($currentCircuit !== $member['circuit_id']) {
                                    $currentCircuit = $member['circuit_id'];
                                    $currentSociety = null; // reset on circuit change
                                    echo '<div class="group-header">' . htmlspecialchars($member['circuit_name'] ?? 'No Circuit') . '</div>';
                                }
                                // New society header and start table
                                if ($currentSociety !== $member['society_id']) {
                                    $currentSociety = $member['society_id'];
                                    $socName = htmlspecialchars($member['society_name'] ?? 'No Society');
                                    $cnt = isset($societyCounts[$currentSociety]) ? $societyCounts[$currentSociety] : 0;
                                    echo '<div class="subgroup-header">'
                                        . '<div>' . $socName . '</div>'
                                        . '<span class="badge bg-primary">' . $cnt . ' member' . ($cnt == 1 ? '' : 's') . '</span>'
                                        . '</div>';
                                    echo '<div class="table-responsive"><table class="table table-striped table-hover mb-0"><thead><tr>'
                                        . '<th style="width:60px">Photo</th>'
                                        . '<th style="width:80px">ID</th>'
                                        . '<th>Name</th>'
                                        . '<th style="width:140px">Voice Part</th>'
                                        . '<th style="width:160px">Contact</th>'
                                        . '<th style="width:220px">Email</th>'
                                        . '<th style="width:100px">Status</th>'
                                        . '<th style="width:120px">Actions</th>'
                                        . '</tr></thead><tbody>';
                                    $openedTable = true;
                                }
                                
                                // Row
                                $fullName = htmlspecialchars($member['last_name'] . ', ' . $member['first_name'] . (!empty($member['middle_name']) ? ' ' . $member['middle_name'] : ''));
                                echo '<tr>';
                                $initials = '';
                                if (!empty($member['first_name']) || !empty($member['last_name'])) {
                                    $initials = strtoupper(substr($member['first_name'] ?? '', 0, 1) . substr($member['last_name'] ?? '', 0, 1));
                                }
                                $photoCell = '';
                                if (!empty($member['profile_image'])) {
                                    $photoCell = '<img src="../uploads/members/' . htmlspecialchars($member['profile_image']) . '" style="width:40px;height:40px;border-radius:50%;object-fit:cover;" />';
                                } else {
                                    $photoCell = '<div style="width:40px;height:40px;border-radius:50%;background:#e9ecef;color:#6c757d;display:flex;align-items:center;justify-content:center;font-weight:600;">' . $initials . '</div>';
                                }
                                echo '<td>' . $photoCell . '</td>';
                                echo '<td>' . htmlspecialchars($member['member_id'] ?? 'N/A') . '</td>';
                                echo '<td>' . $fullName . '</td>';
                                echo '<td>' . htmlspecialchars($member['part'] ?? 'N/A') . '</td>';
                                echo '<td>' . htmlspecialchars($member['contact_number'] ?? 'N/A') . '</td>';
                                echo '<td>' . htmlspecialchars($member['email'] ?? 'N/A') . '</td>';
                                $badgeClass = ($member['membership_status'] == 'active') ? 'success' : 'secondary';
                                echo '<td><span class="badge bg-' . $badgeClass . '">' . ucfirst($member['membership_status']) . '</span></td>';
                                echo '<td class="action-buttons">'
                                    . '<a href="view.php?id=' . $member['id'] . '" class="btn btn-sm btn-info" title="View"><i class="bi bi-eye"></i></a> ';
                                if (hasRole(['admin', 'manager', 'secretary', 'society_secretary', 'circuit_secretary', 'diocesan_secretary', 'choirmaster', 'society_treasurer'])) {
                                    echo '<a href="edit.php?id=' . $member['id'] . '" class="btn btn-sm btn-primary" title="Edit"><i class="bi bi-pencil"></i></a> '
                                        . '<button type="button" class="btn btn-sm btn-danger delete-btn" data-bs-toggle="modal" data-bs-target="#deleteModal" data-id="' . $member['id'] . '" data-name="' . $fullName . '" title="Delete"><i class="bi bi-trash"></i></button>';
                                }
                                echo '</td>';
                                echo '</tr>';
                            endforeach;
                            // Close any open table
                            if ($openedTable) { echo '</tbody></table></div>'; }
                            ?>
                        <?php endif; ?>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Are you sure you want to delete <span id="memberName"></span>?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <a href="#" id="confirmDelete" class="btn btn-danger">Delete</a>
                </div>
            </div>
        </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() {
            // Set up delete modal
            $('.delete-btn').click(function() {
                var id = $(this).data('id');
                var name = $(this).data('name');
                $('#memberName').text(name);
                $('#confirmDelete').attr('href', 'delete.php?id=' + id);
            });
        });
    </script>
</body>
</html>
