<?php
require_once __DIR__ . '/../config.php';

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? '';

if ($method === 'GET' && $action === 'list') {
  $out = [];
  foreach (glob(SECTIONS_DIR.'/*.json') as $f) {
    $out[] = json_decode(file_get_contents($f), true);
  }
  json_out(['ok'=>true,'sections'=>$out]);
}

if ($method === 'POST' && $action === 'save') {
  require_admin();
  $d = read_json_body();
  $id = safe_id($d['id'] ?? ('sec_'.bin2hex(random_bytes(6))));
  $d['id'] = $id;
  file_put_contents(SECTIONS_DIR."/$id.json", json_encode($d, JSON_PRETTY_PRINT));
  json_out(['ok'=>true,'id'=>$id]);
}

if ($method === 'POST' && $action === 'delete') {
  require_admin();
  $d = read_json_body();
  unlink(SECTIONS_DIR.'/'.safe_id($d['id']).'.json');
  json_out(['ok'=>true]);
}

json_out(['ok'=>false,'error'=>'Invalid request'],400);
?>
