<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();

if ($method === 'GET') {
    require_permission('automations.view');
    if (!hv4_table_exists('workflow_definitions')) {
        json_ok(['workflows' => [], 'runs' => [], 'migration_required' => true]);
    }
    $workflows = db()->query('SELECT * FROM workflow_definitions ORDER BY id')->fetchAll();
    foreach ($workflows as &$w) {
        $w['actions'] = json_decode($w['actions'] ?? '[]', true);
    }
    $runs = db()->query('SELECT * FROM workflow_runs ORDER BY id DESC LIMIT 30')->fetchAll();
    json_ok(['workflows' => $workflows, 'runs' => $runs]);
}

csrf_check();
require_permission('automations.manage');

if ($method === 'PUT') {
    $id = (int)($d['id'] ?? 0);
    if (!$id) json_error('id required', 422);
    if (isset($d['enabled'])) {
        db()->prepare('UPDATE workflow_definitions SET enabled=? WHERE id=?')->execute([!empty($d['enabled']) ? 1 : 0, $id]);
    }
    json_ok([], 'Updated');
}

json_error('Method not allowed', 405);
