<?php
require_once '../includes/config.php';
require_once 'header.php';

$action = $_GET['action'] ?? 'list';
$memberId = $_GET['id'] ?? 0;
$error = '';
$success = '';

// Handle delete
if ($action == 'delete' && $memberId) {
    $stmt = $pdo->prepare("DELETE FROM members WHERE id = ?");
    if ($stmt->execute([$memberId])) {
        $success = 'Member deleted successfully';
    } else {
        $error = 'Failed to delete member';
    }
    $action = 'list';
}

// Get all members
$search = $_GET['search'] ?? '';
$filter = $_GET['filter'] ?? '';

$sql = "SELECT m.*, mt.type as membership_type 
        FROM members m 
        LEFT JOIN membership_types mt ON m.membership_type_id = mt.id 
        WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (m.fullname LIKE ? OR m.email LIKE ? OR m.membership_number LIKE ?)";
    $params = array_fill(0, 3, "%$search%");
}

if ($filter == 'expiring') {
    $sql .= " AND m.expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
}

$sql .= " ORDER BY m.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$members = $stmt->fetchAll();

// Get membership types for filter
$stmt = $pdo->query("SELECT * FROM membership_types");
$membershipTypes = $stmt->fetchAll();
?>

<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"><i class="fas fa-users me-2"></i>Manage Members</h1>
    <div>
        <a href="member_add.php" class="btn btn-primary">
            <i class="fas fa-user-plus me-2"></i>Add Member
        </a>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="GET" class="row g-3 mb-4">
            <div class="col-md-6">
                <input type="text" class="form-control" name="search" placeholder="Search by name, email or membership number..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3">
                <select name="filter" class="form-control">
                    <option value="">All Members</option>
                    <option value="expiring" <?php echo $filter == 'expiring' ? 'selected' : ''; ?>>Expiring Soon</option>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary w-100">Search</button>
            </div>
        </form>
        
        <div class="table-responsive">
            <table class="table table-striped table-hover" id="membersTable">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Photo</th>
                        <th>Name</th>
                        <th>Membership No</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Expiry Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $member): ?>
                        <?php $status = getMembershipStatus($member['expiry_date']); ?>
                        <tr>
                            <td><?php echo $member['id']; ?></td>
                            <td>
                                <img src="<?php echo UPLOAD_URL . $member['profile_photo']; ?>" 
                                     style="width: 40px; height: 40px; object-fit: cover; border-radius: 50%;"
                                     onerror="this.src='assets/images/default-avatar.png'">
                            </td>
                            <td><?php echo htmlspecialchars($member['fullname']); ?></td>
                            <td><?php echo $member['membership_number']; ?></td>
                            <td><?php echo $member['email']; ?></td>
                            <td><?php echo $member['membership_type']; ?></td>
                            <td><?php echo formatDate($member['expiry_date']); ?></td>
                            <td>
                                <span class="badge bg-<?php echo $status['class']; ?>">
                                    <?php echo $status['status']; ?>
                                </span>
                            </td>
                            <td>
                                <a href="member_view.php?id=<?php echo $member['id']; ?>" class="btn btn-sm btn-info">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="member_edit.php?id=<?php echo $member['id']; ?>" class="btn btn-sm btn-warning">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="member_idcard.php?id=<?php echo $member['id']; ?>" class="btn btn-sm btn-success">
                                    <i class="fas fa-id-card"></i>
                                </a>
                                <a href="?action=delete&id=<?php echo $member['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    $('#membersTable').DataTable({
        pageLength: 25,
        order: [[0, 'desc']]
    });
});
</script>

<?php require_once 'footer.php'; ?>