<?php
require_once 'lib/ErrorHandler.php';
require_once 'WorkflowEngine.php';
require_once 'db/config.php';

session_start();

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

$person_ids = json_decode($_POST['person_ids'] ?? '[]');
$process_id = $_POST['process_id'] ?? null;
$status = $_POST['status'] ?? null;
$reason = $_POST['reason'] ?? '';
$userId = $_SESSION['user_id'];

if (empty($person_ids) || !$process_id || !$status) {
    throw new WorkflowRuleFailedException('Missing parameters: person_ids, process_id, and status are required.');
}

$pdo = db();
$placeholders = implode(',', array_fill(0, count($person_ids), '?'));
$stmt = $pdo->prepare("SELECT id FROM process_instances WHERE process_definition_id = ? AND person_id IN ($placeholders)");
$params = array_merge([$process_id], $person_ids);
$stmt->execute($params);
$instance_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

if (empty($instance_ids)) {
    $_SESSION['flash_message'] = "No instances found for the selected people and process.";
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit;
}

$statuses = [];
foreach ($instance_ids as $instance_id) {
    $statuses[] = [
        'instance_id' => $instance_id,
        'status' => $status,
        'reason' => $reason,
        'user_id' => $userId
    ];
}

$workflowEngine = new WorkflowEngine();
$results = $workflowEngine->bulkManualStatus($statuses);

$_SESSION['flash_message'] = "Bulk status update completed.";
$_SESSION['bulk_results'] = $results;

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
