<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/scheduler.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok' => false, 'error' => 'POST only']);
    exit;
}

// Batch save — all entries in one load/write/rebuild cycle
if (!empty($_POST['batch'])) {
    $entries = json_decode($_POST['batch'], true) ?: [];
    $clean   = [];
    foreach ($entries as $e) {
        $id   = trim($e['id'] ?? '');
        $cron = trim($e['cron'] ?? '');
        if (!$id) continue;
        if ($cron && !in_array($cron, ['array_start', 'array_stop'], true)
                  && !preg_match('/^(\S+\s+){4}\S+$/', $cron)) $cron = '';
        $clean[] = [
            'id'          => $id,
            'enabled'     => ($e['enabled'] ?? '0') === '1',
            'cron'        => $cron,
            'log_enabled' => ($e['log_enabled'] ?? '0') === '1',
        ];
    }
    $ok = vv_schedule_update_batch($clean);
    echo json_encode(['ok' => $ok, 'error' => $ok ? null : 'Failed to write schedule']);
    exit;
}

$id          = trim($_POST['id']      ?? '');
$enabled     = (bool)($_POST['enabled'] ?? false);
$cron        = trim($_POST['cron']    ?? '');
$log_enabled = ($_POST['log_enabled'] ?? '0') === '1';

if (!$id) {
    echo json_encode(['ok' => false, 'error' => 'Missing id']);
    exit;
}

// Basic cron validation — 5 fields, or known @event trigger, or empty
if ($cron && !in_array($cron, ['array_start', 'array_stop'], true)
         && !preg_match('/^(\S+\s+){4}\S+$/', $cron)) {
    echo json_encode(['ok' => false, 'error' => 'Invalid cron expression']);
    exit;
}

$ok = vv_schedule_update($id, $enabled, $cron, $log_enabled);
echo json_encode(['ok' => $ok, 'error' => $ok ? null : 'Failed to write schedule']);
