<?php
// test_workflow.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'WorkflowEngine.php';
require_once 'db/config.php'; // Include the database configuration

echo "Testing WorkflowEngine...<br>";

// Establish a direct database connection for setup
$pdo = db();

// 1. Get the first person from the database
$stmt = $pdo->query("SELECT id FROM people LIMIT 1");
$person = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$person) {
    die("<b>Error:</b> No people found in the database. Please run `db_setup.php` or ensure the database is seeded correctly.<br>");
}
$personId = $person['id'];
echo "Prerequisite check: Using person with ID $personId.<br>";

// 2. Get the first process definition from the database
$stmt = $pdo->query("SELECT id FROM process_definitions LIMIT 1");
$process = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$process) {
    die("<b>Error:</b> No process definitions found in the database. Please run `db_setup.php` or ensure the database is seeded correctly.<br>");
}
$processDefinitionId = $process['id'];
echo "Prerequisite check: Using process definition with ID $processDefinitionId.<br>";


$engine = new WorkflowEngine();
$userId = $personId;

echo "Attempting to get or create instance with personId: $personId and processDefinitionId: $processDefinitionId<br>";

try {
    $instance = $engine->getOrCreateInstanceByDefId($personId, $processDefinitionId, $userId);

    if ($instance) {
        echo "<b>Success!</b> Successfully got or created instance:<br>";
        echo "<pre>";
        print_r($instance);
        echo "</pre>";
    } else {
        echo "<b>Error:</b> Failed to get or create instance, but no exception was thrown.<br>";
        echo "This might happen if the process definition exists, but `startProcess` fails internally.<br>";
        echo "Check PHP error logs for more details.<br>";
    }
} catch (Exception $e) {
    echo "An exception occurred: " . $e->getMessage() . "<br>";
    echo "Stack trace:<br><pre>" . $e->getTraceAsString() . "</pre>";
}