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

session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$pdo = db();

// Get all active people
$stmt_people = $pdo->prepare("SELECT id FROM people WHERE active = 1");
$stmt_people->execute();
$people = $stmt_people->fetchAll(PDO::FETCH_COLUMN);

// Get all active process definitions
$stmt_processes = $pdo->prepare("SELECT id FROM process_definitions WHERE is_active = 1");
$stmt_processes->execute();
$processes = $stmt_processes->fetchAll(PDO::FETCH_COLUMN);

$insert_stmt = $pdo->prepare("INSERT IGNORE INTO process_instances (person_id, process_definition_id, current_status) VALUES (?, ?, 'none')");

$count = 0;
foreach ($people as $person_id) {
    foreach ($processes as $process_id) {
        $insert_stmt->execute([$person_id, $process_id]);
        if ($insert_stmt->rowCount() > 0) {
            $count++;
        }
    }
}

$_SESSION['flash_message'] = "Initialized $count new process instances.";

header("Location: process_dashboard.php"); // Redirect to the main dashboard
exit;
