<?php

if (($RBAC_Response = $RBAC->userCanAccess("PM_FACTORY")) != 1) {
    return $RBAC_Response;
}
if (!class_exists('Triggers')) {
    require_once ('classes/model/Triggers.php');
}
$triggers = new Triggers();

$processMap = new ProcessMap();

$post = $_POST;

$allFunction = explode(",", $post['ALLFUNCTION']);
$allFunctionType = explode(",", $post['ALLFUNCTION_TYPE']);

$template = "
/***************************************************
 *
 * Generated by ProcessMaker Trigger Wizard
 * Library: " . $post['LIBRARY_NAME'] . "
 * Method: " . $post['PMFUNTION_LABEL'] . "
 * Date: " . date("Y-m-d H:i:s") . "
 *
 * ProcessMaker " . date("Y") . "
 *
 ****************************************************/

";

$params = [];
//Generate params to send
$i = 0;
foreach ($allFunction as $k => $v) {
    if ($v != '') {

        $key = trim(str_replace("$", "", $v));
        if (strstr($key, "=")) {
            $parameter = explode("=", $key);
            $key = trim($parameter[0]);
        }
        if ($post[$key] != '') {

            if ((strstr($post[$key], "@@")) || ($post['PMFUNTION_NAME'] == 'evaluateFunction' && $k == 0 && strstr($post[$key], "@="))) {
                $option = trim($post[$key]);
            } else {

                $post[$key] = strstr($post[$key], 'array') !== false ? str_replace("'", '"', $post[$key]) : str_replace("'", "\'", $post[$key]);
                switch (trim($allFunctionType[$i])) {
                    case 'boolean':
                        $option = $post[$key];
                        break;
                    case 'int':
                        $option = intval($post[$key]);
                        break;
                    case 'float':
                    case 'real':
                    case 'double':
                        $option = floatval($post[$key]);
                        break;
                    default:
                        if (is_numeric($post[$key]) || is_bool($post[$key]) || (strstr($post[$key], "'.array.'") !== false)) {
                            $option = trim($post[$key]);
                        } else {
                            $option = '"' . trim($post[$key]) . '"';
                        }
                        break;
                }
            }
        } else {
            $option = "''";
        }
        $params[] = $option;
    }
    $i++;
}

$template .= (isset($post['TRI_ANSWER']) && $post['TRI_ANSWER'] != '') ? $post['TRI_ANSWER'] . " = " : "";
$template .= $post['PMFUNTION_NAME'] . " (" . implode(",", $params) . ");";

//Create Trigger
$post['TRI_WEBBOT'] = $template;
$postParams = [];
$postParams['hash'] = G::encryptOld($template);
$postParams['params'] = $post;

$post['TRI_PARAM'] = serialize($postParams);
$triggers->create($post);

//Update Info
$post['TRI_UID'] = $triggers->getTriUid();
$triggers->update($post);

//Update Trigger Array
$processMap->triggersList($post['PRO_UID']);

