<?php
require_once 'WorkflowEngine.php';
require_once 'lib/ErrorHandler.php';
require_once 'lib/WorkflowExceptions.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    throw new WorkflowNotAllowedException('Unauthorized');
}

$userId = $_SESSION['user_id'];
$personIds = $_POST['personIds'] ?? '[]';
if (is_string($personIds)) {
    $personIds = json_decode($personIds, true);
}
$process_id = $_POST['process_id'] ?? null;

if (empty($personIds) || !$process_id) {
    throw new WorkflowRuleFailedException('Missing parameters');
}

$engine = new WorkflowEngine();
$results = [
    'success' => [],
    'failed' => [],
];

foreach ($personIds as $personId) {
    try {
        $instance = $engine->getOrCreateInstanceByDefId($personId, $process_id, $userId);
        if ($instance) {
            $results['success'][] = $personId;
        } else {
            $results['failed'][] = $personId;
        }
    } catch (Exception $e) {
        $results['failed'][] = $personId;
        // Optionally log the error
        error_log("Failed to initialize process for person $personId: " . $e->getMessage());
    }
}

$message = "Bulk initialization completed. Success: " . count($results['success']) . ", Failed: " . count($results['failed']);

if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
    header('Content-Type: application/json');
    echo json_encode([
        'message' => $message,
        'results' => $results
    ]);
} else {
    $_SESSION['success_message'] = $message;
    header('Location: index.php');
}
exit();