<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/lib/rounds.php';
require_login();
if (!perms_can_run_round(current_user())) { http_response_code(403); echo 'Forbidden'; exit; }

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    exit;
}
if (!csrf_check()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'csrf']);
    exit;
}

$body = str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'application/json')
    ? (json_decode(file_get_contents('php://input') ?: '[]', true) ?: [])
    : $_POST;

$user   = current_user();
$action = $body['action'] ?? '';
$isSuper = perms_is_super($user);

// Determine which facility this round belongs to
function chosen_facility(array $user, array $body, bool $isSuper): ?int {
    if ($isSuper) {
        if (array_key_exists('facility_id', $body)) {
            $f = $body['facility_id'];
            if ($f === '' || $f === null) return null; // global
            return (int)$f;
        }
        return null;
    }
    return (int)$user['facility_id'];
}

try {
    switch ($action) {
        case 'start':
            $label    = v_clean_string($body['label'] ?? '', 100);
            $duration = v_int($body['duration_minutes'] ?? 8, 1, 60, 8);
            $warn     = v_int($body['warn_minutes']     ?? 2, 1, 30, 2);
            $facId    = chosen_facility($user, $body, $isSuper);
            $r = round_start($pdo, $facId, $label !== '' ? $label : null, $duration, $warn, (int)$user['id']);
            audit_log($pdo, 'round_start', ['round_id' => $r['id'] ?? null, 'duration' => $duration, 'facility_id' => $facId]);
            echo json_encode(['ok' => true, 'round' => round_state_snapshot_for_user($pdo, $user)]);
            return;

        case 'end':
        case 'abort':
            $cur = round_current_for_user($pdo, $user);
            if (!$cur) { echo json_encode(['ok' => true]); return; }
            // permission: super or coordinator over this round's facility
            if (!$isSuper && (int)$cur['facility_id'] !== (int)$user['facility_id']) {
                http_response_code(403);
                echo json_encode(['ok' => false, 'error' => 'forbidden']);
                return;
            }
            round_end($pdo, (int)$cur['id'], (int)$user['id'], $action === 'abort' ? 'aborted' : 'ended');
            audit_log($pdo, 'round_' . $action, ['round_id' => (int)$cur['id']]);
            echo json_encode(['ok' => true]);
            return;

        case 'manual_bell':
            $patternRaw = (string)($body['pattern'] ?? '1');
            $pattern    = in_array($patternRaw, ['1','2','3'], true) ? $patternRaw : '1';
            $type = 'manual_' . $pattern;
            $cur  = round_current_for_user($pdo, $user);
            $id   = bell_fire($pdo, $cur ? (int)$cur['id'] : null, $type, (int)$user['id']);
            audit_log($pdo, 'bell_manual', ['bell_id' => $id, 'pattern' => $pattern]);
            echo json_encode(['ok' => true, 'bell_id' => $id]);
            return;

        default:
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'unknown_action']);
            return;
    }
} catch (Throwable $e) {
    error_log('bell_control: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server_error']);
}
