<?php
/**
 * MSPE Team API
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;

switch ($method) {
    case 'GET':
        if ($id) {
            getMember($id);
        } else {
            getMembers();
        }
        break;
        
    case 'POST':
        requireAuth();
        $postData = !empty($_POST) ? $_POST : getRequestBody();
        if (!empty($postData['id'])) {
            updateMember($postData['id']);
        } else {
            createMember();
        }
        break;
        
    case 'PUT':
        requireAuth();
        if (!$id) {
            jsonResponse(['success' => false, 'message' => 'Member ID required'], 400);
        }
        updateMember($id);
        break;
        
    case 'DELETE':
        requireAuth();
        if (!$id) {
            jsonResponse(['success' => false, 'message' => 'ID required'], 400);
        }
        deleteMember($id);
        break;
        
    default:
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

function getMembers() {
    global $db;
    $members = $db->getAll('team');
    
    // Sort by order
    usort($members, function($a, $b) {
        return ($a['order'] ?? 99) - ($b['order'] ?? 99);
    });
    
    // Public view: only active
    if (!checkAuth()) {
        $members = array_filter($members, function($m) {
            return ($m['status'] ?? 'active') === 'active';
        });
    }
    
    jsonResponse(['success' => true, 'data' => array_values($members)]);
}

function getMember($id) {
    global $db;
    $member = $db->get('team', $id);
    if (!$member) jsonResponse(['success' => false, 'message' => 'Not found'], 404);
    jsonResponse(['success' => true, 'data' => $member]);
}

function createMember() {
    global $db;
    $data = !empty($_POST) ? $_POST : getRequestBody();
    
    if (empty($data['name']) || empty($data['role'])) {
        jsonResponse(['success' => false, 'message' => 'Name and Role are required'], 400);
    }
    
    // Sanitize text fields
    $data['name'] = sanitize($data['name']);
    $data['role'] = sanitize($data['role']);
    $data['email'] = sanitize($data['email'] ?? '');
    $data['linkedin'] = sanitize($data['linkedin'] ?? '');
    // Sanitize bio: allow only safe formatting tags
    $data['bio'] = sanitizeRichText($data['bio'] ?? '');
    
    // Image upload
    if (!empty($_FILES['photo'])) {
        $upload = handleFileUpload($_FILES['photo'], 'team');
        if ($upload['success']) {
            $data['photo'] = $upload['path'];
        }
    }
    
    $data['order'] = (int)($data['order'] ?? 99);
    $data['status'] = $data['status'] ?? 'active';
    
    $member = $db->insert('team', $data);
    jsonResponse(['success' => true, 'message' => 'Team member added', 'data' => $member]);
}

function updateMember($id) {
    global $db;
    $existing = $db->get('team', $id);
    if (!$existing) jsonResponse(['success' => false, 'message' => 'Not found'], 404);
    
    $data = !empty($_POST) ? $_POST : getRequestBody();
    
    if (!empty($_FILES['photo'])) {
        $upload = handleFileUpload($_FILES['photo'], 'team');
        if ($upload['success']) {
            $data['photo'] = $upload['path'];
        }
    }
    
    // Sanitize editable text fields
    if (isset($data['name'])) $data['name'] = sanitize($data['name']);
    if (isset($data['role'])) $data['role'] = sanitize($data['role']);
    if (isset($data['email'])) $data['email'] = sanitize($data['email']);
    if (isset($data['linkedin'])) $data['linkedin'] = sanitize($data['linkedin']);
    if (isset($data['bio'])) $data['bio'] = sanitizeRichText($data['bio']);

    $member = $db->update('team', $id, $data);
    jsonResponse(['success' => true, 'message' => 'Team member updated', 'data' => $member]);
}

function deleteMember($id) {
    global $db;
    $existing = $db->get('team', $id);
    if (!$existing) {
        jsonResponse(['success' => false, 'message' => 'Team member not found'], 404);
    }
    $db->delete('team', $id);
    jsonResponse(['success' => true, 'message' => 'Team member removed']);
}
