<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../admin/auth.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if (empty($input['tier']) && empty($input['id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Tier name is required']);
    exit;
}

$tiers = readJSON(SPONSORSHIP_FILE);
$isNew = empty($input['id']);

if ($isNew) {
    $tier = [
        'id'               => 'spon-' . strtoupper(substr(uniqid(), -4)),
        'tier'             => trim(htmlspecialchars($input['tier'], ENT_QUOTES, 'UTF-8')),
        'badge'            => trim(htmlspecialchars($input['badge'] ?? '', ENT_QUOTES, 'UTF-8')),
        'highlight'        => !empty($input['highlight']),
        'price_label'      => trim(htmlspecialchars($input['price_label'] ?? 'Contact for Pricing', ENT_QUOTES, 'UTF-8')),
        'price_note'       => trim(htmlspecialchars($input['price_note'] ?? '', ENT_QUOTES, 'UTF-8')),
        'icon'             => trim(htmlspecialchars($input['icon'] ?? 'fa-star', ENT_QUOTES, 'UTF-8')),
        'color'            => trim(htmlspecialchars($input['color'] ?? '#CD7F32', ENT_QUOTES, 'UTF-8')),
        'benefits'         => is_array($input['benefits'] ?? null) ? array_map(fn($b) => htmlspecialchars(trim($b), ENT_QUOTES, 'UTF-8'), array_filter($input['benefits'], fn($b) => trim($b) !== '')) : [],
        'visibility_items' => is_array($input['visibility_items'] ?? null) ? array_map(fn($v) => htmlspecialchars(trim($v), ENT_QUOTES, 'UTF-8'), array_filter($input['visibility_items'], fn($v) => trim($v) !== '')) : [],
        'sort_order'       => intval($input['sort_order'] ?? count($tiers) + 1),
        'active'           => !empty($input['active']),
        'slots_available'  => intval($input['slots_available'] ?? 0),
        'slots_taken'      => intval($input['slots_taken'] ?? 0),
        'created_at'       => date('Y-m-d')
    ];
    $tiers[] = $tier;
} else {
    $found = false;
    foreach ($tiers as &$tier) {
        if ($tier['id'] === $input['id']) {
            if (isset($input['tier'])) $tier['tier'] = trim(htmlspecialchars($input['tier'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['badge'])) $tier['badge'] = trim(htmlspecialchars($input['badge'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['highlight'])) $tier['highlight'] = !empty($input['highlight']);
            if (isset($input['price_label'])) $tier['price_label'] = trim(htmlspecialchars($input['price_label'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['price_note'])) $tier['price_note'] = trim(htmlspecialchars($input['price_note'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['icon'])) $tier['icon'] = trim(htmlspecialchars($input['icon'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['color'])) $tier['color'] = trim(htmlspecialchars($input['color'], ENT_QUOTES, 'UTF-8'));
            if (isset($input['sort_order'])) $tier['sort_order'] = intval($input['sort_order']);
            if (isset($input['active'])) $tier['active'] = !empty($input['active']);
            if (isset($input['slots_available'])) $tier['slots_available'] = intval($input['slots_available']);
            if (isset($input['slots_taken'])) $tier['slots_taken'] = intval($input['slots_taken']);
            if (is_array($input['benefits'] ?? null)) $tier['benefits'] = array_map(fn($b) => htmlspecialchars(trim($b), ENT_QUOTES, 'UTF-8'), array_filter($input['benefits'], fn($b) => trim($b) !== ''));
            if (is_array($input['visibility_items'] ?? null)) $tier['visibility_items'] = array_map(fn($v) => htmlspecialchars(trim($v), ENT_QUOTES, 'UTF-8'), array_filter($input['visibility_items'], fn($v) => trim($v) !== ''));
            $found = true;
            break;
        }
    }
    if (!$found) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Tier not found']);
        exit;
    }
}

writeJSON(SPONSORSHIP_FILE, $tiers);
echo json_encode(['success' => true, 'tier' => $tier, 'isNew' => $isNew]);
exit;
