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

function trigger_workflow($trigger, $data) {
    $pdo = db();

    // 1. Fetch all workflows for the given trigger
    $stmt = $pdo->prepare("SELECT * FROM workflows WHERE `trigger` = ?");
    $stmt->execute([$trigger]);
    $workflows = $stmt->fetchAll();

    foreach ($workflows as $workflow) {
        // 2. For each workflow, fetch its actions
        $stmt = $pdo->prepare("SELECT * FROM workflow_actions WHERE workflow_id = ?");
        $stmt->execute([$workflow['id']]);
        $actions = $stmt->fetchAll();

        foreach ($actions as $action) {
            // 3. Execute each action
            execute_action($action, $data);
        }
    }
}

function execute_action($action, $data) {
    $config = json_decode($action['config'], true);

    // Replace placeholders in the config with data
    array_walk_recursive($config, function(&$value) use ($data) {
        if (is_string($value)) {
            foreach ($data as $key => $val) {
                if (is_string($val) || is_numeric($val)) {
                    $value = str_replace('{{candidate.' . $key . '}}', $val, $value);
                }
            }
        }
    });

    switch ($action['action_type']) {
        case 'send_email':
            MailService::sendMail($config['to'], $config['subject'], $config['message']);
            break;
        case 'create_task':
            $pdo = db();
            $stmt = $pdo->prepare("INSERT INTO tasks (name, assignee_id) VALUES (?, ?)");
            $stmt->execute([$config['task_name'], $config['assign_to']]);
            break;
        case 'send_slack_notification':
            $ch = curl_init($config['webhook_url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['text' => $config['message']]));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_exec($ch);
            curl_close($ch);
            break;
        case 'update_candidate_status':
            $pdo = db();
            $stmt = $pdo->prepare("UPDATE candidates SET status = ? WHERE id = ?");
            $stmt->execute([$config['new_status'], $data['candidate.id']]);
            break;
    }
}
?>