<?php
/**
 * Member directory – printable list by fellowship or ministry, optional photos
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/fellowships.php';
requireAuth();

$pageTitle = 'Member Directory';
$currentPage = 'members';

$filterBy = $_GET['filter'] ?? 'all'; // all, fellowship, ministry
$filterFellowship = trim($_GET['fellowship'] ?? '');
$filterMinistryId = isset($_GET['ministry']) ? (int) $_GET['ministry'] : 0;
$includePhotos = !empty($_GET['photos']);

$fellowshipOrder = getFellowshipOrder();
$ministries = $pdo->query('SELECT id, name FROM ministries ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);

// Exclude deceased members from directory
$sql = "SELECT m.id, m.title, m.first_name, m.middle_name, m.last_name, m.gender, m.date_of_birth, m.phone, m.email, m.photo,
        (SELECT GROUP_CONCAT(mn.name ORDER BY mn.name SEPARATOR ', ')
         FROM member_ministries mm
         JOIN ministries mn ON mn.id = mm.ministry_id
         WHERE mm.member_id = m.id) AS ministry_names
        FROM members m
        WHERE (m.status != 'deceased' OR m.status IS NULL) AND (m.date_of_death IS NULL)
        ORDER BY m.last_name, m.first_name";
$params = [];

if ($filterBy === 'ministry' && $filterMinistryId > 0) {
    $sql = "SELECT m.id, m.title, m.first_name, m.middle_name, m.last_name, m.gender, m.date_of_birth, m.phone, m.email, m.photo,
            (SELECT GROUP_CONCAT(mn.name ORDER BY mn.name SEPARATOR ', ')
             FROM member_ministries mm
             JOIN ministries mn ON mn.id = mm.ministry_id
             WHERE mm.member_id = m.id) AS ministry_names
            FROM members m
            INNER JOIN member_ministries mm ON mm.member_id = m.id AND mm.ministry_id = ?
            WHERE (m.status != 'deceased' OR m.status IS NULL) AND (m.date_of_death IS NULL)
            ORDER BY m.last_name, m.first_name";
    $params = [$filterMinistryId];
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($filterBy === 'fellowship' && $filterFellowship !== '') {
    $members = array_filter($members, function ($m) use ($filterFellowship) {
        $fellowship = getMemberFellowship($m['date_of_birth'] ?? null, $m['gender'] ?? null);
        return $fellowship === $filterFellowship;
    });
    $members = array_values($members);
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header no-print">
    <h1>Member Directory</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/members" class="link-muted">← Members</a>
        <button type="button" class="btn" onclick="window.print()">Print / Save as PDF</button>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="card no-print directory-filters">
    <form method="get" class="directory-filter-form">
        <div class="form-row" style="flex-wrap: wrap; gap: 1rem; align-items: flex-end;">
            <div class="form-group">
                <label>Show</label>
                <select name="filter" id="dir_filter">
                    <option value="all" <?= $filterBy === 'all' ? 'selected' : '' ?>>All members</option>
                    <option value="fellowship" <?= $filterBy === 'fellowship' ? 'selected' : '' ?>>By fellowship</option>
                    <option value="ministry" <?= $filterBy === 'ministry' ? 'selected' : '' ?>>By ministry</option>
                </select>
            </div>
            <div class="form-group dir-fellowship" style="display: <?= $filterBy === 'fellowship' ? 'block' : 'none' ?>;">
                <label>Fellowship</label>
                <select name="fellowship">
                    <option value="">— Select —</option>
                    <?php foreach (array_filter($fellowshipOrder) as $f): ?>
                    <option value="<?= htmlspecialchars($f) ?>" <?= $filterFellowship === $f ? 'selected' : '' ?>><?= htmlspecialchars($f) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group dir-ministry" style="display: <?= $filterBy === 'ministry' ? 'block' : 'none' ?>;">
                <label>Ministry</label>
                <select name="ministry">
                    <option value="">— Select —</option>
                    <?php foreach ($ministries as $mn): ?>
                    <option value="<?= (int) $mn['id'] ?>" <?= $filterMinistryId === (int) $mn['id'] ? 'selected' : '' ?>><?= htmlspecialchars($mn['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group checkbox-row">
                <label>
                    <input type="checkbox" name="photos" value="1" <?= $includePhotos ? 'checked' : '' ?>>
                    Include photos
                </label>
            </div>
            <div class="form-group">
                <button type="submit" class="btn">Update</button>
            </div>
        </div>
    </form>
</div>

<div class="directory-print-header print-only">
    <h1><?= htmlspecialchars(SITE_FULL_NAME) ?></h1>
    <p class="directory-print-title">Member Directory<?php
        if ($filterBy === 'fellowship' && $filterFellowship) echo ' · ' . htmlspecialchars($filterFellowship);
        if ($filterBy === 'ministry' && $filterMinistryId) {
            $mnName = '';
            foreach ($ministries as $mn) { if ((int)$mn['id'] === $filterMinistryId) { $mnName = $mn['name']; break; } }
            if ($mnName) echo ' · ' . htmlspecialchars($mnName);
        }
    ?></p>
    <p class="directory-print-date"><?= date('F j, Y') ?></p>
</div>

<div class="card directory-content">
    <p class="text-muted no-print"><?= count($members) ?> member(s)</p>
    <?php if (empty($members)): ?>
        <p class="text-muted">No members match the selected filter.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table class="directory-table">
            <thead>
                <tr>
                    <?php if ($includePhotos): ?><th class="dir-photo">Photo</th><?php endif; ?>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Email</th>
                    <th>Fellowship</th>
                    <th>Service Groups</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $m):
                    $name = trim(($m['title'] ?? '') . ' ' . ($m['first_name'] ?? '') . ' ' . ($m['middle_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                    $fellowship = getMemberFellowship($m['date_of_birth'] ?? null, $m['gender'] ?? null);
                    $photoUrl = $includePhotos && !empty($m['photo']) ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($m['photo']) : null;
                ?>
                <tr>
                    <?php if ($includePhotos): ?>
                    <td class="dir-photo">
                        <?php if ($photoUrl): ?>
                        <img src="<?= $photoUrl ?>" alt="" class="directory-photo">
                        <?php else: ?>
                        <span class="directory-photo directory-photo-placeholder">—</span>
                        <?php endif; ?>
                    </td>
                    <?php endif; ?>
                    <td><?= htmlspecialchars($name) ?></td>
                    <td><?= htmlspecialchars($m['phone'] ?? '') ?></td>
                    <td><?= htmlspecialchars($m['email'] ?? '') ?></td>
                    <td><?= htmlspecialchars($fellowship ?? '') ?></td>
                    <td><?= htmlspecialchars($m['ministry_names'] ?? '') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
(function() {
    var filter = document.getElementById('dir_filter');
    var fellowship = document.querySelector('.dir-fellowship');
    var ministry = document.querySelector('.dir-ministry');
    if (filter && fellowship && ministry) {
        function toggle() {
            var v = filter.value;
            fellowship.style.display = v === 'fellowship' ? 'block' : 'none';
            ministry.style.display = v === 'ministry' ? 'block' : 'none';
        }
        filter.addEventListener('change', toggle);
    }
})();
</script>

<style>
.directory-photo {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
    display: block;
}
.directory-photo-placeholder {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg);
    color: var(--text-muted);
    font-size: 0.75rem;
}
.dir-photo { width: 60px; }
.directory-filter-form .form-row { margin-bottom: 0; }

@media print {
    .sidebar { display: none !important; }
    .main { margin-left: 0 !important; }
    .no-print { display: none !important; }
    .print-only { display: block !important; }
    .directory-print-header {
        text-align: center;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #333;
    }
    .directory-print-header h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }
    .directory-print-title { font-size: 1rem; margin: 0; font-weight: 600; }
    .directory-print-date { font-size: 0.875rem; margin: 0.25rem 0 0; color: #666; }
    .directory-content { border: none; box-shadow: none; }
    .directory-table { font-size: 0.75rem; }
    .directory-table th, .directory-table td { padding: 0.35rem 0.5rem; }
    .directory-photo { width: 32px; height: 32px; }
    body { background: #fff; }
    .main { margin-left: 0; padding: 0; }
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
