<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class axTerminalServices {

    public $command;
    public $commandLte;
    public $parse;
    public $now;

    
    
    public function __construct() {
        $this->command = new axWebServiceCommand();
        $this->commandLte = new axWebServiceCommandLte();
        $this->parse = new axWebServiceParsing();
    }

    private function getTerminalTransit($pdoModelObj, $terminalMac) {
        $out = null;
        $day = new DateTime();
        $today = $day->format('Y-m-d' . ' 00:00:00');

        $pdoModelObj->where('TerminalMac', $terminalMac);
        $pdoModelObj->where('CodeControl', '0');
        $list = $pdoModelObj->select('terminal_clockings');
        foreach ($list as $index => $vClk) {
            $inDateTime = new DateTime($vClk['DateAndTime']);
            $inDay = $inDateTime->format('Y-m-d');
            $out[$inDay][] = $vClk;
        }
        return $out;
    }

    private function reIndex($key, $array, $multy = false) {
        $out = array();

        foreach ($array as $index => $value) {
            if ($multy == false) {
                $out[$value[$key]] = $value;
            } else {
                $out[$value[$key]][] = $value;
            }
        }
        return $out;
    }

    private function lookupTerminalData($pdoModelObj, $arrays) {
        //$out = null;

        foreach ($arrays['terminals'] as $id => $vTerm) {
            if (isset($arrays['keepalive'][$vTerm['imp_mac']])) {
                $termIn = $this->getTerminalTransit($pdoModelObj, $vTerm['imp_mac']);
                $out[$vTerm['installation_id']][$vTerm['location_id']][$id] = $termIn; //$terminalClocking;
            } else {
                //$out[$vTerm['installation_id']][$vTerm['location_id']][$id] = false;
            }
        }

        return $out;
    }

    public function getTerminalData($pdoModelObj, $parm = null) {

        $pdoModelObj->where('enabled', 1);
        $out['client'] = $this->reIndex('id', $pdoModelObj->select('ax_com_multiclient'));
        $pdoModelObj->where('enabled', 1);
        $out['location'] = $this->reIndex('id', $pdoModelObj->select('ax_terminal_location'));
        $pdoModelObj->where('enabled', 1);
        $out['terminals'] = $this->reIndex('imp_id', $pdoModelObj->select('ax_terminal_installations'));

        $out['keepalive'] = $this->reIndex('mac', $pdoModelObj->select('ax_terminal_keep'));
        $out['lookUp'] = $this->lookupTerminalData($pdoModelObj, $out);

        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function getAnagData($pdoModelObj, $parm = null) {
        $pdoModelObj->where('enabled', 1);
        $out['users'] = $this->reIndex('badge', $pdoModelObj->select('ax_badge_user'));

        $pdoModelObj->where('enabled', 1);
        $out['firms'] = $this->reIndex('id', $pdoModelObj->select('ax_firms'));

        //$out['access'] =  $this->func->reIndex('id',$pdoModelObj->get('ax_terminal_access'));

        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function getRealTimeData($pdoModelObj, $parm = null) {
        $dateTime = new DateTime();
        $today = $dateTime->format('Y-m-d 00:00:00');

        $pdoModelObj->where('DateAndTime', $today, '>=');
        $trnsDay = $pdoModelObj->select('terminal_clockings');
        $out = array();

        foreach ($trnsDay as $index => $val) {
            if ($val['CodeControl'] == 0) {
                $out[$val['TerminalMac']]['trnWait'][] = $val;
            } elseif ($val['CodeControl'] == 1) {
                $out[$val['TerminalMac']]['trnSend'][] = $val;
            } elseif ($val['CodeControl'] == 2) {
                $out[$val['TerminalMac']]['trnErr'][] = $val;
            }
            $out[$val['TerminalMac']]['trn'][] = $val;
        }
        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function getTerminalPath($pdoModelObj, $parm = null) {
        $out = null;
        $pdoModelObj->where('enabled', 1);
        $list = $this->reIndex('imp_id', $pdoModelObj->select('ax_terminal_installations'));
        foreach ($list as $termId => $value) {
            $pathFile = PATH_STR . DIRECTORY_SEPARATOR . $value['installation_id'] . DIRECTORY_SEPARATOR . $value['location_id'] . DIRECTORY_SEPARATOR . $value['imp_id'] . DIRECTORY_SEPARATOR . $value['imp_mac'];
            $out['path'][$value['location_id']][$termId] = $pathFile;
        }
        if ($parm == 'associative') {
            $toRetunr = ['ret' => $out, 'debug' => $parm];
        } else {
            $toRetunr = (object) ['ret' => $out, 'debug' => $parm];
        }
        return $toRetunr;
    }

    private function makeAuthBadgeTerm($auths, $authsVisitor, $users, $visitors, $terminal, $writeRule) {
        $out = array();
        foreach ($terminal as $index => $termVal) {
            $idRule = $termVal['imp_wraccess_type'];
            //PROCESSA I PREVENTIVI
            foreach ($auths as $key => $value) {
                $uId = $value['userId'];
                if (isset($users[$uId])) {
                    $idRule = $value['rulefrom'];
                    $rule = $writeRule[$idRule]['code'];
                    $out['ouser'] = $users[$uId];
                    $badgeA = ltrim($users[$uId]['badge'], '0');
                    $badgeB = str_pad($badgeA, 6, "0", STR_PAD_LEFT);
                    $out['in'][$termVal['imp_id']][] = $badgeB . " " . $rule;
                } else {
                    $out['out'][$termVal['imp_id']] = $uId;
                }
            }
            //PROCESSA I FISSI
            if (isset($authsVisitor)) {
                foreach ($authsVisitor as $key => $value) {
                    $uId = $value['userId'];
                    if (isset($visitors[$uId])) {
                        $idRule = $value['rulefrom'];
                        $rule = $writeRule[$idRule]['code'];
                        $out['ouser'] = $visitors[$uId];
                        $badgeA = ltrim($visitors[$uId]['badge'], '0');
                        $badgeB = str_pad($badgeA, 6, "0", STR_PAD_LEFT);
                        $out['in'][$termVal['imp_id']][] = $badgeB . " " . $rule;
                    } else {
                        $out['out'][$termVal['imp_id']] = $uId;
                    }
                }
            }
        }
        return $out;
    }

    public function terminalCommandAuthBadge($pdoModelObj, $parm) {
        $areaId = $parm['op'];
        $makeSendCmd = $parm['send'];

        $out['termPath'] = $this->getTerminalPath($pdoModelObj)->ret['path'];

        $pdoModelObj->columns = array("id", "ente", "badge");
        $out['badgeUsers'] = $this->reIndex('id', $pdoModelObj->select('ax_badge_user'));

        $pdoModelObj->columns = array("id", "ente", "badge");
        $pdoModelObj->where('enabled', 1);
        $out['badgeUsersVisitor'] = $this->reIndex('id', $pdoModelObj->select('ax_badge_visitor'));

        $pdoModelObj->columns = array("installation_id", "location_id", "imp_id", "imp_id", "imp_mac", "imp_wraccess_type");
        $pdoModelObj->where('enabled', 1);
        $out['terminal'] = $this->reIndex('location_id', $pdoModelObj->select('ax_terminal_installations'), true);

        $pdoModelObj->columns = array("areaId", "userId", "rulefrom");
        $out['auth'] = $this->reIndex("areaId", $pdoModelObj->select('ax_auth'), true);

        $pdoModelObj->columns = array("areaId", "userId", "rulefrom");
        $out['authVisitor'] = $this->reIndex("areaId", $pdoModelObj->select('ax_authvisit'), true);

        //$pdoModelObj->columns = array("areaId","userId");
        $out['write'] = $this->reIndex("id", $pdoModelObj->select('ax_terminal_access_write'));

        if ($areaId == 'all') {
            foreach ($out['termPath'] as $areaId => $path) {
                if (isset($out['auth'][$areaId])) {
                    if (!isset($out['authVisitor'][$areaId])) {
                        $visitorsAuth = null;
                    } else {
                        $visitorsAuth = $out['authVisitor'][$areaId];
                    }

                    $out['authMake'][$areaId] = $this->makeAuthBadgeTerm(
                            $out['auth'][$areaId],
                            $visitorsAuth,
                            $out['badgeUsers'],
                            $out['badgeUsersVisitor'],
                            $out['terminal'][$areaId],
                            $out['write']);

                    $out['authDistroRxf'][$areaId] = $this->distroAuthTerminal($path, $out['authMake'][$areaId]['in'], "/rxf/ltcom.bdg", $makeSendCmd);

                    $out['authDistroTxF'][$areaId] = $this->distroAuthTerminal($path, $out['authMake'][$areaId]['in'], "/txf/ltcom.bdg", false);
                } else {
                    $out['authDistroNaN'][$areaId] = 'unset';
                }
            }
        } else {

            $out['authMake'][$areaId] = $this->makeAuthBadgeTerm($out['auth'][$areaId], $out['badgeUsers'], $out['terminal'][$areaId], $out['write']);
            $out['authDistro'][$areaId] = $this->distroAuthTerminal($out['termPath'][$areaId], $out['authMake'][$areaId]['in'], "/rxf/ltcom.bdg");
        }

        return (object) ['ret' => $out, 'debug' => $areaId];
    }

    private function distroAuthTerminal($path, $auth, $extra, $wrCmd) {
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Rome'));
        $now = $date->format('c');
        $out = array();

        foreach ($path as $idTerm => $path) {
            if (is_dir($path)) {
                $out['put'][$idTerm]['size'] = file_put_contents($path . $extra, join(PHP_EOL, $auth[$idTerm]));
                $out['put'][$idTerm]['path'] = $path . $extra;
                //$struct['path'] = $path;
                $out['cmd'][$idTerm] = $this->command->writeServiceCommand($path, 'RxF', 'ltcom.bdg', null, $now, $wrCmd);
            } else {
                $out['put'][$idTerm] = "Err.No Installation struct : " . $path;
            }
        }
        return $out;
    }

    public function writeAuthMacro($initfile, $macro, $accessRule, $user) {
        $writefile = null;
        //$initfile = null;
        $data = array();
        $write = "";
        //xdebug_var_dump($macro);
        foreach ($macro as $term_id => $termVal) {

            $idRule = $termVal['accessType'];
            $rule = $accessRule[$idRule]['code'];

            $structureData = [
                'rootstruct' => PATH_LOG,
                'pathid' => $termVal['install'],
                'pathlocid' => $termVal['location'],
                'pathareid' => $termVal['imp_nr']
            ];

            $structure = controlInstallationStructure($termVal['mac'], $structureData);
            $file = 'rxf/ltcom.bdg';
            $pathFile = $structure['path'] . DIRECTORY_SEPARATOR . $file;

            //xdebug_var_dump($termVal,$structure);

            if ($structure['result'] == true) {
                if ($initfile == true) {
                    file_put_contents($pathFile, "", LOCK_EX);
                }
                $count = 0;
                foreach ($user as $index => $badge) {
                    $count++;
                    $idRule = $termVal['accessType'];
                    $write .= $badge . " " . $rule . PHP_EOL;
                    $data[] = array('term_id' => $term_id, 'badge' => $badge, 'access' => $idRule);
                }

                $writefile = [
                    'size' => file_put_contents($pathFile, $write, FILE_APPEND | LOCK_EX),
                    'counter' => $count,
                    'data' => $data,
                ];
            }
        }
        return $writefile;
    }

    public function writeAuthTerm($termVal, $accessRule) {
        $initfile = null;
        $writefile = null;
        $structureData = [
            'rootstruct' => PATH_LOG,
            'pathid' => $termVal['install'],
            'pathlocid' => $termVal['location'],
            'pathareid' => $termVal['imp_nr']
        ];
        $structure[$term_id] = controlInstallationStructure($termVal['mac'], $structureData);

        $write = "";
        if ($structure['result'] == true) {
            $file = 'rxf/ltcom.bdg';
            $pathFile = $structure['path'] . DIRECTORY_SEPARATOR . $file;
            $initfile = file_put_contents($pathFile, "", LOCK_EX);
            foreach ($user as $index => $badge) {
                $idRule = $termVal['accessType'];
                $write .= $badge . " " . $accessRule[$idRule]['code'] . PHP_EOL;
            }
            $writefile = file_put_contents($pathFile, $write, LOCK_EX);
        }
    }

    private function getLte($parm) {
        $out = array();
        $out['value'] = false;
        if (is_file(PATH_LTE . DIRECTORY_SEPARATOR . 'data.json')) {
            $out['value'] = json_decode(file_get_contents(PATH_LTE . DIRECTORY_SEPARATOR . 'data.json'), TRUE);
            $out['stat'] = true;
        } else {
            $out['value'] = "Err.! Not Found " . PATH_LTE . DIRECTORY_SEPARATOR . 'data.json';
        }
        return $out;
    }

    private function getFile($parm, $dir, $file) {
        $out = array();
        $out['parm'] = $parm;
        $out['value'] = false;
        $filePath = $parm['path'] . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $file;

        if (is_file($filePath)) {
            $decode = json_decode(file_get_contents($filePath), TRUE);
            if (isset($decode)) {
                $out['value'] = $decode;
            } else {
                $out['value'] = 'No Data in : ' . $filePath;
            }

            $out['stat'] = true;
        } else {
            $out['value'] = "Err.! Not Found " . $filePath;
        }
        return $out;
    }

    public function getJsonRealTime($pdoModelObj, $parm) {
        $out['termComm'] = ['value' => 'no terminal set'];
        if (isset($parm['path'])) {
            if (isset($parm)) {
                $out['termComm'] = $this->getFile($parm, 'cmd', 'term_Cmd.json');
            }
            if (isset($parm)) {
                $out['termUpTry'] = $this->getFile($parm, 'log', 'uptry.json');
            }
            if (isset($parm)) {
                $out['termLog'] = $this->getFile($parm, 'log', 'command.json');
            }
            $out['dataLte'] = $this->getLte(null);
        }
        return (object) ['ret' => $out, 'debug' => null];
    }

    public function getTerminalCommandEtc($pdoModelObj, $parm = null) {

        $pdoModelObj->where('cmd_enabled', 1);
        $command = $pdoModelObj->select('ax_terminal_cmd');
        foreach ($command as $key => $value) {
            $value['cmd_readonly'] = boolval($value['cmd_readonly']);
            $out['command'][] = $value;
        }
        $par = $pdoModelObj->select('ax_terminal_cfg_par');
        foreach ($par as $key => $value) {
            $value['distro_all'] = boolval($value['distro_all']);
            $out['par'][] = $value;
        }
        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function terminalCommandManager($pdoModelObj, $parm) {

        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Rome'));
        $now = $date->format('c');
        $out = array();
        $operation = $parm['op'];
        $idTerm = $parm['id'];
        $path = $parm['path'];

        $filePath = $path . DIRECTORY_SEPARATOR . $parm['dir'] . DIRECTORY_SEPARATOR . $parm['file'];

        if ($operation == "D") {
            $out['cmd'][$idTerm] = file_put_contents($filePath, "");
        } elseif ($operation == "RBDG") {
            $stored = "Scarica il file Auth.";
            $parsed = "No File to parse";
            if (is_file($filePath)) {
                $stored = file_get_contents($filePath);
                $parsed = $this->parse->parseFileBadgeAuth($parm['file'], $stored);
            }
            $out['read'] = $parsed;
            $out['parsed'] = $parsed;
        } elseif ($operation == "RPAR") {
            $stored = "Scarica il file Cfg.";
            $parsed = "No File to parse";
            if (is_file($filePath)) {
                $stored = file_get_contents($filePath);
                $parsed = $this->parse->parseLtcomCfg($parm['file'], $stored, $now);
            }
            $out['read'] = $parsed;
            $out['parsed'] = $parsed;
        } else {
            $out['cmd'][$idTerm] = $this->command->writeServiceCommand($path, $parm['op'], $parm['file'], null, $now, true);
        }

        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function terminalCommandReader($parm) {


        return (object) ['ret' => null, 'debug' => $parm];
    }

    public function terminalCommandLte($pdoModelObj, $parm) {
        $out['parm'] = $parm;

        if ($parm['path'] == 'all') {
            $allpath = $this->getTerminalPath($pdoModelObj)->ret['path'];
            foreach ($allpath as $key => $allpathArea) {
                foreach ($allpathArea as $key => $pathTerm) {
                    $parm['termPath'] = $pathTerm;
                    $out['commandLte'][$key] = $this->commandLte->writeCommandLte($parm);
                }

                //$parm['termPath'] = $value;
                //$out['commandLte'] = $this->commandLte->writeCommandLte($parm);
            }
        } else {
            $parm['termPath'] = $parm['path'];
            $out['commandLte'] = $this->commandLte->writeCommandLte($parm);
        }

        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function readerMngLte($pdoModelObj, $parm) {
        $out['parm'] = $parm;
        $out['stored'] = 'No File Stored';

        $out['filepath'] = $parm['path'] . $parm['file'];

        if (is_file($out['filepath'])) {
            $out['stored'] = json_decode(file_get_contents($out['filepath']), TRUE);
        }
        return (object) ['ret' => $out, 'debug' => $parm];
    }

    public function updateCodeControll($pdomodel, $parm) {       
        $ids = join(",",$parm['ids']);
        $newval = $parm['val'];  
        $out['sql'] = "update `terminal_clockings` SET `codeControll` = $newval WHERE `Id` IN ($ids)";
        
        $records = $pdomodel->executeQuery($out['sql']);  
        $out['callback'] = $records;
        return (object) ['ret' => $out, 'debug' => $pdomodel->getLastQuery(),'error'=>$pdomodel->error];
    }

}
