<?php
/**
 * Workflow Manager Script for EspoCRM
 * Usage: php workflow_manager.php <action> [options]
 * Actions: list, read <id>, delete <id>, edit <id> <json_data>, execute <id> <record_id>, test <id>
 */

$config = require '/var/www/html/data/config-internal.php';
$dsn = 'mysql:host=' . $config['database']['host'] . ';dbname=' . $config['database']['dbname'];
$user = $config['database']['user'];
$pass = $config['database']['password'];

function connectDB() {
    global $dsn, $user, $pass;
    try {
        $pdo = new PDO($dsn, $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        die("DB Fehler: " . $e->getMessage() . "\n");
    }
}

function listWorkflows($pdo) {
    $stmt = $pdo->query("SELECT id, name FROM bpmn_flowchart WHERE deleted = 0");
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "Verfügbare Workflows:\n";
    foreach ($results as $row) {
        echo "- ID: {$row['id']}, Name: {$row['name']}\n";
    }
}

function readWorkflow($pdo, $id) {
    $stmt = $pdo->prepare("SELECT * FROM bpmn_flowchart WHERE id = ? AND deleted = 0");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        echo "Workflow Details:\n";
        echo json_encode($row, JSON_PRETTY_PRINT) . "\n";
    } else {
        echo "Workflow nicht gefunden.\n";
    }
}

function deleteWorkflow($pdo, $id) {
    echo "Bist du sicher, dass du den Workflow $id löschen möchtest? (ja/nein): ";
    $input = trim(fgets(STDIN));
    if (strtolower($input) === 'ja') {
        $stmt = $pdo->prepare("UPDATE bpmn_flowchart SET deleted = 1 WHERE id = ?");
        $stmt->execute([$id]);
        echo "Workflow gelöscht.\n";
    } else {
        echo "Abgebrochen.\n";
    }
}

function editWorkflow($pdo, $id, $jsonData) {
    $data = json_decode($jsonData, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("Ungültiges JSON.\n");
    }
    $stmt = $pdo->prepare("UPDATE bpmn_flowchart SET data = ?, modified_at = NOW() WHERE id = ?");
    $stmt->execute([json_encode($data), $id]);
    echo "Workflow aktualisiert.\n";
}

function executeWorkflow($pdo, $id, $recordId) {
    // Einfache Simulation: Setze Status oder triggere Event
    // In Realität würde man EspoCRM-API verwenden
    echo "Workflow $id für Record $recordId ausführen...\n";
    // Beispiel: Status setzen
    $stmt = $pdo->prepare("UPDATE c_vmh_erstgespraech SET status = 'Warte auf Mandatierung' WHERE id = ?");
    $stmt->execute([$recordId]);
    echo "Status gesetzt. Workflow sollte ausgelöst werden.\n";
}

function testWorkflow($pdo, $id) {
    // Simuliere Bedingungen
    $stmt = $pdo->prepare("SELECT data FROM bpmn_flowchart WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $data = json_decode($row['data'], true);
        echo "Teste Workflow: " . (isset($data['list'][0]['text']) ? $data['list'][0]['text'] : 'Unbekannt') . "\n";
        // Prüfe Bedingungen (vereinfacht)
        echo "Bedingungen: " . json_encode(isset($data['list'][0]['conditionsAll']) ? $data['list'][0]['conditionsAll'] : []) . "\n";
    }
}

$pdo = connectDB();
$action = $argv[1] ?? 'list';

switch ($action) {
    case 'list':
        listWorkflows($pdo);
        break;
    case 'read':
        if (!isset($argv[2])) die("Usage: read <id>\n");
        readWorkflow($pdo, $argv[2]);
        break;
    case 'delete':
        if (!isset($argv[2])) die("Usage: delete <id>\n");
        deleteWorkflow($pdo, $argv[2]);
        break;
    case 'edit':
        if (!isset($argv[2]) || !isset($argv[3])) die("Usage: edit <id> <json_data>\n");
        editWorkflow($pdo, $argv[2], $argv[3]);
        break;
    case 'execute':
        if (!isset($argv[2]) || !isset($argv[3])) die("Usage: execute <workflow_id> <record_id>\n");
        executeWorkflow($pdo, $argv[2], $argv[3]);
        break;
    case 'test':
        if (!isset($argv[2])) die("Usage: test <id>\n");
        testWorkflow($pdo, $argv[2]);
        break;
    default:
        echo "Unbekannte Aktion. Verfügbare: list, read, delete, edit, execute, test\n";
}
?>