<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

$body = json_decode(file_get_contents('php://input'), true) ?: [];
$name = $body['name'] ?? '';
$args = $body['args'] ?? [];

switch ($name) {
  case 'flag_for_review':
    // TODO: insert into DB / log / notify
    echo json_encode(['ok' => true, 'message' => 'Flagged for review', 'ref' => uniqid('flag_')]);
    break;

  case 'validate_figures':
    // Basic server-side validation (you can expand)
    $candidates = $args['candidates'] ?? [];
    $rejected = (int)($args['rejected_votes'] ?? 0);

    $sum = 0;
    foreach ($candidates as $c) $sum += max(0, (int)($c['votes'] ?? 0));

    echo json_encode([
      'ok' => true,
      'total_candidate_votes' => $sum,
      'rejected_votes' => $rejected,
      'notes' => ($sum === 0 ? 'All candidate votes are zero. Check OCR.' : 'Looks plausible.'),
    ]);
    break;

  default:
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Unknown action']);
}
