<?php

use CheckPoints\CheckPoint;
use CheckPointTypes\CheckPointType;
//use Tasks\Task;

require_once 'ocs.php';

$onlineMobileTimeoutSeconds = 600;

function VagrantRequest($accid, $tagid, $name, $eventtype, $echo=false)
{
    if ($tagid=='unavailable')
        return;
    global $link;
    $account = Account::Find($accid);
    $jobstring = "No role";
    if ($account)
    {
        $jobtypes = $account->getJobtypesIds();
        $jobstring = GetJobNames($jobtypes)[0];
        $company = $account->getCompany();
        if ($company)
        {
            if (intval($company->id) > 1)
                return;
        }
//        $jobnames_account = GetJobNames($jobtypes)[0];
//        $jobstring = implode(",", $jobnames_account);
    }
//    var_dump($jobstring);
//return;
    $params['projectId'] = "000T";
    $params['role'] = $jobstring;
    $params['fullName'] = $name; //"123";//"2019-10-28T13:00:00";
    $params['employeeId'] = $accid; //"123";//"2019-10-28T13:00:00";
    $params['tagId'] = $tagid; //"123";//"2019-10-28T13:00:00";
    $params['eventType'] = $eventtype; //1;//"2019-10-28T13:00:00";
    $url = "https://vagrantsmopp.azurewebsites.net/api/EmployeeTag";
    $jsonEncoded = json_encode($params);

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept:application/json"));
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonEncoded);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);


    $result = curl_exec($curl);
    $str = "insert into vagrant_log (acc_id, eventtype, reply, stamp, tagid) values ($accid, $eventtype, '$result', NOW(), '$tagid')";
    mysqli_query($link, $str);

    if ($echo) {
        var_dump($result);
        var_dump($params);
//        echo $str;
    }



}


function GetCompanyID($act, $activeid)
{
    $companyID = 0;
    switch ($act)
    {
        case "tasktypes":
            $tt = Tasktype::Find($activeid);
            if ($tt)
                $companyID = $tt->company;
            break;
        case "tasks":
            $task = Task::Find($activeid);
            if ($task) {
                $type = $task->type;
                $tt = Tasktype::Find($type);
                if ($tt)
                    $companyID = $tt->company;
            }
            break;
        case "projects":
            $proj = Project::Find($activeid);
            if ($proj)
                $companyID = $proj->getCompany();
            break;
        case "project_types":
            $proj = ProjectType::Find($activeid);
            if ($proj)
                $companyID = $proj->company;
            break;
    }
    return $companyID;
}

function EnqueueCMD($acc_id, $cmd)
{
    global $link;

    $str = "insert into commands (account_id, cmd, created) values ($acc_id, '$cmd', NOW())";
    $query = mysqli_query($link, $str);
}

function DequeueCMD($acc_id)
{
    global $link;
    $str = "select * from commands where account_id = $acc_id";
    $query = mysqli_query($link, $str);
    $cmdarr = array();
    while ($res = mysqli_fetch_array($query)) {
        $cmd = $res['cmd'];
        array_push($cmdarr, $cmd);
        mysqli_query($link, "delete from commands where id = ".$res['id']);
    }
    return $cmdarr;
}

function XLSRead($inputFileName, $activeSheet = 0)
{
    error_reporting(E_ALL);
    set_time_limit(0);

    date_default_timezone_set('Europe/London');

    /** Include path **/
    set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel_1.8.0_doc/Classes/');

    /** PHPExcel_IOFactory */
    include 'PHPExcel/IOFactory.php';
    //$inputFileName = 'example1.xls';

    //$inputFileName = './sampleData/example1.xls';
//    echo 'Loading file ', pathinfo($inputFileName, PATHINFO_BASENAME), ' using IOFactory to identify the format<br />';
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);


    echo '<hr />';
    if ($activeSheet > 0)
        $objPHPExcel->setActiveSheetIndex($activeSheet);
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
    //var_dump($sheetData);
    return $sheetData;
}

function FindAction($actionID)
{
    global $link, $companyID;
    $query1 = mysqli_query($link, "select * from projecttypes where id=$actionID");

    if ($res1 = mysqli_fetch_array($query1)) {
        return $res1;
    }
}

function FindActions($tasktype = '')
{
    global $link, $companyID, $entityManager;

    return $entityManager->getRepository('ProjectType')->findBy(array('company' => $companyID));
//    //return $entityManager->getRepository('MyProject\Domain\User')->findBy(array('age' => 20, 'surname' => 'Miller'));
//
//    $str = "select p_r.id,p_r.name,p_r.company
//                from projecttypes p_r
//                join projecttypes_tasktypes p_t on p_t.projecttype_id = p_r.id
//                join tasktypes t on t.id = p_t.tasktype_id
//                where p_r.company = $companyID" ;
//
////$str = "select * from project_types where company=$companyID";
//    if ($tasktype != '') {
//        //$str .= " and $tasktype in (tasktypes)";
//        $str .= " and t.id = $tasktype";
//    }
//    //var_dump($str); die();
//
//    $query1 = mysqli_query($link, $str);
//    $returnArr = array();
//    while ($res1 = mysqli_fetch_array($query1)) {
//        array_push($returnArr, $res1);
//    }
//
//    return $returnArr;
}

function FindParentTaskType($ttid)
{
    global $link;
    $str = "select * from tasktypes tt where main_task=1 and $ttid IN (tt.subtasks)";
    //echo '$str'.$str;
    $returnArr = array();
    $query1 = mysqli_query($link, $str);
    while ($res1 = mysqli_fetch_array($query1)) {
    
        array_push($returnArr, $res1);
    }
    return $returnArr;
}

function FindTaskOwner($tid)
{
    global $link;
    $str = "select id from accounts accs where $tid IN (accs.active_task_ids)";
//    echo '$str'.$str;
    $returnArr = array();
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_row($query1)) {
        return $res1[0];
    }
    return null;
//    while ($res1 = mysqli_fetch_array($query1)) {
//
//        array_push($returnArr, $res1);
//    }
//    return $returnArr;
}


function StartProject($action, $project_id, $manager=null)
{
    global $entityManager;
//    var_dump($entityManager);
//    echo "<br>"; die();
    //$assign_id - id таблицы входных данных
    //$action - действие (например перемещение)
    //данная функция:
    //1. ищет в базе среди tasktype данное действие (глобальное main_task=true)
    //2. создает задачу найденного типа
    $existing_tasks = GetTasksForProject($project_id);
    
    if (sizeof($existing_tasks) > 0) {
        echo "<span style='color: red'>Задачи для этого проекта уже созданы</span><br>";
        OCSnewproject($project_id);
        return true;
    }
//    $tasktypesarr = GrabTasktypes("all", intval($action));
    if ( null == $entityManager ) {
        $entityManager = $manager;
    }

    $tasktypesarr = ProjectType::GrabTasktypesByProjectType(intval($action), $entityManager);

    if (sizeof($tasktypesarr) > 0) {

        CreateTasks($tasktypesarr, $project_id);
        OCSnewproject($project_id);
        return true;
    }
    else
    {
        echo "<span style='color: red'>Ошибка: нет подходящих задач под выбранное действие</span>";
        OCSnewproject($project_id);
        return false;
    }
}

function getTaskStatusName($status)
{
    global $link;
    $name = '';
    $color = '';
    $query = mysqli_query($link,"select * from task_status_names where id=".$status);
    if ($res = mysqli_fetch_array($query))
    {
        $name = $res['name'];
        $color = $res['color'];
    }
    return array ($name, $color);
}

function GetHrefActive($href, $name, $li=true)
{
    global $act;
    $hrefactive = '';
    if ($href == $act) {
        $hrefactive = ' style="color:blue" class="active" ';
    }
    $liopen = '<li>';
    $liclose = '</li>';
    if ($li == false)
    {
        $liopen = '';
        $liclose = '';
    }
    echo $liopen.'<a class="menuleft" href="?act='.$href.'"'.$hrefactive.'>'.$name.'</a>'.$liclose;
}

function GetAccordeonNum($act)
{
    $accordnum = 0;
    switch($act)
    {
        case "global": $accordnum = 0;break;
        case "companies": $accordnum = 0;break;
        case "projects": $accordnum = 0;break;
        case "locations": $accordnum = 0;break;
        case "projects_old": $accordnum = 0;break;
        case "project_types": $accordnum = 0;break;
        case "loco": $accordnum = 0;break;
        case "penalties": $accordnum = 3;break;
        case "filelib": $incl ="filelib/in.php";break;
        case "accounts": $incl ="accounts.php";$accordnum = 0;break;
        case "analytics": $incl ="analytics.php";$accordnum = 0;break;
        case "markers": $incl ="markers.php";$accordnum = 1;break;
        case "tasks": $incl ="tasks.php";$accordnum = 2;break;
        case "checkpoints": $incl ="checkpoints.php";$accordnum = 2;break;
        case "checkitems": $incl ="checkitems.php";$accordnum = 2;break;
        case "tasksdone": $incl ="tasksdone.php";$accordnum = 2;break;
        case "tasktypes": $incl ="tasktypes.php";$accordnum = 2;break;
        case "docs": $incl ="docs.php";$accordnum = 4;break;
        case "reports": $incl ="reports.php";$accordnum = 4;break;
        case "journal": $incl ="journal.php";$accordnum = 4;break;
        case "devices": $incl ="devices.php";$accordnum = 1;break;
        case "staff": $incl ="staff.php";$accordnum = 3;break;
        case "objects": $incl ="objects.php";$accordnum = 1;break;
        case "object": $incl ="object.php";$accordnum = 1;break;
        case "typeobject": $incl ="typeobject.php";$accordnum = 1;break;
        case "input_data": $incl ="input_data.php";$accordnum = 3;break;
        case "jobs": $incl ="jobs.php";$accordnum = 3;break;
        case "dashboard": $incl ="dashboard.php";$accordnum = 0;break;
    }
    return $accordnum;
}

function GetInclude($act, $cmdlevel)
{
    $incl = '';
    $accordnum = GetAccordeonNum($act);
    if ($cmdlevel==10) {//head admins
        switch($act) {
            case "asusg_dayplan": $incl ="asusg_dayplan.php";break;
            case "penalties": $incl ="penalties.php";break;
            case "loco": $incl ="loco.php";break;
            case "locations": $incl ="locations.php";break;
            case "algo": $incl ="algo.php";break;
            case "locations2": $incl = "locations2.php";break;
            case "global": $incl ="global.php";break;
            case "companies": $incl ="companies.php";break;
            case "accounts": $incl ="accounts.php";break;
            case "markers": $incl ="markers.php";break;
            case "tasks": $incl ="tasks.php";break;
            case "tasksdone": $incl ="tasksdone.php";break;
            case "analytics": $incl ="analytics.php";break;
            case "mp_using": $incl ="user_activity.php";break;
            case "checkpoints": $incl ="checkpoints.php";break;
            case "checkitems": $incl ="checkitems.php";break;
            case "tasktypes": $incl ="tasktypes.php";break;
            case "docs": $incl ="docs.php";break;
            case "reports": $incl ="reports.php";break;
            case "devices": $incl ="devices.php";break;
            case "projects": $incl ="projects.php";break;
            case "project_types": $incl ="project_types.php";break;
            case "projects_old": $incl ="projects_old.php";break;
            case "staff": $incl ="staff.php";break;
            case "objects": $incl ="objects.php";break;
            case "object": $incl ="object.php";break;
            case "typeobject": $incl ="typeobject.php";break;
            case "input_data": $incl ="input_data.php";break;
            case "jobs": $incl ="jobs.php";break;
            case "dashboard": $incl ="dashboard.php";break;
            case "journal": $incl ="journal.php";break;
	        case "filelib": $incl ="filelib/in.php";break;
	        case "addproject": $incl ="addproject.php";break;
	        case "oprt_management": $incl ="oprt_management.php";break;
            case "_peekdatasafe" : $incl = "_peekdatasafe.php";break;
            case "_log" : $incl = "_log.php"; break;
            //--Левое меню
            //Список устройств
            case "tmc/new" : case "tmc/list_materials" : case "tmc/detail/added" : $incl = "tmc/new.php"; break;
            case "tmc/repair" : case "tmc/repair_list" : $incl = "tmc/repair.php"; break;
            case "tmc/write" : case "tmc/write_list" : $incl = "tmc/write-off.php"; break;
            case "tmc/edit" : $incl = "tmc/edit.php"; break;
            //Передача устройств
            case "tmc/issued_tmcs" : $incl = "tmc/issued_tmcs.php"; break;
            case "tmc/free_tmcs" : $incl = "tmc/free_tmcs.php"; break;
            case "tmc/give" : case "tmc/list_materials_give" : $incl = "tmc/give.php"; break;
            case "tmc/take" : $incl = "tmc/take.php"; break;
            //Места хранения
            case "tmc/storage" : $incl = "tmc/new_storage.php"; break;
            case "tmc/find_cell" : $incl = "tmc/find_cell.php"; break;
            case "views/metrics" : $incl = "views/metrics.php"; break;
            default:
        }
    }
    else if ($cmdlevel==1)	//company admin
    {
        switch($act)
        {
            case "penalties": $incl ="penalties.php";break;
            case "loco": $incl ="loco.php";break;
            case "locations": $incl ="locations.php";break;
            case "companies": $incl ="companies.php";break;
            case "accounts": $incl ="accounts.php";break;
            case "markers": $incl ="markers.php";break;
            case "tasks": $incl ="tasks.php";break;
            case "tasktypes": $incl ="tasktypes.php";break;
            case "docs": $incl ="docs.php";break;
            case "reports": $incl ="reports.php";break;
            case "staff": $incl ="staff.php";break;
            case "projects": $incl ="projects.php";break;
            case "objects": $incl ="objects.php";break;
            case "input_data": $incl ="input_data.php";break;
            case "jobs": $incl ="jobs.php";break;
            case "dashboard": $incl ="dashboard.php";break;
            case "journal": $incl ="journal.php";break;
            default:
        }
    }
    else if ($cmdlevel==2)	//company ops
    {
        switch($act)
        {
            case "markers": $incl ="markers.php";break;
            case "tasks": $incl ="tasks.php";break;
            case "tasktypes": $incl ="tasktypes.php";break;
            case "docs": $incl ="docs.php";break;
            case "reports": $incl ="reports.php";break;
            case "staff": $incl ="staff.php";break;
            case "projects": $incl ="projects.php";break;
            case "input_data": $incl ="input_data.php";break;
            case "dashboard": $incl ="dashboard.php";break;
            case "journal": $incl ="journal.php";break;
            default:
        }
    }
    return array($incl,$accordnum);
}

function getConfirmTypeName($id)
{
    global $link;
    $query = mysqli_query($link,"select * from confirmtypes where id=".$id);
    if ($query && $res = mysqli_fetch_array($query))
    {
        $name = $res['name'];
    }
    return $name;
}

function GrabConfirmTypes($company = 0)
{
    global $link;
    $str = "select * from confirmtypes where company=0";
    $types = array();
    if ($company > 0)
        $str .= " OR company=".$company;

    //echo "GrabConfirmTypes $company $str";
    $query = mysqli_query($link,$str);
    while ($query && $res = mysqli_fetch_array($query))
    {
        array_push($types, $res);
    }
    //print_r($types);
    return $types;
}

function getConfirmTypebyTask($tid)
{
    global $link;
    $query = mysqli_query($link,"select type from tasks where id=".$tid);
    if ($res = mysqli_fetch_array($query)) {
        $tasktype = $res['type'];
//        echo "tid $tid tasktype $tasktype ";
    }
    $query = mysqli_query($link,"select confirmtype from tasktypes where id=".$tasktype);
    if ($res = mysqli_fetch_array($query))
    {
        $confirmtype = intval($res['confirmtype']);
//        echo " confirmtype $confirmtype ";
    }
    return $confirmtype;
}

function GetOnlineAccountList($byteAnswer = false)
{
    global $link;
    //$date2 = date(strtotime("-3 minutes"));
//    echo 'GetOnlineAccountList1';
    $date = 'last_seen_mobile';
    ///$query = mysqli_query("select * from accounts where DATE(".$date.") < (NOW() + INTERVAL 1 DAY)");
    $query = mysqli_query($link,"select * from accounts where ".$date." > (NOW() - INTERVAL 3 MINUTE)");
    $accs = array();
    while ($res = mysqli_fetch_array($query))
    {
        array_push($accs, $res);
    }
    if (!$byteAnswer)
    {
        ;
//        foreach ($accs as $acc)
//        {
//            echo 'online acc '.$acc['name'].'<br>';
//        }
    }
    else
    {
        $buf = "";//pack("C", 10);
        foreach ($accs as $acc) {
            $buf .= pack("l", $acc['id']);    //заголовок - номер пакета 1б и длина 2б. v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
        }
        $c = ConstructVariablePacket(10, $buf);
        echo base64_encode($c);
    }
}

function Online($acc_id)
{
    $acc = GetAccount($acc_id);
    return OnlineAccountCheck($acc['last_seen_mobile'], 1);
}

function TimeString($timeobj)
{
    if ($timeobj != null)
        return $timeobj->format('d.m.Y H:i');

    //return date('d.m.Y H:i', $timeobj);
}

function OnlineAccountCheck($last_seen)
{
    //var_dump($last_seen);
    global $onlineMobileTimeoutSeconds;
    $last_seen = date($last_seen);
    $time = (time()-strtotime($last_seen));
    //$date1 = date('d.m.Y H:i', strtotime($last_seen_mobile));
    if ($time <= $onlineMobileTimeoutSeconds)
        return true;
    return false;
}

function GrabTasksByType($type)
{
    global $link;
    $str = "select * from tasks where type=$type";
    $query = mysqli_query($link, $str);
    $tasks = array();
    while ($res = mysqli_fetch_array($query))
    {
        array_push($tasks, $res);
    }
    return $tasks;
}

function DeleteTasksByType($task_type, $full=true)
{
    global $link;
    $tasks = GrabTasksByType($task_type);
    foreach ($tasks as $task)
    {
        DeleteTask($task['id']);
    }
}

function ClearTaskTypeFromJobs($task_type)
{
    global $link;
    $query1 = mysqli_query($link, "select * from jobtypes where $task_type in (tasktypes)");
    $jobs = array();
    while ($res1 = mysqli_fetch_array($query1))
    {
        array_push($jobs, $res1);
    }
    //print_r($jobs);
    foreach ($jobs as $job)
    {
        $tasktypes = explode(",", $job['tasktypes']);
        foreach (array_keys($tasktypes, "$task_type") as $key) {
            unset($tasktypes[$key]);
        }
        $tasktypes = implode(",", $tasktypes);
        mysqli_query($link, "update jobtypes set tasktypes = '$tasktypes'");
    }
}

function DeletePic($path)
{
    unlink ( $path );
}

function DeleteTask($task_id, $full=true)
{
    //echo "DeleteTask!!!";
    CheckPoint::DeleteByTask($task_id);
    global $link;
    if ($full)
    {
        $subtasks = GrabSubTasks($task_id);
        foreach ($subtasks as $sub)
        {
            DeleteTask($sub['id'], false);
        }
    }
    $accid = GetAccountFromTask($task_id);
    Account::ClearTasksFromAccount($accid);
    mysqli_query($link, "delete from tasks where id =".$task_id);
}

function GetImagePathFromTask($task)
{
    $taskid = $task->id;
    $companyID = getCompanyByTask($taskid)[0];
    $project_id = $task->input_id;
    $imgpath = "data/$companyID/$project_id/$taskid/";
    return $imgpath;
}

function GetVideoPathFromTasktype($taskid)
{
//    $rootPath = $_SERVER['DOCUMENT_ROOT'];
//    $videoPath = $rootPath."/guides/$taskid/";
    $videoPath = "guides/$taskid/";
    return $videoPath;
}

//in minutes
function TimeSpent($timeStart, $timeEnd)
{
    $accepted  = strtotime($timeStart);
    $finished = strtotime($timeEnd);
    return round(($finished - $accepted)/60.0, 0, PHP_ROUND_HALF_UP);
    //return round (($finished - $accepted)/60.0, 2);
}

function TimeSpentForTaskFromArray($taskarr)
{
    $accepted_time = $taskarr['accepted_time'];
    $finished_time = $taskarr['finished_time'];
    $accepted  = strtotime($accepted_time);
    $finished = strtotime($finished_time);
    //return round (($finished - $accepted)/60.0, 2);
    return $finished - $accepted;
    //return round(($finished - $accepted)/60.0, 0, PHP_ROUND_HALF_UP);
}

function GetAssigneeNamesfromGlobal($taskid)
{
    global $link;
    $str = "select id from tasks where parent_id = $taskid";
    $query1 = mysqli_query($link, $str);
    $accids = array();
    while ($res1 = mysqli_fetch_row($query1)) {
//        array_push($accids, $res1['assignees_arr']);
        $accid = FindTaskOwner($res1[0]);
//        var_dump($accid);
//        echo "tid ".$res1[0];
        array_push($accids, $accid);
    }

    $accarr = array();
    $accnames = array();

    foreach ($accids as $accid)
    {
        if (!in_array($accid, $accarr)) {
            array_push($accarr, $accid);
            $accname = GetAccount($accid)['name'];
            array_push($accnames, $accname);
        }
    }
    $assignee_names_parent = implode(",", $accnames);
    return $assignee_names_parent;
}

function EchoScriptName($name)
{
    echo "<script>
    var page = '$name';";
    echo "</script>";
}


function GetProject($project_id)
{
    global $link;
    $str = "select * from projects_locotech where id = $project_id";
    
    $query1 = mysqli_query($link, $str);
    
    if ($res1 = mysqli_fetch_array($query1)) {
        return $res1;
    }
    return 0;
}

function GetLocoSerial($project_id)
{
    global $link;
    $str = "select loco_number from projects_locotech where id = $project_id";
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_row($query1)) {
        return $res1[0];
    }
    return 0;
}

function CleanTasks($project_id)
{
    global $link;
    $str = "select id from tasks where input_id = $project_id";
    $query1 = mysqli_query($link, $str);
    while ($res1 = mysqli_fetch_row($query1)) {
        $taskid = $res1[0];
        DeleteTask($taskid);
    }
}

function EchoTask2(Task $task, $activeid, $parent = false)
{
    global $entityManager;
    $tasktype_id = $task->type;
    /**
     * @var $type Tasktype
     */
    $type = Tasktype::Find($tasktype_id);

    $taskname = $type->name;
    $letter = $type->letter;
    $lettersign = "";
    if ($letter)
        $lettersign = "[Секция $letter]";
    $project_id = intval($task->project->id);
    $project = $task->project;
    //$action_id = $project->getAction();
//    $action = $project->getProjectType();
    $action = $project->projecttype;
//    if ($action != null)

//    if (!isset($action)) {
//        echo "action $action_id null";
//        return;
//    }
    try {
        $action_id = $action->id;
        $action_name = $action->name;
    }
    catch (Exception $e)
    {
//        echo "exception ".$e->getMessage();
//            \Doctrine\Common\Util\Debug::dump($action);
    }
    $created_time = TimeString($task->created);
    $taskid = $task->id;
    $assigned = TimeString($task->assigned);
    $zone = $task->zone_id;
    $zonename = GetZoneName($zone);
    $zone_req= $type->zone_required_id;
    $zone_req_name = GetZoneName($zone_req);
    $status = $task->status;
    $statusname = getTaskStatusName($status);
    $desc = $task->text;//$type->description;
    $loco = GetLocoSerial($project_id);
    $section = Section::Find($loco);
//    if ($section)
//        $loco = $section->getSectionNumber();
    $class = 'content__menu__task';
    $assignee_id = $task->assignees_arr;

    if ($activeid == $taskid)
        $class .= ' content__menu__task_active';
    else
        $class .= ' list';

    //PARENT LIST TO LEFT
    if ($parent) {
//        \Doctrine\Common\Util\Debug::dump(isset($task->getAccount());
        if ($task->getAccount() != null && 0 < $task->assignees_arr) {
            $assignee_names_parent = $task->getAccount()->name;//GetAssigneeNamesfromGlobal($taskid);
        }

        if ($status != '1')
            $statusname[0] .= ': '.$assignee_names_parent."<br> Выдана: $assigned ";

        //echo "111 $assignee_names_parent $taskid $class $taskname $desc $project_id  $action_id $action_name $created_time ".$statusname[0];
        echo "<div onclick='SelectTask($taskid)' class='$class'>
                <h3 class='content__menu__task-title'>
                    $taskid. $taskname <br>
                    $lettersign<br>
                    Описание: $desc
                </h3>
                <p class='content__menu__task-text'>
                    Проект: $project_id<br>
                    Тип проекта: $action_id. $action_name<br>
                    Локомотив №: $loco <br>
                    Создана: $created_time  <br>  <br>
                    $statusname[0]
                </p>                
            </div>";
    }
    else
    {
        $confirmtype = $type->confirmtype;
        $confirmname = getConfirmTypeName($confirmtype);
        $priority = $task->priority.'.';
        $assignee_names = GetAccount($assignee_id)['name'];
        if ($status =='2' || $status =='3' || $status =='5')
            $statusname[0] .= ': '.$assignee_names;
        $statustitle = $statusname[0];
        if ($status =='3')
            $statusname[0] = "<span style='color: green'>$statusname[0]</span>";

        $statusclass = 'content__main__item';

        switch ($status)
        {
            case '2': $statusclass .= ' content__main__item_wait'; break;
            case '3': $statusclass .= ' content__main__item_wait'; break;
            case '4': $statusclass .= ' content__main__item_wait'; break;
            case '5': $statusclass .= ' content__main__item_ready';
                $accepted_time = TimeString($task->accepted_time);
                $finished_time = TimeString($task->finished_time);
                $timetodo = intval($type->time_to_complete_minutes);
                $result = TimeSpent($accepted_time, $finished_time);
                //echo "acc $accepted_time fin $finished_time <br>";
                if (!$parent) {
                    if ($result >= 0)
                        $result = " за $result из $timetodo минут";
                    $statusname[0] .= ': ' . $accepted_time.$result;
                }
            break;
        }

        $zoneOk = (intval($zone_req)== intval($zone));
        if ($zoneOk)
        {
            $zoneText = "соответствие";
            $zonecolor = "green";
        }
        else {
            $zoneText = "неверно";
            $zonecolor = "red";
        }
        if ($zone)
            $zonestring =  "<span style='color: $zonecolor'>[$zoneText]</span>";
        else
            $zonestring =  "";
        echo "
        <div class='$statusclass' title='$statustitle'>
            <h3 class='content__main__item__title'>
                $priority $taskname
            </h3>
            <p class='content__main__item__text'>
               Тип задачи: $tasktype_id<br>
               Описание: $desc <br>
               Тип подтверждения: $confirmname<br>
               $taskid. Создана $created_time<br>
               Выдана: $assigned<br>
               Зона выполнения: $zone ($zonename) $zonestring<br>
               Зона выполнения требуемая: $zone_req ($zone_req_name)<br>
               $statusname[0]<br><br>
                Вы можете <span class='content__main__item__del' onclick='DelTask($taskid)'>удалить</span>
                или <span class='content__main__item__recall' onclick='Revoke($assignee_id)'>отозвать</span> эту задачу,
                если что-то пошло не так.
            </p>
        </div>
        ";

        $cps = CheckPoint::FindAllByTask($taskid);
        if (sizeof($cps) > 0)
        {

        //echo "<p>";
            echo "<div style='margin-left: 50px'>";
            echo "<h4>Контрольная карта:</h4>";
            foreach ($cps as $cp) {
                if ($cp->parentCheckpointId == 0)
                {
                    echo "<b>$cp->id. [$taskname]<br> $cp->name:</b><br>";
                }
                
                if ($cp->value != null)
                    echo $cp->value . '<br>';
//                else {
                    $children = $cp->childrenCheckpoints;
                    if (0 < count($children))
                    {
                        echo '<ul>';
                        foreach ($children as $child) {
                            if ('1' == $child->state)
                            {
                                if ('' == $child->value)
                                    echo "<li>$child->name</li>";
                                else
                                    echo "<li>$child->name: $child->value</li>";
                            }
                        // У чайлдов замечаний нет. ПИА.
                        /*$textnotes = $entityManager->getRepository('Tasknote')->findBy(array('checkpoint_id' => $child->id));
                        foreach ($textnotes as $tn)
                        {
                            echo "Замечание: $tn->text<br>";
                        }/**/
                        }
                        echo '</ul>';
                    }
//                }
                    
                if ($cp->parentCheckpointId == 0)
                {
                    $textnotes = $entityManager->getRepository('Tasknote')->findBy(array('checkpoint_id' => $cp->id));
                    foreach ($textnotes as $tn)
                    {
                        echo "<pre>  Замечание: $tn->text</pre>";
                    }
                }

            }
            echo "</div><br><br>";
        }
        //echo "</p>";
        //LOAD MEDIA DATA

        $imgpath = GetImagePathFromTask($task);
        $files1 =  scandir($imgpath);
        //print_r($files1);

        if (sizeof($files1) > 2)
        {
            echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';
            $x = '';
            foreach ($files1 as $file )
            {
                $prevx = $x;
                $x = pathinfo($file)['extension'];
                if ($prevx != '' && $prevx != $x)
                    echo "<br>";

                if($file === '.' || $file === '..') {continue;}
                if ($x == 'jpg') {
                    echo "<div class='content__main__imgwrap'>";
                    echo "<img title='$file' src='$imgpath$file' width =112 height='84' class='content__main__img' onclick=\"openpic('" . $imgpath.$file . "')\">";
                   echo '<img src="ProSysNew/delete.svg" alt="удалить" class="content__main__imgdel" onclick=delpic("'. $imgpath . $file .'")>';
                     echo '</div>';
                }
                if ($x == 'mp3') {
                    echo "<div class='content__main__imgwrap'>
                            <img class='content__main__img' title='$file'  onclick=\"openaudio('" . $imgpath . $file . "')\"  src='images/audio.svg'>
                    </div>";
                    //  echo "<a href='$imgpath$file'>$file</a>";
                }
            }
            echo '</div>';
        }
        $notes = FindTaskNotes($taskid);
        if (sizeof($notes) > 0) {
            echo "<div style='float:none; background-color: rgba(0,170,255,0.03); padding: 5px; border: solid; margin-right:44px; margin-left:44px;  border-width: .5px; border-color: #9cb2c4; border-radius: 10px; border-top-left-radius: 0px;'><p><b>Текстовые заметки: </b></p>";
            foreach ($notes as $note) {
                if (!$note['checkpoint_id']) {
                    $notedate = $note['date'];
                    $noteid = $note['id'];
                    $notetext = $note['text'];
                    echo "<p><b>$noteid.</b> [$taskname] $notetext</p>";
                }
            }
            echo '</div><br><br>';
        }
    }
    //locotube
    if ($task->parent_id) {
        echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';
        showVideoLinks($task);
//        getTaskVideos($task);
        echo '</div>';
    }
    //video files
        echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';

            $ocsVideo = OCSgetvideo($taskid);
            $splitted = explode(",",$ocsVideo);
            $domain = "http://ocs.prmsys.net/video/";

            foreach ($splitted as $spl) {
                if ($spl == "")
                    continue;
                $link = "$domain$spl";
                echo "<div class='content__main__imgwrap' onclick=\"openvideo('$link')\">
                    <video height='144' class='content__main__img' preload='metadata' title='$link'>
                        <source src='$link'>
                    </video>
                </div>";
            }
        echo '</div>';
    echo '<div>';
    if ($status != '1')
        echo " <input style='margin-right: 20px' type='button' onclick='ReopenTask($taskid)' value='Открыть заново'>";

    echo '</div>';
}

function showVideoLinks($task)
{
    $urls = \app\models\entity\Locotube::getLinks($task, 310);
    foreach ($urls as $url): ?>
        <a href="<?= $url ?>" target="_blank">
            <img style="width: 32px; height: 32px; margin-bottom: 14px" src="images/mp4.png" alt="mp4">
        </a>
    <? endforeach;
}

function getTaskVideos(Task $task)
{
    if ('DateTime' != get_class($task->accepted_time)) return;

    $userId = $task->getAccount()->getId();

    $sp = DIRECTORY_SEPARATOR;

    $path = $sp . 'uploads' . $sp . 'locotube' . $sp . $userId . $sp;
    $fullPath = __DIR__ . $path;
    if (is_dir($fullPath)) {
        $files = scandir($fullPath);

        $start = $task->accepted_time;
        $finish = $task->finished_time;
        foreach ($files as $file) {
            if ($file[0] == '.') continue;

            $videoDate = parseDate($file);
            if ($start <= $videoDate && $videoDate <= $finish) { ?>
                <a href="/player.php?file=<?= $path . $file ?>" target="_blank">
                    <img style="width: 32px; height: 32px; margin-bottom: 14px" src="images/mp4.png" alt="mp4">
                </a>
            <?php
            }
        }
    }
}

function parseDate(string $str)
{
    $date = new DateTime();
//    $date->setTimezone(new DateTimeZone('+0010'));
    $y = substr($str, 0, 4);
    $m = substr($str, 5, 2);
    $d = substr($str, 7, 2);
    $date->setDate($y, $m, $d);
    $h = substr($str, 10, 2);
    $i = substr($str, 12, 2);
    $s = substr($str, 14, 2);
    $date->setTime($h, $i, $s);

    return $date;
}

function FindTaskNotes($taskID)
{
    global  $link;
    $query = mysqli_query($link,"select * from task_notes where task_id=".$taskID);
    $notes = array();
    while ($res1 = mysqli_fetch_array($query))
    {
        array_push($notes, $res1);
    }
    return $notes;
}

function ActionsForm($action_data, $c_action)
{
    echo "<option selected value = '0' ><Выберите тип проекта></option >";
    foreach ($action_data as $val) {
        if ($val->id == $c_action)
            $sel = 'selected';
        else
            $sel = '';
        echo "<option $sel value = '".$val->id."' > ".$val->name."</option >";
    }
}

function AddJob($acc_id, $new_jobtype_id, $job_ids)
{
    global  $link;
    $job_ids .= ','.$new_jobtype_id;
    mysqli_query($link, "update accounts set jobtypes='".$job_ids."' where id=".$acc_id);
    echo "<span style='color: darkolivegreen'>Должность добавлена!</span><br><br>";
}


function JobTaskTypesIDs($job_id)
{
    $tts = GrabJobTaskTypes($job_id);
    $arr = array();
    if (sizeof($tts) > 0) {
        foreach ($tts as $tt) {
            array_push($arr, $tt->id);
        }
    }
    return $arr;
}

function GrabJobTaskTypes($job_id)
{
    /**
     * @var Jobtype$jobtype
     */
    $tasktypes = array();
    $jobtype = Jobtype::Find($job_id);
    if ($jobtype != null)
        $tasktypes = $jobtype->getTaskTypes();

    return $tasktypes;
}

//function GrabJobTaskTypes($job_id)
//{
//    global $link;
//    $subtaskarr = array();
//    $query = mysqli_query($link,"select tasktypes from jobtypes where id=".$job_id);
//    if ($res = mysqli_fetch_row($query)) {
//        $tasktype_data = $res[0];
//        $subtaskarr = explode(",", $tasktype_data);
//    }
//    return array_filter($subtaskarr);
//}

function ShowJobTasks($job_id)
{
    $subtaskarr = GrabJobTaskTypes($job_id);
    foreach ($subtaskarr as $taskid) {
        $taskarr = GrabTasktype($taskid);
        $name = $taskarr['name'];
        if ($name != '')
            echo '<span style=\'color:blue\'>'.$taskarr['name'].'</span> <b>|</b> ';
    }
}

function FillArrayString($elem_name, $make_array = false)
{
    //echo sizeof($_REQUEST)." elname $elem_name<br>";
    //print_r($_REQUEST);
    $subtask_arr = array();
    foreach (array_keys($_REQUEST) as $var) {
        //echo "var $var ${$var} <br>";
        $sub = substr($var, 0, -1);
        $sub2 = substr($var, 0, -2);
        $sub3 = substr($var, 0, -3);
        //echo "sub $sub<br>";
        if ($sub === $elem_name || $sub2 === $elem_name || $sub3 === $elem_name)
        {
            if ($_REQUEST[$var] != '')
                array_push($subtask_arr, $_REQUEST[$var]);
        }
    }
    
    $subtask_string = implode(",", $subtask_arr);
    if ($make_array) {
        $subtask_string = $subtask_arr;
    }
    //print_r($subtask_arr);
    return $subtask_string;
}


function ShowTasksSelect($arr, $c_action=0, $id="", $keyword, $alg=false)
{
    if ($id !="") {
        $id = "id='$id'";
    }
    $max = sizeof($arr);
    echo "<select onchange='AddSelect(this.value, $max)' $id class='form-input content__main__form__goal'  name='$keyword"."1' >";
    echo '<option value=""></option>';
    $count=1;
    foreach ($arr as $res1) {
        if ($c_action ==0 || $res1->action == $c_action)
        {
            $tasktype_id = $res1->id;
            $taskname = $res1->name;
            if (!isset($taskname)) {
                $type = $res1->type;
                $name = GetTaskNameAndDesc($type)[0];
                $taskname = "$tasktype_id. $name [$type]";
            }
            echo "<option value='$tasktype_id'>$count. $taskname</option>";
            $count++;
        }
    }
    echo '</select><br>';
    if ($alg) {
        echo "<select style='margin-left:20px ' class='form-input content__main__form__goal' id='alg' name='alg' >";
        echo '<option value="">Собрать результат выполнения задачи</option>';
        echo '<option value="">Составить промежуточную таблицу</option>';
        echo '<option value="">Алгоритм3</option>';
        echo '<option value="">Алгоритм4</option>';
        echo '</select><br>';
    }
}

function GetJobtypes($companyID)
{
    global $link;
    $query1 = mysqli_query($link, "select * from jobtypes where company=$companyID");
    $jobtypes = array();
    while ($res1 = mysqli_fetch_array($query1))
    {
        array_push($jobtypes, $res1);
    }
    return $jobtypes;
}

function GetAccountFromTask($task_id)
{
    global $link;

    $str = "select assignees_arr from tasks where id = ".$task_id;
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_row($query1)) {

        return $res1[0];
    }
    return null;
}

function GetVagrantTagID($acc_id)
{
    global $link;

    $str = "select tagid from vagrant_log where acc_id = $acc_id ORDER BY id DESC limit 1";

    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_row($query1)) {

        return $res1[0];
    }
    return null;
}

function GetAccount($acc_id)
{
    global $link;

    $str = "select * from accounts where id = ".$acc_id;
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_array($query1)) {

        return $res1;
    }
    return null;
}

function GetAccountJobs($acc_id)
{
    global $link;
//    echo 'GetAccountJobs '.$acc_id;
    //get free accs (without active tasks)
    $str = "select * from accounts where id = ".$acc_id;
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_array($query1)) {
//        echo 'jobs '.$res1['jobtypes'];
        $jobtypes = explode(",",$res1['jobtypes']);
        return $jobtypes;
    }
}

function GetCMDName($cmdlevel)
{
    global $link;
    $str = "select name from accounttypes where type = ".$cmdlevel;
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_array($query1))
        return $res1['name'];
}


function GetTasksFromProjectString($projectid)
{
    global $link;
    $str = "select tasks from projects_locotech where id = $projectid";

    $query1 = mysqli_query($link, $str);
    $ret = array();
    if ($res1 = mysqli_fetch_row($query1))
    {

        $ret = $res1[0];
    }
 
    return $ret;
}

function GetTasksForProject($projectid, $status=0, $inactiveproject=0, $subs = 0)
{
    global $link;
            
    $taskstring = GetTasksFromProjectString($projectid);
    if ($inactiveproject != 0)
    {
        $str = "select COUNT(id) from tasks where id in ($taskstring) and (status=2 or status=3)";
        $query1 = mysqli_query($link, $str);
        if ($res1 = mysqli_fetch_row($query1))
        {
            $count = intval($res1[0]);
            if ($count > 0) {
                echo "Found started tasks!";
                return;
            }
        }
    }
    if ($subs > 0) {

        //echo "subss!";
        $tasksarr = explode(",", $taskstring);
        foreach ($tasksarr as $task_id)
        {
            $parent = GrabTask($task_id);
            if ($parent['status'] == $status) {
                return GrabSubTasks($task_id);
            }
        }
    }
    $statusstr = '';
    if ($status != 0)
        $statusstr .= " and status=$status";

//    $str = "select * from tasks where input_id = ".$projectid." and parent_id=0";
    $str = "select * from tasks where id in ($taskstring)$statusstr";
    $query1 = mysqli_query($link, $str);
    $ret = array();
    
    while ($res1 = mysqli_fetch_array($query1))
        array_push($ret, $res1);
    return $ret;
}

function GetJobNames($jobtypes)
{
    global $link;
    $jobnames = array();
    foreach ($jobtypes as $jobid)
    {
//        echo ' jobid '.$jobid;
        $str = "select name from jobtypes where id = ".$jobid;
        $query1 = mysqli_query($link, $str);
        if ($res1 = mysqli_fetch_array($query1)) {
            $jobname = $res1['name'];
//            echo ' jobname '.$jobname;
            //$jobnames[$jobid] = $jobname;
            array_push($jobnames, $jobname);
        }
    }
    return $jobnames;
}

function TaskReopen($tid)
{
    global $link;
    mysqli_query($link, "update tasks set status=1, assignees_arr=0 where id=".$tid);
}

function FindUrgentAccounts()
{
    global $link;
    $str ="select DISTINCT a.id, p.id from accounts a join tasks t on t.assignees_arr= a.id  join projects_locotech p on p.id = t.input_id where p.urgent=1 and p.status<5";
    $query = mysqli_query($link, $str);
    $retarr = array();
    while ($res = mysqli_fetch_row($query))
    {
        $retarr[] = $res[0];
    }
    return $retarr;
}

function CheckPreferredAssignee(&$opentasks, $echo)
{
    global $link;
    $pids = array();
    $prefs = array();
    foreach ($opentasks as &$opentask)
    {
        $tid = $opentask['id'];
        $pref = intval($opentask['preferred_assignee']);

        if ($pref > 0) {
            if ($echo)
                echo ("CheckPreferredAssignee pref>0: $tid");
            $opentask['status'] = 2;
            $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=$pref where id=$tid";
            mysqli_query($link, $str);

            $pid = intval($opentask['parent_id']);
            if ($pid > 0 && !in_array($pid, $pids)) {
                $pids[] = $pid;
                $prefs[$pid] = $pref;
            }
        }
    }
    if ($echo) {
        $plen = sizeof($pids);
        echo("pids len: $plen");
    }
    foreach ($pids as $pid)
    {
        $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=".$prefs[$pid]." where id=$pid";
        mysqli_query($link, $str);
    }
}

function TasksAssignCore($freeaccounts, $task_id, $execute, $project_id, $echo = false)
{
    global $link, $companyID;
    
    $assigned_tasks = array();
    $accsused = array();
    $project = null;
    if ($task_id =='' || !isset($task_id))
    {
        if ($project_id == 0)
            $opentasks = GrabOpenTasks('subtasks');   //array of mysql res, tasks status=1
        else {
            $project = Project::Find($project_id);
            $opentasks = GetTasksForProject($project_id, 1, 0, 1);
        }
    }
    else
        $opentasks = GrabTasksFromGlobal($task_id);
//select * from accounts a left outer join tasks t on t.assignees_arr= a.id  left outer  join projects_locotech p on p.id = t.input_id where p.urgent=1 and a.id=1

    CheckPreferredAssignee($opentasks, $echo);

    if ($echo)
    {
        echo "<br>opentasks:<br>";
        var_dump($opentasks);

        echo "<br>freeaccounts:<br>";
        var_dump($freeaccounts);
    }
    $assigned_accs = array();
//    if ($echo) {
//        echo "<br>freeaccounts";
//        var_dump($freeaccounts);
//    }
    foreach ($freeaccounts as $acc_id=>$jobtypesIds)
    {
        $parent_id = 0;
        $assigned_accs[$acc_id]  = array();
        if (!in_array($acc_id, $accsused))
        {
            $tasktypesJob = array();
            foreach ($jobtypesIds as $job_type) {
                $tasktypesJob = array_merge($tasktypesJob, JobTaskTypesIDs($job_type));
            }
            foreach ($opentasks as $opentask)
            {
                $taskid = $opentask['id'];
                if (intval($opentask['status']) > 1)
                    continue;

                $exists = array_key_exists($taskid, $assigned_tasks);
                if ($echo)
                    echo ' key exists '.$taskid.' '.($exists == true).'<br>';
                if (!$exists) {
                    // echo '!exists';
                    if (in_array($opentask['type'], $tasktypesJob)) {
                        if ($echo)
                            echo ' job available task type '.$opentask['type'].' ';
                        $pid = intval($opentask['parent_id']);
                        if ($pid != $parent_id && in_array($acc_id, $accsused)) {//parent change = stop for this acc
                            if ($echo)
                                echo "cont1";
                            continue;
                        }
                        else
                            $parent_id = $pid;
                        $parent = GrabTask($parent_id);
                        $parenttype = $parent['type'];

                        $tgrab = GrabTasktype($parenttype);
                        $tsize = sizeof($tgrab);
                        if ($tsize == 0)
                            DeleteTasksByType($parenttype);

                        //фикс блуждающих подзадач без парента и тасктипа парента
                        if (($parent_id > 0 && GrabTask($parent_id) == null) || $tsize == 0)
                        {
                            if ($echo)
                                echo "skip2 id $parent_id<br>";
                            continue;
                        }
                        Assign($accsused, $assigned_tasks, $assigned_accs, $acc_id, $taskid, $execute);
                        if ($echo) {
                            echo "assigned_tasks:<br>";
                            var_dump($assigned_tasks);
                            echo "assigned_accs: <br>";
                            var_dump($assigned_accs);
                        }
                    }
                }
            }
            if ($execute)
            {
                $parent_updated = false;
                foreach ($assigned_accs as $acc)
                {
                    if (sizeof($assigned_accs[$acc_id]) == 0)
                        continue;
                    $tasks = implode(',', $acc);    //taskarr
                    foreach ($acc as $tsk) {
                        if (in_array($tsk, $assigned_accs[$acc_id])) {

                            if ($echo) {
                                echo '<br>updating task ' . $tsk . ' setting ass ' . $acc_id;
                            }
//                            var_dump($acc_id);
                            OCStaskstatus($tsk, 2, $acc_id);
                            $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=$acc_id where id=$tsk";
                            require_once 'tmc/yiiInit_once.php';
                            \app\models\ElasticLog::command((int)$tsk, 'Назначение');
                            //echo '<br>'.$str;
                            mysqli_query($link, $str);   //создание подзадач
                        }
                    }
                    if ($parent_id != 0)
                        $tasks = $parent_id.','.$tasks;


//                    mysqli_query($link, "update accounts set active_task_ids = '$tasks' where id=".$acc_id);   //создание подзадач
                    if ($parent_id != 0 && !$parent_updated) {
                        $parent_updated = true;
                        OCStaskstatus($parent_id, 2, $acc_id);
                        mysqli_query($link, "update tasks set status = 2, assigned=NOW(), assignees_arr=$acc_id where id=" . $parent_id);
                        $proj = getProjectByTask($parent_id);
                        mysqli_query($link, "update projects_locotech set status = 2 where id=".$proj['id']);
                    }
                }
            }
        }
    }
    return $assigned_accs;
}

function CheckPush($accounts, $echo=false)
{
    foreach ($accounts as $account)
    {
//        if ($echo)
//            \Doctrine\Common\Util\Debug::dump($account);
        $lastpush = TimeString($account->last_push_message_sent);

        $time = (time()-strtotime($lastpush));
        if ($echo)
            echo $account->name." time $time";
        if ($time > 30)
            SendPush($account->id, "Check your SMoPP application!", "");
    }
}


function TasksAssign($task_id, $execute, $project_id = 0, $echo = false, $source = 0)
{
    //1 ищем онлайн акки без тасков
    //2 определяем основные должности акков
    //3 определяем замещяющие должности акков
    //4 определяем доступные задачи по должностям
    //5 берем активные (невыданные) задачи
    //6 выдаем подходящим основным аккам их подзадачи
    //7 выдаем подходящим замещающим аккам их подзадачи
    global $companyID;
    $freeaccountsPrimary = array();
    $freeaccountsSecondary = array();

    /**
     * @var $company Company
     */
    $company = Company::Find($companyID);
//    $last_assign = strtotime(TimeString($company->last_assign));
//    $time = (time()-$last_assign);
//    if ($echo)
//    {
//        var_dump($last_assign);
//        var_dump($time);
//    }
//
//    if ($time < 10)
//    {
//        if ($echo)
//            echo "часто";
//        return null;
//    }

    $companyID = $company->id;

    $company->last_assign = new \DateTime("now");
    $company->Save();

    if ($company == null)
        return array();

    $project = null;
    $urgent = 0;
    if ($project_id > 0)
    {
        $project = Project::Find($project_id);
        if ($project != null && intval($project->getStatus()) < 5 )
        {
            $urgent = $project->urgent;
        }
    }
    if ($urgent >0)
        $accs = $company->GetOnlineAccounts(true, true);
    else
        $accs = $company->GetIdleAccounts();

    if ($echo) {
        var_dump($urgent);
        if ($urgent >0)
            echo "urgent accs: ";
        else
            echo "idle accs: ";
        \Doctrine\Common\Util\Debug::dump($accs);
        echo "<br>";
    }

    $online_counter = sizeof($accs);
    foreach ($accs as $acc)
    {
        $jobtypesIdsPrimary = array();
        $jobtypesIdsSecondary = array();
        /**
         * @var $acc Account
         */
//        $last_seen_mobile = TimeString($acc->getLastSeenMobile());
//        $online_mobile = OnlineAccountCheck($last_seen_mobile);
//        if (!$online_mobile)
//            continue;
//        else
//            $online_counter++;
        $acc_id = $acc->getId();
        $jobtypes = $acc->getJobtypesExtended();
        foreach ($jobtypes[0] as $jobtype)
        {
            $jobtypesIdsPrimary[] = $jobtype->id;
        }
        foreach ($jobtypes[1] as $jobtype)
        {
            $jobtypesIdsSecondary[] = $jobtype->id;
        }
        $freeaccountsPrimary[$acc_id] = $jobtypesIdsPrimary;
        $freeaccountsSecondary[$acc_id] = $jobtypesIdsSecondary;
    }

    if ($online_counter == 0)
    {
        if ($echo)
            echo "<h3><span style='color:red'>Задачи не выданы в работу! Нет подходящих исполнителей онлайн</span></h3>";
        return array();
    }

    $assigned_accs1 = TasksAssignCore($freeaccountsPrimary, $task_id, $execute, $project_id, $echo);
    if ($echo) {
        echo "<br> assigned_accs1: ";
        var_dump($assigned_accs1);
    }

//    $assigned_accs2 = array();

    $accs1str = "";
    foreach ($assigned_accs1 as $id=>$taskids)
    {
        if (sizeof($taskids) > 0) {
            $acstr = implode(',',$taskids);
            $accs1str .= " $id: $acstr | ";
            SendPush($id, "You have a new task!", $acstr);
        }
//        var_dump($taskids);echo "<br>";
//        foreach ($taskids as $tid)
//        {
//            $task = Task::Find($tid);
//            if ($task != null)
//            {
//                $tt = $task->type;
//            }
//        }
//        if (sizeof($freeaccountsSecondary[$id]) > 0 && sizeof($taskids)>0) {
//            $task = Task::Find($taskids[0]);
//            if ($task != null) {
//                $proj_id = $task->input_id;
////            var_dump($proj_id);echo "<br>";
//                $freeaccs = array($id => $freeaccountsSecondary[$id]);
////            var_dump($freeaccs);echo "<br>";
//                $assigned_accs2 = TasksAssignCore($freeaccs, '', true, $proj_id);
////            var_dump($assigned_accs2);echo "<br>";
//            }
//        }
        if (sizeof($taskids) > 0)
            unset($freeaccountsSecondary[$id]);
    }
    $assigned_accs3 = TasksAssignCore($freeaccountsSecondary, $task_id, $execute, $project_id, $echo);
    foreach ($assigned_accs3 as $id=>$taskids)
    {
        if (sizeof($taskids) > 0) {
            $acstr = implode(',',$taskids);
            $accs1str .= " $id: $acstr | ";
            SendPush($id, "You have a new task!", $acstr);
        }
    }
    if ($accs1str != '')
        LogTaskAssign("Account: $source $accs1str");

//    if ($echo) {
//        echo "<br>  assigned_accs3: ";
//        var_dump($assigned_accs3);
//    }
    $retarr = array_merge($assigned_accs1, $assigned_accs3);
//    var_dump($retarr);

    return $retarr;
}

function LogTaskAssign($text)
{
    global $link;
    mysqli_query($link, "insert into task_assign_log (msg, created) values ('$text', NOW())");
}

function SendPush($accid, $text, $tskid)
{
    global $link;
    $acc = Account::Find($accid);
    if ($acc != null) {
        $android_token_id = $acc->android_token_id;
        if ($android_token_id) {
            //$f = file_get_contents("http://corp.prmsys.net/?act=staff");
            $text = "AccountId $accid taskids $tskid ".$text;
            $text = urlencode($text);
            require_once "fcm/SendNotification.php";
            $oldKey = ($acc->getCompany()->id == 1);
            Send($text, $android_token_id, $oldKey);
            $str = "update accounts set last_push_message_sent = NOW() where id=$accid";
            mysqli_query($link, $str);

//            $f = file_get_contents("http://corp.prmsys.net/fcm/SendNotification.php?text=$text&token=$android_token_id");
//            echo $f;
        }
//        else
//            echo "invalid token";
    }
}

function SetAccordNum($num)
{
    echo '<div style="display: none" id="accordnum">'.$num.'</div>';
}


function GetTaskNameAndDesc($type)
{
    global $link;
    $str = "select name, description from tasktypes where id = $type";
    $query1 = mysqli_query($link, $str);
    if ($res1 = mysqli_fetch_row($query1)) {
        return $res1;
    }
    return '';
}

function GetAccountTasksStatus()
{


}

function Assign(&$accsused, &$assigned_tasks, &$assigned_accs, $acc_id, $taskid, $execute=false)
{
    global $link;
    //echo '<br>foundacc ' . $acc_id .' task type '.$opentask['type'].' task id '.$opentask['id'].'<br>';
   // echo '<br>foundacc ' . $acc_id;
    if (!in_array($acc_id, $accsused)) {
        array_push($accsused, $acc_id);
    }

    $req = "select account_id from refuses where created > date_sub(NOW(), interval 2 minute) and account_id = "
            .$acc_id
            ." and main_task_id = (select parent_id from tasks where id = "
            .$taskid
            .")";
    //echo '<pre>'; var_dump($req);
    $taskrefused = mysqli_query($link, $req);
    //echo '<pre>'; var_dump($taskrefused);
    $isrefusedthistask = mysqli_fetch_array($taskrefused);/**/
    //echo '<pre>'; var_dump($isrefusedthistask);
    //die();
    if (count($isrefusedthistask) == 0)
    {
        $assigned_tasks[$taskid] = $acc_id;
        array_push($assigned_accs[$acc_id],$taskid);
    }
    //echo '<br>Assigned opentask type '.$opentask['type'].' id '.$opentask['id'].'<br>';
    return false;
}

function GrabTasksForAccount($acc_id, $status=0)
{
    global $link;
    $str = "select * from tasks where assignees_arr = $acc_id";
    if ($status != 0)
        $str .= " and status=".$status;
    $str .= " and status < 5";
    //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
    $query1 = mysqli_query($link, $str);
    $tasks = array();
    while ($res1 = mysqli_fetch_array($query1)) {
        array_push($tasks, $res1);
    }
    return $tasks;
}

function GrabTasksFromGlobal($task_id)
{
//    echo 'GrabTask '.$task_id;
    global $link;
    $str = "select * from tasks where parent_id = $task_id and status=1";
    //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
    $query1 = mysqli_query($link, $str);
    $tasks = array();
    while ($res1 = mysqli_fetch_array($query1)) {
        array_push($tasks, $res1);
    }
    return $tasks;
}

function GrabTask($task_id)
{
    global $link;
    $str = "select * from tasks where id = ".$task_id;
    //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
    $query1 = mysqli_query($link, $str);

    if ($res1 = mysqli_fetch_array($query1)) {
        $result = sizeof($res1);
        //echo 'GrabTask '.$task_id.' size '.$result;
        return $res1;
    }
    //echo 'GrabTask res null';
    return null;
}

function GrabTasks($taskstring)
{
    global $link;
    $tasks = array();
    $task_ids = explode(',',$taskstring);
//    echo 'taskstring '.$taskstring;
    foreach ($task_ids as $task_id)
    {
        $str = "select * from tasks where id = $task_id";
        $query1 = mysqli_query($link, $str);

        if ($res1 = mysqli_fetch_array($query1)) {
            array_push($tasks, $res1);
        }
    }
    return $tasks;
}

function GrabSubTasks($parent_id)
{
    global $link;
    $subtasks = array();
    $str = "select * from tasks where parent_id = $parent_id";
    $query1 = mysqli_query($link, $str);

    while ($res1 = mysqli_fetch_array($query1)) {
        array_push($subtasks, $res1);
    }

    return $subtasks;
}


function GrabOpenTasks($flag = 'all')
{
    if ($flag == 'subtasks')
        $add = ' and parent_id > 0';
    else
        $add = ' and parent_id = 0';

    global $link, $companyID;
    //$str = "select * from tasks where status = 1";
    $str = "select t.* from tasks t join projects_locotech p on t.input_id = p.id and p.company=$companyID where t.status = 1";
//    echo $str;
    //echo "opentasks $str<br>";
    $query1 = mysqli_query($link, $str.$add);
    $alltasks = array();
    while ($res1 = mysqli_fetch_assoc($query1)) {
        $id = $res1['id'];
        $parent_id = $res1['parent_id'];
        //echo "parent_id $parent_id ";
        if ($flag == 'subtasks' && GrabTask($parent_id) == null)
        {
            echo "parent_id skip $parent_id<br>";
            continue;
        }
        array_push($alltasks, $res1);
        if ($flag == 'all') {  //subtasks in main select
            $subs = GrabSubTasks($id);
            $alltasks = array_merge($alltasks, $subs);
        }
    }
//    var_dump($alltasks);
    return $alltasks;
}

function GrabTasktype($id)
{
    global $link;
    $str = "select * from tasktypes where id=$id";

    $query1 = mysqli_query($link, $str);

    if ($res1 = mysqli_fetch_array($query1)) {
        return $res1;
    }
    return array();
}

function GetListFromDB($class, $key, $value, $sortby="id", $sort="ASC")
{
    global $entityManager;
    return $entityManager->getRepository($class)->findBy(array($key => $value), array($sortby => $sort));
}

function GetArrayFromDB($class, $array, $sortby="id", $sort="ASC")
{
    global $entityManager;
    return $entityManager->getRepository($class)->findBy($array, array($sortby => $sort));
}

function GrabActions($id)
{
    $actions = array();
    return $actions;
}

function CreateTasks($tasktypesarr, $input_id=0)
{
    global $link;
    //echo "CreateTasks sizetask ".sizeof($tasktypesarr);

    $maintasks = array();
    foreach ($tasktypesarr as $tasktype)
    {
        /**
         * @var Tasktype $tasktype
         */
        if ($tasktype->main_task == '1')
        {
            $tid = $tasktype->id;

            $subtaskarr = explode(",", $tasktype->subtasks);
//            $subtaskarr = $tasktype->getTasktypes();

            $str = "INSERT INTO tasks (type, status, priority, created, input_id) VALUES ($tid, 1, 0, NOW(), $input_id)";
//            echo $str;
           $result = mysqli_query($link, $str);   //создание глобальной задачи

            if (mysqli_affected_rows($link) >0 )
            {
                $parent_id = mysqli_insert_id($link);
                array_push($maintasks, $parent_id);

                $priority = 1;
                
                foreach ($subtaskarr as $subid) {

                    $str = "insert into tasks (type, parent_id, priority, status, created, input_id) values ($subid, $parent_id, $priority, 1, NOW(), $input_id)";
                    $sub_id = mysqli_insert_id($link);
                    require_once 'tmc/yiiInit_once.php';
                    \app\models\ElasticLog::command((int)$sub_id);
                    //создаем парентов
                    $types = \CheckPointTypes\CheckPointType::GetCheckPointTypesByTask($subid);
                    if (sizeof($types) > 0) {
                        $q = mysqli_query($link, "select MAX(id) from tasks");
                        if ($res = mysqli_fetch_row($q))
                        {
                            $myid = intval($res[0]);
                            foreach ($types as $typeID) {
//                                echo "create type " . $typeID['cp_type_id'];
                                //var_dump($typeID['cp_type_id']);die();
                                $cpt = \CheckPointTypes\CheckPointType::CreateFromID($typeID['cp_type_id']);
                                if ($cpt != null)
                                    $cp = \CheckPoints\CheckPoint::CreateFromType($cpt, null, $myid+1);
                            }
                        }
                    }

                    mysqli_query($link, $str);   //создание подзадач
                    $priority++;
                }
            }

        }
    }
    if (sizeof($maintasks) > 0) {
        //echo " <span style='color: green'>Задачи созданы для проекта $input_id!</span>";
        $taskstring = implode(",",$maintasks);
        AddTasksToProject($taskstring, $input_id);
    }
//    else
//        echo '<span style="color: red;"> Нет ни одной основной задачи!</span><br>';
}

function AddTasksToProject($taskstring, $input_id)
{
    global $link;
    $str = "update projects_locotech set tasks = '$taskstring' where id= $input_id";
    mysqli_query($link, $str);
}

function GrabTasktypesStringFromAction($actionid)
{
    global $link;
    $str = "select tasktypes from project_types where id=$actionid";
    $query1 = mysqli_query($link, $str);
    $ret = array();
    if ($res1 = mysqli_fetch_row($query1))
    {
        $ret = $res1[0];
    }
    return $ret;
}


//получить сабтаски по компании
//получить таски по компании
//получить и таски и сабтаски по компании

function GrabTasktypes($chooseSubtasks = "all")
{
    global $link, $companyID, $entityManager;
    //$list = GetListFromDB('Tasktype', 'company', $companyID, 'id', 'DESC');
    $str = "SELECT t FROM Tasktype t";    //DOCTRINE
    $str .= " WHERE t.company=$companyID";
    if ($chooseSubtasks == "subs")
        $str .= " and t.main_task = 0";
    else if  ($chooseSubtasks == "tasks")
        $str .= " and t.main_task = 1";

    //$str .= ' ORDER BY t.name ASC';
    $str .= ' ORDER BY t.id DESC';

    $query = $entityManager->createQuery($str);
    $list = $query->getResult();
    return $list;
}

function GrabTasktypesIDs($chooseSubtasks = "all")
{
    global $link, $companyID, $entityManager;
    //$list = GetListFromDB('Tasktype', 'company', $companyID, 'id', 'DESC');
    $str = "SELECT t.id FROM Tasktype t";    //DOCTRINE
    $str .= " WHERE t.company=$companyID";
    if ($chooseSubtasks == "subs")
        $str .= " and t.main_task = 0";
    else if  ($chooseSubtasks == "tasks")
        $str .= " and t.main_task = 1";

    $str .= ' ORDER BY t.id DESC';

    $query = $entityManager->createQuery($str);
    $list = $query->getResult();
    $ids = array();
    foreach ($list as $el)
        array_push($ids, $el['id']);
    return $ids;
}


function getCurrentDeviceId($accountId)
{
    global $link;
    $did = 0;
    $query = mysqli_query($link,"select active_device_id from accounts where id = $accountId");
    if ($query && $res = mysqli_fetch_row($query))
    {
        $did = intval($res[0]);
    }
    return $did;
}

function LogOff()
{

}

function getActiveSession($accountId)
{
    global $link;
    $sid = 0;
    $query0 = mysqli_query($link,"select MAX (id) from sessions where account_id = ". $accountId);
    if ($query0 && $res = mysqli_fetch_row($query0))
    {
        $sid = intval($res[0]);
    }
    if ($sid)
    {
        $query = mysqli_query($link,"select start, device_id from sessions where id=".$sid);
        if ($query && $res = mysqli_fetch_row($query))
        {
            $start = $res[0];
            $did = intval($res[1]);
        }
    }
    return array("id"=>$sid, "start"=>$start, "device_id"=>$did);
}

function getProjectByTask($taskId)
{
    global $link;
    $query = mysqli_query($link,"select input_id from tasks where id = ".$taskId);
    if ($query && $res = mysqli_fetch_array($query))
    {
        return GetProject($res['input_id']);
    }
    return null;
}

function getProjectsByAction($actionId)
{
    global $link;
    $str = "select * from projects_locotech where action = $actionId";
    $query1 = mysqli_query($link, $str);
    $projarr = array();
    while ($res1 = mysqli_fetch_array($query1)) {
        array_push($projarr, $res1);
    }
    return $projarr;
}

function getProjectIDByTask($taskId)
{
    global $link;
    //$query = mysqli_query($link,"select * from tasktypes tt INNER JOIN tasks t ON t.type = tt.id");
    $query = mysqli_query($link,"select input_id from tasks where id = ".$taskId);
    $pid = 0;
    if ($query && $res = mysqli_fetch_array($query))
    {
        $pid = intval($res['input_id']);
    }
    return $pid;
}

function getCompanyByTask($taskId)
{
    global $link;
    //$query = mysqli_query($link,"select * from tasktypes tt INNER JOIN tasks t ON t.type = tt.id");
    $query = mysqli_query($link,"select * from tasktypes tt, tasks t where t.type = tt.id and t.id = ".$taskId);

    if ($query && $res = mysqli_fetch_array($query))
    {
        $companyid = intval($res['company']);
    }
    return getCompanyByID($companyid);
}

function getCompanyByAccount($accountId)
{
    global $link;
	$query = mysqli_query($link,"select company from accounts where id = $accountId");
	if ($query && $res = mysqli_fetch_array($query)) {
		$companyid = intval($res['company']);		
	}
	return getCompanyByID($companyid);
}

function getCompanyByID($companyid) 
{
    global $link;
	$query = mysqli_query($link,"select name, logo from companies where id = $companyid");
	if ($query && $res = mysqli_fetch_array($query))
	{
		$mycompany = $res['name'];
                $mycompanylogo = $res['logo'];
	}
	return array($companyid, $mycompany, $mycompanylogo);
}

$oses = "WinPhoneWinXPMacOSLinuxUbuntuiPhoneiPodiPadAndroidBlackBerryMobile";
function getOS() 
{ 
	$user_agent     =   $_SERVER['HTTP_USER_AGENT'];
	//echo "user_agent ".$user_agent;
	$os_platform    =   "Unknown OS Platform";
	$os_array       =   array(
						'/ARM/i'     =>  'WinPhone',
                    '/windows nt 5.2/i'     =>  'WinXP',
                    '/windows nt 5.1/i'     =>  'WinXP',
                    '/windows xp/i'         =>  'WinXP',
						'/windows/i'     =>  'Windows',							
                    '/macintosh|mac os x/i' =>  'MacOS',
                    '/mac_powerpc/i'        =>  'MacOS',
                    '/linux/i'              =>  'Linux',
                    '/ubuntu/i'             =>  'Ubuntu',
                    '/iphone/i'             =>  'iPhone',
                    '/ipod/i'               =>  'iPod',
                    '/ipad/i'               =>  'iPad',
                    '/android/i'            =>  'Android',
                    '/blackberry/i'         =>  'BlackBerry',
                    '/webos/i'              =>  'Mobile'    						
						
//                            '/windows nt 10/i'     =>  'Windows 10',
//                            '/windows nt 6.3/i'     =>  'Windows 8.1',
//                            '/windows nt 6.2/i'     =>  'Windows 8',
//                            '/windows nt 6.1/i'     =>  'Windows 7',
//                            '/windows nt 6.0/i'     =>  'Windows Vista',
//                            '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
//                            '/windows nt 5.1/i'     =>  'Windows XP',
//                            '/windows xp/i'         =>  'Windows XP',
//                            '/windows nt 5.0/i'     =>  'Windows 2000',
//                            '/windows me/i'         =>  'Windows ME',
//                            '/win98/i'              =>  'Windows 98',
//                            '/win95/i'              =>  'Windows 95',
//                            '/win16/i'              =>  'Windows 3.11',
//                            '/macintosh|mac os x/i' =>  'Mac OS X',
//                            '/mac_powerpc/i'        =>  'Mac OS 9',
//                            '/linux/i'              =>  'Linux',
//                            '/ubuntu/i'             =>  'Ubuntu',
//                            '/iphone/i'             =>  'iPhone',
//                            '/ipod/i'               =>  'iPod',
//                            '/ipad/i'               =>  'iPad',
//                            '/android/i'            =>  'Android',
//                            '/blackberry/i'         =>  'BlackBerry',
//                            '/webos/i'              =>  'Mobile'
                );


	foreach ($os_array as $regex => $value) 
	{ 
		if (preg_match($regex, $user_agent))
		{
			$os_platform    =   $value;
			return $os_platform;
		}
	}
}

function GetTaskStatusFromID($taskid)
{
    $task = GrabTask($taskid);
    $parent = intval($task['parent_id']);
    if ($parent > 0)
        return intval($task['status']);
    else
    {
        $tasks = GrabSubTasks($taskid);
        $assigned = 0;
        $accepted = 0;
        $hold = 0;
        $done = 0;
        $lentasks = sizeof($tasks);
        foreach ($tasks as $task)
        {
            $status = intval($task['status']);
            switch ($status) {
                case 2:
                    $assigned++;
                    break;
                case 3:
                    $accepted++;
                    break;
                case 4:
                    $hold++;
                    break;
                case 5:
                    $done++;
                    break;
            }
        }
        if ($done == $lentasks && $lentasks > 0)
        {
            return 5;
        }
        elseif ($accepted > 0 || $assigned > 0)
        {
            return 2;
        }
        else
            return 1;
    }
}

function GetTaskStatus($taskid)
{
    $task = GrabTask($taskid);
    $parent = intval($task['parent_id']);
    if ($parent > 0)
        return intval($task['status']);
    else
    {
        $tasks = GrabSubTasks($taskid);
        $assigned = 0;
        $accepted = 0;
        $hold = 0;
        $done = 0;
        $lentasks = sizeof($tasks);
        foreach ($tasks as $task)
        {
            $status = intval($task['status']);
            switch ($status) {
                case 2:
                    $assigned++;
                    break;
                case 3:
                case 6:
                case 7:
                    $accepted++;
                    break;
                case 4:
                    $hold++;
                    break;
                case 5:
                    $done++;
                    break;
            }
        }
        if ($done == $lentasks && $lentasks > 0)
        {
            return 5;
        }
        elseif ($accepted > 0)
        {
            return 2;
        }
        elseif ($assigned > 0)
            return 2;
        else
            return 1;
    }
}

function GetProjectStatus($projid)
{
    //$proj = GetProject($projid);
    /**
     * @var $proj Project
     */
    $proj = Project::Find($projid);
    $tasks = $proj->getTasks();
    //$tasks = GetTasksForProject($projid);
    $assigned = 0;
    $accepted = 0;
    $hold = 0;
    $done = 0;
    $numcommands = 0;
    $lentasks = 0;
    foreach ($tasks as $task)
    {
     //   if ($task['parent_id']=='0') {
        if ($task->parent_id==0) {
            $lentasks++;
            $numcommands++;
            //$status = intval($task['status']);
//            $status = GetTaskStatus($task['id']);
            switch ($task->status) {
                case 2:
                    $assigned++;
                    break;
                case 3:
                    $accepted++;
                    break;
                case 4:
                    $hold++;
                    break;
                case 5:
                    $done++;
                    break;
            }
        }
    }
    //echo $lentasks;
    if ($done == $lentasks && $lentasks > 0)
    {
        return 5;
    }
    elseif ($done > 0)
    {
        return 2;
    }
    elseif ($accepted > 0 || $assigned > 0)
    {
        return 2;
    }
    else
        return 1;
}
function ASUSG($asusg_job_mapped_id)
{
    global $link;
    $query = mysqli_query($link, "select * from asusg_job2launch where id=$asusg_job_mapped_id");

    $taskarr = array();
    while ($query && $res = mysqli_fetch_assoc($query))
    {
        array_push($taskarr, $res);
    }
    return $taskarr;
}

function TaskStatusSet($taskid, $status, $confirmdata = '', $main = 0)
{
    global $link;
    if ($status == '5') {
        $finished = ", finished_time=NOW()";
    }
    if ($confirmdata != '')
        $conf = ", confirm_data ='$confirmdata'";

    mysqli_query($link, "update tasks set status = $status$finished$conf  where id=$taskid");
    $proj = getProjectByTask($taskid);
    $project_id = intval($proj['id']);
    if (($main && $status == '5') || $status == '2' || $status == '3')
    {
        /**
         * @var $proj Project
         */
        if ($project_id > 0) {
            $proj = Project::Find($project_id);
            if ($proj != null) {
                OCStaskstatus($taskid, $status, 0);
                $proj->setStatus($status);
                $proj->Save();
                if ($status == 5)
                    $proj->AddCompletedWork();
            }
        }
    }
//        mysqli_query($link, "update projects_locotech set status = $status where id=".$proj['id']);
}

function WriteLog($accid, $text='')
{
    global $link;
    $text = urldecode($text);
    $str = "INSERT into text_log (msg, stamp) values ('$accid: $text',NOW())";
    mysqli_query($link, $str);
}


//0 = неудача основная причина, 1 - успех, 2 - неудача по зоне, 3 - неудача таймаут, 4 - неудача по ТМЦ (объект)
function TaskConfirmCheck(Task $task, $zoneId)
{
    global $link;
    if (!$task) {
        WriteLog("TaskConfirmCheck task not found", "");
        return 0;
    }
    /**
     * @var $tasktype Tasktype
     */
    $tasktype = Tasktype::Find($task->type);


    try {
        $company = Company::Find($tasktype->company);
        if ($company)
        {
            $timeout = $company->GetConfirmTimeout();
            $accepted = TimeString($task->accepted_time);
            $time = ($timeout+strtotime($accepted));

            if (time() < $time) {
                WriteLog("TaskConfirmCheck task $task->id timeout fail, time:", $time);
                return 3;
            }
        }
    } catch (\Throwable $e) {
        echo $e->getMessage();
    }


    $objtype = $tasktype->object_type;
    $tmcId = FindTMCId($objtype);

    $proj = $task->project;//getProjectByTask($tid);


    $taskid = $task->GetId();
    $confirmtype = getConfirmTypebyTask($taskid);
    $result = 1;
    switch ($confirmtype)
    {
        case 2:    //Скан QR кода, пришедшего с объектом - доверяем клиенту
            break;
        case 8: //picture
            $imgpath = GetImagePathFromTask($task);
            $files1 =  scandir($imgpath);
            $len = sizeof($files1);
            if ($len <= 2)  //dots
            {
                //echo "TaskConfirmCheck images false";
                WriteLog("TaskConfirmCheck task $task->id failed image: ", $len);
                $result = 0;
            }
            break;
        case 9:  //text or audio note
            $notes = FindTaskNotes($taskid);
            if (sizeof($notes) == 0)
            {
                //echo "TaskConfirmCheck notes false";
                WriteLog("TaskConfirmCheck task $task->id failed notes: ", sizeof($notes));
                $result = 0;
            }
            break;
        case 12:    //control map
            require_once "server.php";
            $task->control_map_checked = TaskControlMapCheck($taskid);

            $task->save();
//            var_dump($task->control_map_checked);
            if (intval($task->control_map_checked) != 1) {
                WriteLog("TaskConfirmCheck task $task->id failed control map: ",intval($task->control_map_checked));
                $result = 0;
            }
            break;
        case 13:    //масломер
            if (intval($tmcId) > 0 && isset($proj)) {
                $section = $task->getSection();
//        WriteLog("TaskConfirmCheck request sec id $section->id ", isset($proj));
                if ($section) {
                    require_once("curlexec.php");
                    $str = "http://oiltest.prmsys.net/api/session/finish?deviceId=$tmcId&sectionId=$section->id";
//            WriteLog("TaskConfirmCheck request string ", $str);
                    $response = CURLrequestGET($str, ["uuid-key: 07a13c8907d1-6a7bdba1-a2fz-aatgu4j"]);
                    WriteLog("TaskConfirmCheck request response ", $response);
                    if (intval($response) > 0) {
                        WriteLog("TaskConfirmCheck task $task->id failed with oil tmc, api response: ", $response);
                        return 4;
                    }
                }
            }
            break;
        case 14:
            $zone_req= $tasktype->zone_required_id;
            if ($zone_req && $zoneId != $zone_req)
                $result = 2;
            break;
        case 17:    //AR object recognized
            $str = "select ar_object_id from tasks where id=$taskid";
            $query = mysqli_query($link, $str);
            if ($result = mysqli_fetch_object($query)) {
                if (!$result->ar_object_id)
                    $result = 0;
            }
            break;
        case 18:    //smart contract
            global $host, $port;
            WriteLog(666, "18!!!");
            if (CheckConnection())
                readfile("http://$host:$port/WebAPI/1");
            break;
    }
    //WriteLog("workToExecute =>1", 'start'.$taskid);
    $exec = \app\models\MappingworksModel::workToExecute($taskid);
    //WriteLog("workToExecute =>2", $exec);
    //if ( false == $exec) {
    //    $result = 0;
    //}
    //echo "TaskConfirmCheck tid $taskid ctype $confirmtype result $result path $imgpath fileslen $len ";
    return $result;
}
//SERVER FUNCTIONS

function GetLastZoneId($accId, $echo=false)
{
    global $link;
    $str = "SELECT * from user_positions where acc_id=$accId and DATE_ADD(ts, INTERVAL 1 minute) > now() order by id desc limit 1";
    $result_pos = mysqli_query($link, $str);
    if ($obj = mysqli_fetch_object($result_pos)) {
        $location_id = $obj->location_id;
        $x = $obj->coord_x;
        $y = $obj->coord_y;
    }
    //scale 1 зоны = 10 клеткам x1 z1 - position, x2 z2 - scale
    //координаты юзеров сейчас увеличены в
    //x/10 < x1+x2 && x/10 > x1-x2 &&
    $str = "SELECT * from zones where ($x < x1+x2*5) and ($x > x1-x2*5) and ($y < z1+z2*5) and ($y > z1-z2*5) and location_id=$location_id limit 1";
    WriteLog($accId, $str);
    if ($echo)
    {
        echo $str;
    }
    $result_zones = mysqli_query($link, $str);
    if ($obj = mysqli_fetch_object($result_zones)) {
        $zone_id = $obj->id;
        $desc = $obj->description;
        return $zone_id;
    }
    return 0;
}

function GetZoneName($zone_id)
{
    global $link;
    $str = "SELECT description from zones where id=$zone_id";
    $result_pos = mysqli_query($link, $str);
    if ($obj = mysqli_fetch_object($result_pos)) {
        return $obj->description;
    }
    return "";
}

function IsMeasurement($task_id)
{
    global $link;
    $str = "SELECT * from asusg_measurements where smopp_task_id=$task_id order by id desc  limit 1";
    $result_pos = mysqli_query($link, $str);
    if ($obj = mysqli_fetch_object($result_pos)) {
        //WriteLog("IsMeasurement task $task_id", "true");
        return $obj;
    }
    WriteLog("IsMeasurement task $task_id", "false");
    return null;
}

function Measurements2JSON($proj_id)
{
    global $link;
    $work_id = 0;
    $user_id = 0;
    $jsonStringReturn = array();
    $measurements = array();
    $str = "SELECT mes.* from tasks as t join asusg_measurements as mes on mes.smopp_task_id=t.id where t.input_id=$proj_id";
    $result_pos = mysqli_query($link, $str);
    while ($obj = mysqli_fetch_object($result_pos)) {
        if (!$work_id)
            $work_id = $obj->work_id;
        if (!$user_id)
            $user_id = json_decode($obj->worker)->id;

        $measurement = [];
        $measurement['measurement_id'] = $obj->measurement_id;
        $measurement['characteristic_id'] = $obj->characteristic_id;
        $measurement['measurement_stage'] = $obj->measurement_stage;
        $measurement['measurement_value'] = $obj->measurement_value;
        $measurement['comment'] = json_decode($obj->measurement_comment)->text;
        $measurements[] = $measurement;
    }
    $jsonStringReturn['user_id'] = $user_id;
    $jsonStringReturn['work_id'] = $work_id;
    $jsonStringReturn['measurements'] = $measurements;
    return $jsonStringReturn;
}

function Measurements2JSONTask($task_id, $user_id, $ignore_hardware = true)
{
    global $link;
    $work_id = 0;
    $jsonStringReturn = array();
    $measurements = array();
    $str = "SELECT mes.* from tasks as t join asusg_measurements as mes on mes.smopp_task_id=t.id where t.id=$task_id";
    $result_pos = mysqli_query($link, $str);
    while ($obj = mysqli_fetch_object($result_pos)) {
        if ($ignore_hardware && intval($obj->is_hw_measurement)>0)
            continue;
        if (!$work_id)
            $work_id = $obj->work_id;
        if (!$user_id)
        {
            $user_id = json_decode($obj->worker)->id;
        }

        if ($obj->value_type == 'boolean')
        {
            $obj->measurement_value = $obj->measurement_value == 1 ?true:false;
        }

        $measurement = [];
        $measurement['measurement_id'] = $obj->measurement_id;
        $measurement['characteristic_id'] = $obj->characteristic_id;
        $measurement['measurement_stage'] = $obj->measurement_stage;
        $measurement['measurement_value'] = $obj->measurement_value;
        $measurement['comment'] = json_decode($obj->measurement_comment)->text;
        $measurements[] = $measurement;
    }
    $jsonStringReturn['user_id'] = $user_id;
    $jsonStringReturn['work_id'] = $work_id;
    $jsonStringReturn['measurements'] = $measurements;
    return $jsonStringReturn;
}

function WriteMeasurementsToTWX($dict)
{
    require_once 'curlexec.php';
    //$url = "http://devplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/write_work_measurements_v2";
    //$result = CURLrequestPOST($url, ["AppKey: 6a7bdbaa-6bc1-4159-a2f4-07a13c8907d1"], $dict);

    $url = "http://qaplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/write_work_measurements_v2";
    $result = CURLrequestPOST($url, ["AppKey: 33cd23bb-3b03-4638-afef-7104a13e9211"], $dict);
    WriteLog("WriteMeasurementsToTWX input ".json_encode($dict), $result);
}



function TaskConfirm($num, $id, $tid, $confirm_data, $verbose=false)
{
//    try {received
    //TODO брать сабтаски из их таблицы по исполнителю
    ob_start();
    global $link, $companyID;
    /**
     * @var $task Task
     */
    $task = Task::Find($tid);
    if ($task != null) {
        $accid = intval($task->assignees_arr);
        if ($accid != intval($id))
        {
            TaskConfirmResult($num, 0, $tid);
            EnqueueCMD($id, "21");
            WriteLog("TaskConfirm task $tid failed account id $id != ",$accid);
            return;
        }

        if (intval($task->status) == 5)
        {
            TaskConfirmResult($num, 1, $tid);
            WriteLog("TaskConfirm task $tid failed status already ",$task->status);
            return;
        }
        $zoneId = GetLastZoneId($id);
        $checkresult = TaskConfirmCheck($task, $zoneId);
        if ($verbose)
            echo "result $checkresult";

        if ($checkresult != 1) {
            TaskConfirmResult($num, $checkresult, $tid);
            return;
        }

        /**
         * @var $account Account
         */
        $account = Account::Find($id);
        if ($account != null) {
            $tasks = $account->tasks;
            $account->last_action = new \DateTime("now");
            $account->Save();

            $companyID = $account->getCompany()->id;

            $measurement = IsMeasurement($tid);
            if ($measurement)
            {
                    //TODO понять что таск записан - тогда слать тру
                    $task_hw = $task->asusg_task_hw_measurement_id;
                    if ($task_hw)
                    {
                        if (intval($task->status) != 7) {
                            TaskConfirmResult($num, 0, $tid);
                            WriteLog("TaskConfirm task $tid failed status is ", $task->status);
                            return;
                        }
                    }
                $json = Measurements2JSONTask($tid, $account->uuid);
                \app\models\entity\Metrics::log(2, $num, 'write_work_measurements_v2, workId = ' . ($json['work_id'] ?? 0));
                WriteMeasurementsToTWX($json);
                \app\models\entity\Metrics::log(3, $num, 'write_work_measurements_v2, workId = ' . ($json['work_id'] ?? 0));
            }
            else
            {
                $subs = explode(" ",$task->name);
                if ($subs[0] === "Замер")
                {
                    TaskConfirmResult($num, 0, $tid);
                    return;
                }
            }
            mysqli_query($link, "update tasks set status=5, zone_id = $zoneId, finished_time = NOW() where id=$tid");
            \app\models\ElasticLog::command((int)$task->id, 'Завершение');
            $parenttask = Task::Find($task->parent_id);
            $subtasks = GrabSubTasks($parenttask->id);
            $numconfirmed = 0;

            foreach ($subtasks as $sub) {
                $status = intval($sub['status']);
                $subtask = Task::Find($sub['id']);
//                \Doctrine\Common\Util\Debug::dump($subtask);

                if ($status == 5 && $tasks->contains($subtask)) {
                    $numconfirmed++;
                }
            }

            if ($verbose)
            {
                var_dump($numconfirmed);
                var_dump(sizeof($subtasks));
            }
            if ($numconfirmed == sizeof($subtasks)) {
                $parenttask->status = 5;
                $parenttask->Save();
                $proj = $parenttask->project;
                if ($verbose)
                    \Doctrine\Common\Util\Debug::dump($proj);
                if ($proj != null) {
//write entire project
//                    if (IsMeasurement($tid))
//                    {
//                        $json = Measurements2JSON($proj->id);
//                        WriteMeasurementsToTWX($json);
//                    }
                    $proj->finished_time = new \DateTime("now");;
                    $proj->setStatus(GetProjectStatus($proj->id));
                    if ($verbose)
                        var_dump($proj->getStatus());
                    $proj->Save();

                    //временный хардкод - ПРИЕМКА создает опись
                    TempStartProject($proj);
                }
                TasksAssign('', true, 0, false);
            }
            WriteLog("TaskConfirm success $tid account id $accid","");
            OCStaskstatus($tid, 5, $accid);
            TaskConfirmResult($num, 1, $tid);
//            $buf = pack("C", $num);
//            $buf .= pack("Cl*", 1, $tid);
//            ob_get_clean();
//            echo base64_encode($buf);
        }
    }
//    } catch (\Throwable $e) {
//        echo $e->getMessage();
//    }

}

function TaskConfirmResult($num, $res, $tid)
{
    \app\models\entity\Metrics::log(4, $num, 'taskId = ' . $tid);
    $buf = pack("C", $num);
    $buf .= pack("Cl*", $res, $tid);
    ob_get_clean();
    echo base64_encode($buf);
}

/**
 * Проверяет есть ли секция с заданными параметрами, если нет, то создаёт её.
 * Обновляет диагностическую карту
 *
 * @param $letter
 * @param $series
 * @param $number
 * @param $subnumber
 */
function CheckSection($letter, $series, $number, $subnumber)
{
    if ($subnumber) {
        global $entityManager;
        $sec = $entityManager->getRepository('Section')->findBy([
            'locomotive_series' => $series,
            'section_number' => $number,
            'section_subnumber' => $subnumber,
            "letter" => $letter
        ]);
        if (sizeof($sec) > 0) {
            $section = $sec[0];
        } else {
            $series = LocoSeries::Find("$series");
            if ($series != null) {
                $section = new Section();
                $section->letter = $letter;
                $section->series = $series;
                $section->setSectionSubnumber($subnumber);
                $section->setSectionNumber($number);
            }
        }
        if ($section != null) {
            UpdateDiagnosticMap($section, true);
        }
    }
}

function UpdateDiagnosticMap(Section $section, $save = false)
{
    $params['subnum_section'] = $section->getSectionSubnumber();
    $locomotiveModel = new app\models\LocomotiveModel();
    $result = $locomotiveModel->getSectionInfo($params);
    $json = json_decode($result);
    if ($json != null && $json->diagnosticMap != null) {
        $uuid = $json->diagnosticMap;
        $section->uuid = $json->section_id;
        $mynum = $json->section_num;    //letter == last symbol
        $letter = substr($mynum, -1);
        if (intval($letter) <= 0)
            $section->letter = $letter;
        $existed = DiagnosticMap::Find($uuid);
        if ($existed == null) {
            $dm = new DiagnosticMap();
            $dm->created = new DateTime("now");
            $dm->uuid = $uuid;
            $section->addDiagnosticMap($dm);
            $section->diagnostic_map = $uuid;
        }
    }
    if ($save)
        $section->Save();
}

function CreateProject($projecttype, $loco_number, $loco_type, $А, $Б, $В, $Г)
{
    global $link, $companyID;

        CheckSection("А", $loco_type, $loco_number, $А);
        CheckSection("Б", $loco_type, $loco_number, $Б);
        CheckSection("В", $loco_type, $loco_number, $В);
        CheckSection("Г", $loco_type, $loco_number, $Г);

        $qstr = "insert into projects_locotech (action, company, status, loco_type,loco_number,depo,depo_service, created, urgent) values ($projecttype, $companyID,1,'$loco_type',$loco_number,'','', NOW(), 0)";
        mysqli_query($link, $qstr);
        $activeid = mysqli_insert_id($link);

        if ($activeid) {
            if (StartProject($projecttype, $activeid))
                TasksAssign('', true, $activeid);
        }
}

function TempStartProject($proj = null)
{
    global $link, $companyID;
    $projecttype = $proj->getAction();
//    var_dump($projecttype);
    if ($projecttype == 187 || $projecttype == 185 || $projecttype == 170 || $projecttype == 178) {
        if ($proj->getStatus() == 5) {
            $loco_number = $proj->loco_number;
            $loco_type = $proj->getLocoType();
            $qstr = "insert into projects_locotech (action, company, status, loco_type,loco_number,depo,depo_service, created, urgent) values (" . 214 . "," . 3 . ",1,'$loco_type','$loco_number','','', NOW(), 0)";
            mysqli_query($link, $qstr);
            $activeid = mysqli_insert_id($link);

//            var_dump($activeid);
            if ($activeid) {
                $project = Project::Find($activeid);
                if ($project != null) {
                    /**
                     * @var $project Project
                     */
                    if ($proj->section) {
                        $project->section = $proj->section;
                        $project->Save();
                    }
                }
                if (StartProject(214, $activeid))
                    TasksAssign('', true, $activeid);
            }
            //временный хардкод - ПРИЕМКА создает опись
        }
    }
}
//            if (StartProject($action_num, $activeid))
//                TasksAssign('', true, $assign_id);
function GrabReadyTasksForAccount($accid, $typeid)
{
    global $link;
    $query = mysqli_query($link, "select * from tasks where status = 5 and type = $typeid and assignees_arr=".$accid);
    $taskarr = array();
    while ($query && $res = mysqli_fetch_array($query))
    {
        array_push($taskarr, $res);
    }
    return $taskarr;
}

function GetAverageTime($taskarr)
{
    $sum = 0;
    foreach ($taskarr as $res)
    {
        $time = TimeSpentForTaskFromArray($res);
        $sum += $time;
    }
    $sum /= sizeof($taskarr);
    $sum = round($sum, 0, PHP_ROUND_HALF_UP);
    if ($sum > 120)
        $sum = '---';
    return $sum;
}

function EfficiencyReport($accid)
{
    global $link;
    $query = mysqli_query($link, "select * from tasks where status = 5 and assignees_arr=".$accid);
    $taskarr = array();
    $retarr = array();
    
    while ($query && $res = mysqli_fetch_array($query))
    {
        $timespent = TimeSpentForTaskFromArray($res);
        $typeid = $res['type'];
        if (sizeof($taskarr[$typeid]) == 0) {
            $taskarr[$typeid] = array();
            }
        array_push($taskarr[$typeid], $timespent);
    }
    foreach ($taskarr as $type_id=>$timesspent)
    {
        $sum = 0;
        foreach ($timesspent as $time) {
            $sum += $time;
        }
        //echo "time $time";
        $sum /= sizeof($time);
        if ($sum > 120)
            $sum = '---';
        $retarr[$type_id] = $sum;
    }
    return $retarr;
}

/**
 * @param string $action Acceptable values are `encrypt` or `decrypt`.
 * @param string $string The string value to encrypt or decrypt.
 * @return string
 */
function encrypt_decrypt($action, $string)
{
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = '202cb962ac59075b964b07152d234b70';
    $secret_iv = '289dff07669d7a23de0ef88d2f7129e7';

    // hash
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a
    // warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    if ($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } elseif ($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}