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

if ($method === 'GET') {
    require_permission('automations.view');
    $templates = function_exists('hv5_workflow_templates') ? hv5_workflow_templates() : [];
    $workflows = [];
    if (function_exists('hv4_table_exists') && hv4_table_exists('workflow_definitions')) {
        $workflows = db()->query('SELECT * FROM workflow_definitions ORDER BY id')->fetchAll();
        foreach ($workflows as &$w) $w['actions'] = json_decode($w['actions'] ?? '[]', true);
    }
    json_ok(compact('workflows', 'templates'));
}

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

if ($method === 'POST') {
    $name = v_str($d, 'name', 120);
    $trigger = v_str($d, 'trigger_event', 80);
    $actions = $d['actions'] ?? [];
    if (!is_array($actions)) json_error('actions must be array', 422);
    if (!function_exists('hv5_save_workflow')) json_error('V5 not loaded', 503);
    hv5_save_workflow(0, $name, $trigger, $actions, !empty($d['enabled']));
    json_ok([], 'Workflow saved');
}

if ($method === 'PUT') {
    $id = (int)($d['id'] ?? 0);
    if (!$id) json_error('id required', 422);
    hv5_save_workflow($id, v_str($d, 'name', 120), v_str($d, 'trigger_event', 80), $d['actions'] ?? [], !empty($d['enabled']));
    json_ok([], 'Updated');
}

json_error('Method not allowed', 405);
