<?php
/**
 * Admin - Team Members
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Team Members';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        redirect(BASE_URL . 'admin/team-members.php', 'error', 'Invalid security token');
    }
    
    $ids = $_POST['selected_ids'] ?? [];
    $action = $_POST['bulk_action'];
    
    if (!empty($ids)) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        try {
            if ($action === 'delete') {
                $stmt = db()->prepare("DELETE FROM team_members WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/team-members.php', 'success', count($ids) . ' members deleted');
            } elseif ($action === 'activate') {
                $stmt = db()->prepare("UPDATE team_members SET status = 1 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/team-members.php', 'success', count($ids) . ' members activated');
            } elseif ($action === 'deactivate') {
                $stmt = db()->prepare("UPDATE team_members SET status = 0 WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/team-members.php', 'success', count($ids) . ' members deactivated');
            }
        } catch (PDOException $e) {
            redirect(BASE_URL . 'admin/team-members.php', 'error', 'Action failed');
        }
    }
}

// Get team members
$members = [];
$search = sanitize($_GET['search'] ?? '');
$status = $_GET['status'] ?? '';

$conditions = [];
$params = [];

if ($search) {
    $conditions[] = '(name LIKE ? OR designation LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}
if ($status !== '') {
    $conditions[] = 'status = ?';
    $params[] = $status;
}

$sql = "SELECT * FROM team_members";
if ($conditions) {
    $sql .= " WHERE " . implode(' AND ', $conditions);
}
$sql .= " ORDER BY sort_order, id DESC";

try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $members = $stmt->fetchAll();
} catch (PDOException $e) {}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Team Members</h2>
    <a href="team-member-add.php" class="btn btn-primary"><i class="bi bi-plus-lg me-2"></i>Add Member</a>
</div>

<form method="GET" class="row g-3 mb-4">
    <div class="col-md-4">
        <input type="text" name="search" class="form-control" placeholder="Search members..." value="<?php echo $search; ?>">
    </div>
    <div class="col-md-3">
        <select name="status" class="form-select">
            <option value="">All Status</option>
            <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>Active</option>
            <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>Inactive</option>
        </select>
    </div>
    <div class="col-md-2">
        <button type="submit" class="btn btn-outline-primary w-100">Filter</button>
    </div>
    <div class="col-md-2">
        <a href="team-members.php" class="btn btn-outline-secondary w-100">Clear</a>
    </div>
</form>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
    
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span class="fw-bold">Team Members</span>
            <div class="d-flex gap-2">
                <select name="bulk_action" class="form-select form-select-sm" style="width: auto;">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Activate</option>
                    <option value="deactivate">Deactivate</option>
                    <option value="delete">Delete</option>
                </select>
                <button type="submit" class="btn btn-sm btn-outline-secondary">Apply</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th><input type="checkbox" class="form-check-input" id="selectAll"></th>
                        <th>Photo</th>
                        <th>Name</th>
                        <th>Designation</th>
                        <th>Order</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $member): ?>
                    <tr>
                        <td><input type="checkbox" name="selected_ids[]" value="<?php echo $member['id']; ?>" class="form-check-input row-checkbox"></td>
                        <td>
                            <?php if ($member['image']): ?>
                                <img src="<?php echo UPLOADS_URL . $member['image']; ?>" alt="" style="width: 50px; height: 50px; object-fit: cover; border-radius: 50%;">
                            <?php else: ?>
                                <div style="width: 50px; height: 50px; background: #eee; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                    <i class="bi bi-person text-muted"></i>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $member['name']; ?></td>
                        <td><?php echo $member['designation']; ?></td>
                        <td><?php echo $member['sort_order']; ?></td>
                        <td>
                            <span class="badge bg-<?php echo $member['status'] ? 'success' : 'secondary'; ?>">
                                <?php echo $member['status'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <a href="team-member-edit.php?id=<?php echo $member['id']; ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-pencil"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($members)): ?>
                    <tr><td colspan="7" class="text-center py-4 text-muted">No team members found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</form>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

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