<?php
require_once 'lib/ErrorHandler.php';
register_error_handler();

require_once 'db/config.php';
require_once 'WorkflowEngine.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => ['message' => 'Authentication required.']]);
    exit;
}

$userId = $_SESSION['user_id'];
$personId = filter_input(INPUT_POST, 'person_id', FILTER_VALIDATE_INT);
$subjectType = filter_input(INPUT_POST, 'subject_type', FILTER_SANITIZE_STRING) ?: 'person';
$subjectId = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT) ?: $personId;
$processDefinitionId = filter_input(INPUT_POST, 'process_id', FILTER_VALIDATE_INT);
$processCode = filter_input(INPUT_POST, 'process_code', FILTER_SANITIZE_STRING);
$deleteExisting = filter_input(INPUT_POST, 'delete_existing');
$mode = filter_input(INPUT_POST, 'mode', FILTER_SANITIZE_STRING);

$pdo = db();

if (!$processDefinitionId && $processCode) {
    $stmt = $pdo->prepare("SELECT id FROM process_definitions WHERE code = ? AND is_latest = 1 LIMIT 1");
    $stmt->execute([$processCode]);
    $processDefinitionId = $stmt->fetchColumn();
}

if (!$subjectId || !$processDefinitionId) {
    throw new InvalidArgumentException('Invalid or missing subject_id or process_id/process_code.');
}

$engine = new WorkflowEngine();


    $stmt_def = $pdo->prepare("SELECT code FROM process_definitions WHERE id = ?");
    $stmt_def->execute([$processDefinitionId]);
    $code = $stmt_def->fetchColumn() ?: $processCode;

if($deleteExisting === '1') {
    $instance = $engine->getActiveInstanceForSubject($code, $subjectType, $subjectId, $cycleKey);
    if ($instance) {
        $engine->deleteInstance($instance['id']);
    }
}

if ($mode === 'create_new_run' || filter_input(INPUT_POST, 'force', FILTER_VALIDATE_INT) === 1) {
    // start new process
    $instanceId = $engine->startProcessForSubject($code, $subjectType, $subjectId, $userId, 'create_new_run', $cycleKey);
    $stmt = $pdo->prepare("SELECT * FROM process_instances WHERE id = ?");
    $stmt->execute([$instanceId]);
    $instance = $stmt->fetch(PDO::FETCH_ASSOC);
} else {
    $instance = $engine->getOrCreateInstanceForSubject($processDefinitionId, $subjectType, $subjectId, $userId);
}

if ($instance) {
    echo json_encode(['success' => true, 'message' => 'Process initialized successfully.', 'instance_id' => $instance['id']]);
} else {
    throw new Exception("Failed to initialize process for an unknown reason.");
}
