<?php
/**
 * save-promos.php — POST { promos: ["text 1", "text 2", ...] }
 * Overwrites data/promos.json. Requires login.
 */
require_once __DIR__ . '/auth.php';
header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$promos = $input['promos'] ?? null;

if (!is_array($promos)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'promos must be an array of strings']);
    exit;
}

// Sanitize: strip tags, trim, drop empties, cap length and count
$clean = [];
foreach ($promos as $p) {
    if (!is_string($p)) continue;
    $p = trim(strip_tags($p));
    if ($p === '') continue;
    $clean[] = mb_substr($p, 0, 140);
    if (count($clean) >= 6) break; // sane upper limit
}

if (!is_dir(DATA_DIR)) mkdir(DATA_DIR, 0755, true);

$ok = file_put_contents(
    DATA_DIR . 'promos.json',
    json_encode($clean, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);

echo json_encode(['ok' => $ok !== false, 'promos' => $clean]);
