<?php
require_once 'db/config.php';

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

if (!isset($_GET['process_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Process ID is required.']);
    exit;
}

$process_id = $_GET['process_id'];

try {
    $pdo = db();

    // 1. Get process definition details
    $stmt_def = $pdo->prepare("SELECT * FROM process_definitions WHERE id = ?");
    $stmt_def->execute([$process_id]);
    $process_definition = $stmt_def->fetch(PDO::FETCH_ASSOC);

    if (!$process_definition) {
        http_response_code(404);
        echo json_encode(['error' => 'Process definition not found.']);
        exit;
    }

    if (!empty($process_definition['definition_json'])) {
        $process_definition['definition_json'] = json_decode($process_definition['definition_json'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Failed to decode process definition JSON. Error: " . json_last_error_msg());
        }
    } else {
        $process_definition['definition_json'] = [];
    }

    // 2. Get all instances for this process
    $stmt_instances = $pdo->prepare("SELECT * FROM process_instances WHERE process_definition_id = ?");
    $stmt_instances->execute([$process_id]);
    $instances = $stmt_instances->fetchAll(PDO::FETCH_ASSOC);

    $instance_ids = array_map(function($i) { return $i['id']; }, $instances);

    // 3. Get all events for these instances
    $events = [];
    if (!empty($instance_ids)) {
        $placeholders = implode(',', array_fill(0, count($instance_ids), '?'));
        $stmt_events = $pdo->prepare("SELECT * FROM process_events WHERE process_instance_id IN ($placeholders) ORDER BY created_at, id");
        $stmt_events->execute($instance_ids);
        $all_events = $stmt_events->fetchAll(PDO::FETCH_ASSOC);
        // Group events by instance_id
        foreach ($all_events as $event) {
            $events[$event['process_instance_id']][] = $event;
        }
    }

    // 4. Get People details
    $people_ids = array_unique(array_column($instances, 'person_id'));
    $people = [];
    if (!empty($people_ids)) {
        $valid_people_ids = array_filter($people_ids, 'is_numeric');

        if (!empty($valid_people_ids)) {
            $placeholders = implode(',', array_fill(0, count($valid_people_ids), '?'));
            $stmt_people = $pdo->prepare("SELECT id, first_name, last_name FROM people WHERE id IN ($placeholders)");
            $stmt_people->execute(array_values($valid_people_ids));
            $people_results = $stmt_people->fetchAll(PDO::FETCH_ASSOC);
            foreach ($people_results as $person) {
                $people[$person['id']] = $person;
                $people[$person['id']]['name'] = trim($person['first_name'] . ' ' . $person['last_name']);
            }
        }
    }

    // Assemble the response
    // Ensure steps are available, even if the JSON is empty or malformed.
    $steps = !empty($process_definition['definition_json']['steps']) ? $process_definition['definition_json']['steps'] : [];
    
    $response = [
        'process' => $process_definition,
        'steps' => $steps,
        'instances' => $instances,
        'events' => $events,
        'people' => $people
    ];

    echo json_encode($response);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'A database error occurred.', 'details' => $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'A general error occurred.', 'details' => $e->getMessage()]);
}
?>