<?php
    /**
     * - - - - - - - - - - - -
     * Author: yandexphp
     * - - - - - - - - - - - -
     */
    class synergy {
        public static $host; // Хост с которым будем работать (https://synergy.arta.pro)
        public static $SU; // Супер пользователь формат: (логин:пароль)
        private static $dataUUID = false;
        private static $formData = false;
        public static function load($dataUUID){
            $res = self::api('asforms/data/' . $dataUUID, false, false);
            self::$formData = (property_exists((object)$res, 'data') ? $res : false);
            self::$dataUUID = $dataUUID;
            return $res;
        }
        public static function getValue(){
            if (!self::$formData) return;
            $args = func_get_args();
            $data = null;
            if (is_string($args[0]) && @is_int($args[2])) {
                if ($args[2] == 0) $args[2] = 1;
                foreach (self::$formData['data'] as $item) {
                    if ($item['id'] == $args[1]) {
                        foreach ($item['data'] as $bItem) {
                            if ($bItem['id'] == $args[0] . '-b' . $args[2]) {
                                $data = (@$args[3] ? $bItem[$args[3]] : $bItem);
                                break;
                            }
                        }
                        break;
                    }
                }
            } else {
                foreach (self::$formData['data'] as $item) {
                    if ($item['id'] == $args[0]) {
                        $data = (@$args[1] ? $item[$args[1]] : $item);
                        break;
                    }
                }
            }
            return $data;
        }
        public static function setValue(){
            if (!self::$formData) return;
            $args = func_get_args();
            if (is_string($args[0]) && @is_int($args[2])) {
                if ($args[2] == 0) $args[2] = 1;
                foreach (self::$formData['data'] as $k => $item) {
                    if ($item['id'] == $args[1]) {
                        foreach ($item['data'] as $k2 => $bItem) {
                            if ($bItem['id'] == $args[0] . '-b' . $args[2]) {
                                if (is_array($args[3])) {
                                    if (@$args[4]) self::$formData['data'][$k]['data'][$k2][$args[4]] = $args[3];
                                    else foreach ($args[3] as $key => $aItem) self::$formData['data'][$k]['data'][$k2][$key] = $aItem;
                                } else self::$formData['data'][$k]['data'][$k2][(@$args[4] ? $args[4] : 'value')] = $args[3];
                                break;
                            }
                        }
                        break;
                    }
                }
            } else {
                foreach (self::$formData['data'] as $k => $item) {
                    if ($item['id'] == $args[0]) {
                        if (is_array($args[1])) foreach ($args[1] as $key => $aItem) self::$formData['data'][$k][$key] = $aItem;
                        else self::$formData['data'][$k][(@$args[2] ? $args[2] : 'value')] = $args[1];
                        break;
                    }
                }
            }
        }
        public static function getRowsCount($tableID){
            if(!self::$formData) return;
            return count(self::convertTable($tableID));
        }
        public static function convertTable($tableID){
            if (!self::$formData) return;
            $data = self::getValue($tableID);
            $convert = array();
            $b = -1;
            foreach ($data['data'] as $item) {
                if (stripos($item['id'], '-b') !== false) {
                    $b = substr($item['id'], strpos($item['id'], '-b') + 2, strlen($item['id']));
                    if (!array_key_exists($b, $convert)) $convert[$b] = new stdClass();
                    $convert[$b]->{stristr($item['id'], '-b', 1)} = $item;
                }
            }
            return $convert;
        }
        public static function save($callback = null){
            if (!self::$formData) return;
            self::fixManualTags();
            $save = self::api('asforms/data/save', 'POST', array(
                'uuid' => self::$dataUUID,
                'data' => '"data":' . json_encode(self::$formData['data'], JSON_UNESCAPED_UNICODE)
            ));
            if ($save['errorCode'] != 13 && $callback) $callback(self::$dataUUID);
            return $save;
        }
        private static function fixManualTags($recursiveIndex = null){
            if (!self::$formData) return;
            if ($recursiveIndex) {
                if (!array_key_exists('data', self::$formData['data'][$recursiveIndex])) return;
                foreach (self::$formData['data'][$recursiveIndex]['data'] as $k => $v) {
                    if (array_key_exists('manualTags', $v)) self::$formData['data'][$k]['manualTags'] = new stdClass();
                }
            } else {
                foreach (self::$formData['data'] as $k => $v) {
                    if (array_key_exists('manualTags', $v)) {
                        self::$formData['data'][$k]['manualTags'] = new stdClass();
                    } else if (array_key_exists('type', $v) && $v['type'] == 'appendable_table') {
                        self::fixManualTags($k);
                    }
                }
            }
        }
        public static function api($method, $type = 'GET', $params = false){
            return json_decode(self::curl(self::$host . '/Synergy/rest/api/' . $method, $type, $params), 1);
        }
        public static function curl($url, $type = 'GET', $params = false, &$data = null){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, ($params && strtoupper($type) == 'GET' ? $url .= '?' . http_build_query($params) : $url));
            if (stristr($url, 'synergy/rest/api') !== false){
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                curl_setopt($ch, CURLOPT_USERPWD, self::$superUser);
            }
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            if (strtoupper($type) == 'POST'){
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
            }
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }
        public static function getUUID(){
            return self::$dataUUID;
        }
        public static function getData(){
            return self::$formData['data'];
        }
    }