<?php
/**
 * save-testimonials.php — POST { testimonials: [{name, stars, quote}, ...] }
 * Overwrites data/testimonials.json. Requires login.
 */
require_once __DIR__ . '/auth.php';
header('Content-Type: application/json');

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

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

$clean = [];
foreach ($items as $t) {
    if (!is_array($t)) continue;
    $name = trim(strip_tags($t['name'] ?? ''));
    $quote = trim(strip_tags($t['quote'] ?? ''));
    $stars = isset($t['stars']) ? (int)$t['stars'] : 5;
    $stars = max(1, min(5, $stars));
    if ($name === '' || $quote === '') continue;
    $clean[] = [
        'name' => mb_substr($name, 0, 60),
        'quote' => mb_substr($quote, 0, 400),
        'stars' => $stars,
    ];
    if (count($clean) >= 20) break;
}

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

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

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