<?
if (!$logged_me_in_successfully234)
	return;

//$arResult = mainFuncController();
$managementModel = new \app\models\ManagementModel();
$arResult = $managementModel->mainFuncController();

$company = Company::Find($companyID);

if (isset($assign_id) && isset($assign_act)) {
    if (StartProject($assign_act, $assign_id))
        TasksAssign('', true, $assign_id);
}





//echo "sort1 $sorttasks $sort";
if (!isset($sort))
{
    $sort = $_SESSION['sorttasks'];
    if (!isset($sort)) {
        $sort = 1;
    }
}
$_SESSION['sorttasks'] = $sort;
//echo "scr ".$scroll;
echo "<input type='hidden' id='scroll' value=$scroll>";
//echo "sort $sorttasks $sort";


//getAccountList();

//var_dump(getAccountList()); echo "<br>";

echo
"
<div class='main__content'>
    <div class='content__menu'>
        <h2 class='content__title content__menu__title'>
            Сотрудники
        </h2>
        ";
        
    
    echo '<table style="height: 154px;" width="413">
    <thead>
        <tr>
        <td style="width: 42px;">Сотрудники</td>
        <td style="width: 42px;">Должности</td>
        </tr>
    </thead>
    <tbody>';
    if( count($arResult['accountList']) > 0 ) {    
        foreach($arResult['accountList'] as $acc) {
            echo '<tr>
                <td style="width: 42px;">'. $acc['name'] .'</td>
                <td style="width: 42px;">
                    <select>';
                        foreach($acc as $position) {
                            if (!is_array($position)) {continue;}
                            $selected = ( 0 == $position['priority'])? 'selected="selected"': '';
                            echo '<option value="'. $position['id'].'" '.$selected.'>'. $position['job_name'].'</option>';
                        }    
                    echo '</select>
                    <input type="button" value="Сохранить">
                </td>
            </tr>';
        
        }
    }  else {
            echo '<tr>
                <td style="width: 42px;">Никого не найдено</td>
                <td style="width: 42px;">Ничего не найдено</td>
            </tr>';
        }
    echo '
    </tbody>
    </table>';         
    
echo    '<div class="content__menu__list">';
echo '<br>';





//EchoProjects($sort);
    echo '</div>';
echo '</div>';




    //PARENT TITLE IN CHILDREN LIST
if ($new == 1){

} else if ($activeid) { 
//    $proj = GetProject($activeid);
    /**
     * @var $proj Project
     */
    $proj = Project::Find($activeid);
    if ($proj != null) {
        $action = FindAction($proj->getAction());
        $actionid = $action['id'];
        $types = ProjectType::GrabTasktypesByProjectType($actionid);
        $acname = $action['name'];

        $section = $proj->section;
        if ($section != null) {
            $loco_type = $section->locomotive_series;//$proj['loco_type'];
            $loco_number = $section->getSectionNumber();//intval($proj['loco_number']);
        }
        $depo = $proj->getDepo();
        $depos = $proj->getDepoService();
        if ($activeid) {
            echo "<div class='content__main'>
            <h2 class='content__title content__main__title'>$activeid. $acname</h2>
            <p class='content__main__item__text'>";
            
            
            
            
            echo "<span style='color: black'>
            Тип проекта: <a href='?act=project_types&activeid=$actionid'>$actionid. $acname</a><br> 
            Локомотив серии: $loco_type № $loco_number <br>
            Депо приписки: $depo<br>
            Депо обслуживания: $depos<br><br>
            Доступные типы задач:
            </span><br><br>";
            foreach ($types as $type) {
                //if ($type['main_task']) {
                if ($type->main_task) {
                    echo "[Главная] ";
                    $sort = '1';
                }
                $tid = $type->GetId();
                $tname = $type->name;
                echo "<a href = '?act=tasktypes&activeid=" . $tid . "&sort=$sort'>$tid. $tname</a>";
                echo '<br>';
            }
            echo "<br><span style='color: black'>Созданные задачи:</span><br><br>";

            $tasks = GetTasksForProject($activeid);

            // ПОЛУЧЕНИЕ XML НАЧАЛО

            $parents = $entityManager->getRepository('Task')->findBy(array('parent_id' => 0), array('id' => 'DESC'));
            $tasktypesIds = GrabTasktypesIDs();
            $array_children = [];
            $array_parent = [];
            foreach ($parents as $parent) {
                if (!in_array(intval($parent->type), $tasktypesIds)) {
                    continue;
                }
                $status = GetTaskStatus($parent->id);
                if ($status == 5) {
                    $array_parent[$parent->id] = $parent;
                    $children = $entityManager->getRepository('Task')->findBy(array('parent_id' => $parent->id));
                    $array_children[$parent->id] = $children;
                }

            }
            $array_type = [];
            $array_id = [];

            $_SESSION['array_children'] = $array_children;
            $_SESSION['array_parent'] = $array_parent;
            
            $arrayTasksId = [];
            foreach ($tasks as $task) {
            
                $type = $task['type'];
                $id = $task['id'];

                $_SESSION['actid'] = $id;
                foreach ($array_children as $parent_id => $children) {
                    if ($id == $parent_id) {
                        foreach ($children as $res1) {
                            $array_type[] = $res1->type;
                            $array_id[] = $res1->id;
                        }
                    }
                }
                $xmltype = implode(',', $array_type);
                $xmlid = implode(',', $array_id);

                $name = GetTaskNameAndDesc($type)[0];
                $sort = GetTaskStatus($id);

                if ($task['parent_id'] == '0') {
                    $arrayTasksId[] =  $id;
                    echo "<a href = '?act=tasks&activeid=$id&sort=$sort'>$id [$sort]. $name </a><br>";
                    http://corp.prmsys.net/index.php?act=tasks&activeid=679&scroll=0
                    
                }
                
            }
            
            echo '</p></div>';
        }
    }
}



echo '<div class="content__main" >
        <h2 class="content__title content__menu__title">
            Локомотивы
        </h2><br>
        <div>
            <h3>Новая задача:</h3>';
            echo "<select class='form-input content__main__form__goal' name='newtasktype'>";
            $tasktypes = GrabTasktypes();
            foreach ($tasktypes as $tasktype)
            {
                if ($tasktype->main_task == '1') {
                    $ttype = $tasktype->id;
                    $ttname = $tasktype->name;
                    echo "<p class='content__menu__task-text'><option value = '".$ttype."'>[" . $ttype . "] " . $ttname . "</option></p>";
                }
            }

        echo '</select></div>
        <ul id="sortable">';
        foreach( $arResult['locomotiveList'] as $loco )
        {
            $project = $loco['obj'];
            $project_id = $project->id;
            $urgent = $project->urgent;
            if (!$urgent)
                $makeurgent = "Назначить приоритетным";
            else
                $makeurgent = "Снять приоритетность";

            echo '<li>
            <div   id="'.$project_id.'"  style="border: solid;  border-width: 1px; border-color: #9cb2c4; border-radius: 15px; margin:5px; margin-bottom:20px; padding: 5px">            
                <div id="data_pos_top_1" class="slider_staff_toggle27_top" ></div>
                <p class="button_staff_toggle button_sou_toggle" data="slider_staff_toggle'.$loco['obj']->loco_number .'" style="float: right; font-size: 10px;text-decoration: underline;color: blueviolet;">Развернуть</p>
                <h4 class="_button_staff_toggle" data="slider_staff_toggle'.$loco['obj']->loco_number .'">' . $loco['obj']->loco_type .' <b><span style="color: darkolivegreen">['. $loco['obj']->loco_number.'] </span></b> Выполнено задач: '.$loco["countDone"]['done'].' из '. $loco["countDone"]['all'] .'</h4> 
                <input id="makeurgent" value="'.$makeurgent.'" type="button"> 
                <input  id="addtask"  value="Добавить задачу" type="button">';

                echo '<div class="slider_staff_toggle'.$loco['obj']->loco_number .'" style="display: none;">                
                    <p></p>
                    <h4 style="margin-bottom: 5px">Активные задачи:</h4> 
                    
                    <div id="result"></div><ul id="sortableIn">';

                    foreach ($loco['arr'] as $item)
                    {
                        $color = \Yii::$app->params['task_status']['color'][$item['status']];
                        echo '<li style="list-style-type: none"><div style="border: solid;  border-width: 1px; border-color: #9cb2c4; border-radius: 15px; margin:5px; margin-bottom:20px; padding: 5px; background-color:'.$color.'">';
                        echo "<a href = '' > " . $item['id'] . " " . $item['name']."</a><br>";

                        echo \Yii::$app->params['task_status']['attributes'][$item['status']] . ": ";
                        echo "<select>";
                        foreach($item['listAccounts'] as $employee) {
                            $selected = ($item['assignees_arr'] == $employee['id'])? 'selected="selected"': '';
                            echo "<option value='".$employee['id']."' $selected>". $employee['name']."</option>";
                        }
                        echo "</select>";
                        //var_dump( $item['listAccounts']);
                        echo "</div></li>";
                    }
                    echo '</ul>
                    <br>                    
                </div>
            </div>';
        }
    echo '</div></li>';
 
// ПОЛУЧЕНИЕ XML КОНЕЦ
echo '</ul></div>';  //main__content


echo '
      <script>
  $( function() {
    $( "#sortable" ).sortable();
    $( "#sortableIn" ).sortable();
    $( "#sortable" ).disableSelection();
  } );
  </script>'; 

function mainFuncController(){
    
    $arResult = [];
    $arResult['accountList'] = getAccountList();
    $arResult['locomotiveList'] = getLocomotiveList();
    
    return $arResult;
}
        
        
function getAccountList(){

    global $companyID;
    $result = [];
    //var_dump($companyID);
    $accountsEntity = \app\models\entity\Accounts::find()->where(['company' => $companyID])->all();
    foreach( $accountsEntity as $item){
        $last_seen_mobile = ( null != $item->last_seen_mobile )? new DateTime($item->last_seen_mobile): $item->last_seen_mobile ;
        $online_mobile = OnlineAccountCheck(TimeString($last_seen_mobile));
        if (!$online_mobile) { continue;}
        foreach($item->jobtype as $it) {
            $result[] = ['name' => $item->name,'position' => $it->name];
            
        }
    }
    return $result;
}

function getLocomotiveList(){

    global $companyID;
    
    $result = [];
    //var_dump($companyID);
    $projectsLocotechEntity = \app\models\entity\ProjectsLocotech::find()->where(['company' => $companyID,'status' => 2] )->orderBy(['id' => SORT_DESC])->all();
    
    foreach( $projectsLocotechEntity as $item){    
        //$tempArray = GetTasksForProject($item->id);
        foreach( GetTasksForProject($item->id) as &$proj) {
            $proj['name'] = GetTaskNameAndDesc($proj['type'])[0];
        }
        //$tempArray['name'] = GetTaskNameAndDesc($tempArray['type'])[0];
            
        $result[$item->id]['arr'] = GetTasksForProject($item->id);
        $result[$item->id]['obj'] = $item;
    }
    
    return $result;
    
} ?>
<style type="text/css">
    .ui-sortable li {
        list-style: none;
    }
    .ui-sortable-handle {
        margin: 0;
    }
    .ui-sortable-handle div {
        margin: 15px 0 0 !important;
        padding: 0 15px !important;
    }
</style>