<?php
include("../public/impOpreation.php");

$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");
$userid = $_SESSION['userid'];
if (empty($do)) {  
    $taskssettings = R::load('taskssettings',1);
    if (!in_array($_SESSION['usergroupid'] , explode(',', $taskssettings->usergroupadd))) {   
     header("location:tasksController.php?do=show");
     exit();
    }

    $taskscases = R::findAll('taskscases','del = 0');
    $smarty->assign('taskscases', $taskscases);
    $smarty->display("header.html");
    $smarty->display("tasksview/add.html");
    $smarty->display("footer.html");
} elseif ($do == "show") {
    $taskssettings = R::load('taskssettings',1);
    if (!in_array($_SESSION['usergroupid'] , explode(',', $taskssettings->usergroupshow))) {   
       $smarty->assign('usergroupid', 1);
    }else{
       $smarty->assign('usergroupid', 0); 
    }

     $taskscases = R::findAll('taskscases','del = 0');
    $smarty->assign('taskscases', $taskscases);
    include_once("../public/authentication.php");
    $smarty->display("header.html");
    $smarty->display("tasksview/show.html");
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    $taskssettings = R::load('taskssettings',1);
    if (!in_array($_SESSION['usergroupid'] , explode(',', $taskssettings->usergroupupdate))) {   
     header("location:tasksController.php?do=show");
     exit();
    }
    $id = filter_input(INPUT_GET, 'id');
    $task = R::load('tasks', $id);
    $smarty->assign('task', $task);
    $client = R::getRow('SELECT * FROM client where conditions = 0 and clientid = ? ',[$task->taskclientid]);
    $smarty->assign('client', $client);
    $user = R::getRow('SELECT * FROM user where conditions = 0 and userid = ? ',[$task->taskuserid]);
    $smarty->assign('user', $user);
    $tasktype = R::findOne('taskstypes','del = 0 and id = ? ',[$task->tasktypeid]);
    $smarty->assign('tasktype', $tasktype);
    $taskscases = R::findAll('taskscases','del = 0');
    $smarty->assign('taskscases', $taskscases);
    $taskscomments = R::findAll('taskscomments','del = 0 and taskid = ? ',[$id]);
    $smarty->assign('taskscomments', $taskscomments);
    $smarty->display("header.html");
    $smarty->display("tasksview/edit.html");
    $smarty->display("footer.html");
} elseif ($do == "detail") {
    
    $id = filter_input(INPUT_POST, 'id');
    $task = R::load('tasks', $id);
    $smarty->assign('task', $task);
    $client = R::getRow('SELECT * FROM client where conditions = 0 and clientid = ? ',[$task->taskclientid]);
    $smarty->assign('client', $client);
    $user = R::getRow('SELECT * FROM user where conditions = 0 and userid = ? ',[$task->taskuserid]);
    $smarty->assign('user', $user);
    $tasktype = R::findOne('taskstypes','del = 0 and id = ? ',[$task->tasktypeid]);
    $smarty->assign('tasktype', $tasktype);
    $taskcase = R::load('taskscases',$task->taskcaseid);
    $smarty->assign('taskcase', $taskcase);
    $taskscomments = R::findAll('taskscomments','del = 0 and taskid = ? ',[$id]);
    foreach($taskscomments as $taskcomment){
        $user = R::getRow('SELECT * FROM user where userid = ? ',[$taskcomment->userid]);
        $taskcomment->userm = $user['employeename'];
    }
    $smarty->assign('taskscomments', $taskscomments);

    $taskscasescomments = R::findAll('taskscasescomments','del = 0 and taskid = ? order by id desc',[$id]);
    foreach($taskscasescomments as $taskcasecomment){
        $taskcase = R::load('taskscases',$taskcasecomment->taskcaseid);
        $taskcasecomment->taskcase =$taskcase->taskcase;
        $user = R::getRow('SELECT * FROM user where userid = ? ',[$taskcasecomment->userid]);
        $taskcasecomment->userm = $user['employeename'];
    }
    $smarty->assign('taskscasescomments', $taskscasescomments);

    $smarty->display("tasksview/detail.html");
} elseif ($do == "changetaskcase") {    
    $id = filter_input(INPUT_POST, 'id');
    $smarty->assign('id', $id);
    $taskscases = R::findAll('taskscases','del = 0');
    $smarty->assign('taskscases', $taskscases);
    $smarty->display("tasksview/changetaskcase.html");    
} elseif ($do == "addcommentajax") {    
    $id = filter_input(INPUT_POST, 'id');
    $smarty->assign('id', $id);
    $smarty->display("tasksview/addcommentajax.html");     
}else if ($do == 'del') {
    $taskssettings = R::load('taskssettings',1);
    if (!in_array($_SESSION['usergroupid'] , explode(',', $taskssettings->usergroupdel))) {   
     header("location:tasksController.php?do=show");
     exit();
    }
    $id = filter_input(INPUT_POST, 'id');  
    $tasks = R::load('tasks', $id);
    $tasks->del = 1;
    $tasks->useriddel = $userid;
    $tasks->todaydel = $today;
    try {
        R::store($tasks);   
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }  

}else if ($do == 'removecomment') {
    $id = filter_input(INPUT_POST, 'id');  
    $taskscomments = R::load('taskscomments', $id);
    $taskscomments->del = 1;
    $taskscomments->useriddel = $userid;
    $taskscomments->todaydel = $today;
    try {
        R::store($taskscomments);   
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }  
}else if ($do == 'select2client') {
  select2client();
}else if ($do == 'select2user') {
  select2user();
}else if ($do == 'select2types') {
  select2types();  
}else if ($do == 'showajax') {
  showajax();      
}else if ($do == 'appendcomment') {
    $itr = filter_input(INPUT_POST, 'itr');
    $smarty->assign('itr', $itr);
    $smarty->display("tasksview/appendcomment.html");
}else if ($do == 'add') {
    $taskclientid = filter_input(INPUT_POST, 'taskclientid');
    $taskuserid = filter_input(INPUT_POST, 'taskuserid');
    $tasktypeid = filter_input(INPUT_POST, 'tasktypeid');
    $taskdate = filter_input(INPUT_POST, 'taskdate');
    $taskaddress = filter_input(INPUT_POST, 'taskaddress');
    $taskdetail = filter_input(INPUT_POST, 'taskdetail');
    $taskcaseid = filter_input(INPUT_POST, 'taskcaseid');
    $taskcasecomment = filter_input(INPUT_POST, 'taskcasecomment');
    $taskscommentsitr = filter_input(INPUT_POST, 'taskscommentsitr');
    $tasks = R::dispense('tasks');
    $tasks->del = 0;
    $tasks->today = $today;          
    $tasks->userid = $userid;
    $tasks->taskclientid = $taskclientid;
    $tasks->taskuserid = $taskuserid;
    $tasks->tasktypeid = $tasktypeid;
    $tasks->taskdate = $taskdate; 
    $tasks->taskaddress = $taskaddress; 
    $tasks->taskdetail = $taskdetail;
    $tasks->taskcaseid = $taskcaseid;
    $tasks->taskcasecomment = $taskcasecomment;
    try {
         $taskid = R::store($tasks);    
         $taskscasescomments = R::dispense('taskscasescomments');
         $taskscasescomments->del = 0;
         $taskscasescomments->today = $today;  
         $taskscasescomments->userid = $userid;
         $taskscasescomments->taskid = $taskid;
         $taskscasescomments->taskcaseid = $taskcaseid;
         $taskscasescomments->taskcasecomment = $taskcasecomment;
         R::store($taskscasescomments);   

          for ($i = 1; $i <= $taskscommentsitr; $i++) {
            $taskcomment = filter_input(INPUT_POST, 'taskcomment_' . $i);
            if (!$taskcomment) {continue;}
                $taskscomments = R::dispense('taskscomments');
                $taskscomments->del = 0;
                $taskscomments->today = $today;  
                $taskscomments->userid = $userid;
                $taskscomments->taskid = $taskid;
                $taskscomments->taskcomment = $taskcomment;
                R::store($taskscomments);   
          }    
       header("location:tasksController.php?do=show");
    } catch (Exception $e) {
       header("location:tasksController.php");
    }
}else if ($do == 'update') {
    $id = filter_input(INPUT_POST, 'id');
    $taskclientid = filter_input(INPUT_POST, 'taskclientid');
    $taskuserid = filter_input(INPUT_POST, 'taskuserid');
    $tasktypeid = filter_input(INPUT_POST, 'tasktypeid');
    $taskdate = filter_input(INPUT_POST, 'taskdate');
    $taskaddress = filter_input(INPUT_POST, 'taskaddress');
    $taskdetail = filter_input(INPUT_POST, 'taskdetail');
    $taskcaseid = filter_input(INPUT_POST, 'taskcaseid');
    $taskcasecomment = filter_input(INPUT_POST, 'taskcasecomment');
    $taskscommentsitr = filter_input(INPUT_POST, 'taskscommentsitr');

    $tasks = R::load('tasks',$id);
    if ($tasks->taskcaseid != $taskcaseid) {
         $taskscasescomments = R::dispense('taskscasescomments');
         $taskscasescomments->del = 0;
         $taskscasescomments->today = $today;  
         $taskscasescomments->userid = $userid;
         $taskscasescomments->taskid = $id;
         $taskscasescomments->taskcaseid = $taskcaseid;
         $taskscasescomments->taskcasecomment = $taskcasecomment;
         R::store($taskscasescomments);   
    }else{
        $taskscasescomments = R::findOne('taskscasescomments','taskid = ? and del = 0 order by id desc',[$id]);
        $taskscasescomments->taskcaseid = $taskcaseid;
        $taskscasescomments->taskcasecomment = $taskcasecomment;
        R::store($taskscasescomments);   
    }
    $tasks->updatetoday = $today;          
    $tasks->updateuserid = $userid;
    $tasks->taskclientid = $taskclientid;
    $tasks->taskuserid = $taskuserid;
    $tasks->tasktypeid = $tasktypeid;
    $tasks->taskdate = $taskdate; 
    $tasks->taskaddress = $taskaddress; 
    $tasks->taskdetail = $taskdetail;
    $tasks->taskcaseid = $taskcaseid;
    $tasks->taskcasecomment = $taskcasecomment;
    try {
         $taskid = R::store($tasks); 
          for ($i = 1; $i <= $taskscommentsitr; $i++) {
            $taskcommentid = filter_input(INPUT_POST, 'taskcommentid_' . $i);
            $taskcomment = filter_input(INPUT_POST, 'taskcomment_' . $i);
            if (!$taskcomment) {continue;}
                if ($taskcommentid) {
                   $taskscomments = R::load('taskscomments',$taskcommentid);
                   $taskscomments->updatetoday = $today;  
                   $taskscomments->updateuserid = $userid;
                }else{
                    $taskscomments = R::dispense('taskscomments');
                    $taskscomments->del = 0;
                    $taskscomments->today = $today;  
                    $taskscomments->userid = $userid;
                }
                
               
                $taskscomments->taskid = $taskid;
                $taskscomments->taskcomment = $taskcomment;
                R::store($taskscomments);   
          }    
       header("location:tasksController.php?do=show");
    } catch (Exception $e) {
       header("location:tasksController.php?do=edit&id=".$id);
    }
}else if ($do == 'savetaskcase') {
    $id = filter_input(INPUT_POST, 'id');
    $taskcaseid = filter_input(INPUT_POST, 'taskcaseid');
    $taskcasecomment = filter_input(INPUT_POST, 'taskcasecomment');

    $tasks = R::load('tasks',$id);
    $tasks->updatetoday = $today;          
    $tasks->updateuserid = $userid;
    $tasks->taskcaseid = $taskcaseid;
    $tasks->taskcasecomment = $taskcasecomment;
    try {
         $taskid = R::store($tasks); 
         $taskscasescomments = R::dispense('taskscasescomments');
         $taskscasescomments->del = 0;
         $taskscasescomments->today = $today;  
         $taskscasescomments->userid = $userid;
         $taskscasescomments->taskid = $id;
         $taskscasescomments->taskcaseid = $taskcaseid;
         $taskscasescomments->taskcasecomment = $taskcasecomment;
         R::store($taskscasescomments);    
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
}else if ($do == 'savecomment') {
    $id = filter_input(INPUT_POST, 'id');
    $taskcomment = filter_input(INPUT_POST, 'taskcomment');
    $taskscomments = R::dispense('taskscomments');
    $taskscomments->del = 0;
    $taskscomments->today = $today;  
    $taskscomments->userid = $userid;
    $taskscomments->taskid = $id;
    $taskscomments->taskcomment = $taskcomment;      
    try {
        R::store($taskscomments); 
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
}


function select2client() {
    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];
    

    $productsData = R::getAll("SELECT clientid, clientname as name
    FROM client 
    WHERE conditions = 0 and clientname LIKE '%" . $name . "%'  limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['clientid'];
        $row_array['text'] = $pro['name'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}

function select2user() {
    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];
    
    $productsData = R::getAll("SELECT userid, employeename as name
    FROM user 
    WHERE conditions = 0 and employeename LIKE '%" . $name . "%'  limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['userid'];
        $row_array['text'] = $pro['name'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}


function select2types() {
    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];
    
    $productsData = R::getAll("SELECT id, typename
    FROM taskstypes 
    WHERE del = 0 and typename LIKE '%" . $name . "%'  limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['id'];
        $row_array['text'] = $pro['typename'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}



function showajax() {
    $columns = array('id', 'clientname', 'sa.employeename as saemployeename', 'typename', 'taskdate','taskaddress', 'taskcaseid', 'tasks.today', 'user.employeename', 'id', 'id', 'id', 'id', 'id');
    $start_date = $_POST['fromdate'];
    $end_date   = $_POST['todate'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = (int)$_POST['data3'];
    $data4      = $_POST['data4'];
    $data5      = $_POST['data5'];
    $data6      = $_POST['data6'];

    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and tasks.taskclientid = ".$data1. " ";
    }

    if($data2 != ''){
       $searchQuery .= " and tasks.userid = ".$data2. " ";
    }
    
    if($data3 > 0){
       $searchQuery .= " and tasks.taskcaseid = ".$data3. " ";
    }

    if($data4 != ''){
       $searchQuery .= " and tasks.taskuserid = ".$data4. " ";
    }


    if($data5 != ''){
       $searchQuery .= " and tasks.tasktypeid = ".$data5. " ";
    }

    if($data6 != 0){
       $searchQuery .= " and tasks.taskuserid = ".$_SESSION['userid']. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  tasks.taskdate  >= "' . $start_date . '" and tasks.taskdate <= "' . $end_date . '" ';
    }

    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( tasks.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR clientname LIKE "%'.$_POST["search"]["value"].'%"
                    OR tasks.taskdate LIKE "%'.$_POST["search"]["value"].'%"
                    OR tasks.taskaddress LIKE "%'.$_POST["search"]["value"].'%"
                    OR tasks.today LIKE "%'.$_POST["search"]["value"].'%"
                    OR user.employeename LIKE "%'.$_POST["search"]["value"].'%"
                    OR sa.employeename LIKE "%'.$_POST["search"]["value"].'%"
                    OR typename LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  tasks.id DESC ";
    }
    
     $totals = R::count('tasks','LEFT JOIN user
         ON tasks.userid = user.userid LEFT JOIN client
         ON tasks.taskclientid = client.clientid  LEFT JOIN taskscases
         ON tasks.taskcaseid = taskscases.id 
         LEFT JOIN user as sa ON tasks.taskuserid = sa.userid 
         LEFT JOIN taskstypes ON tasks.tasktypeid = taskstypes.id 
          WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT tasks.* ,clientname ,taskcase, user.employeename, sa.employeename as saemployeename, typename  FROM `tasks`
         LEFT JOIN user ON tasks.userid = user.userid 
         LEFT JOIN client ON tasks.taskclientid = client.clientid 
         LEFT JOIN taskscases ON tasks.taskcaseid = taskscases.id  
         LEFT JOIN user as sa ON tasks.taskuserid = sa.userid 
         LEFT JOIN taskstypes ON tasks.tasktypeid = taskstypes.id 
         WHERE 1 '.$searchQuery.' ');   
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" =>  $totals,
        "recordsFiltered" => count($rResult),
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["clientname"];
        $sub_array[] = $row["saemployeename"];
        $sub_array[] = $row["typename"];
        $sub_array[] = $row["taskdate"];
        $sub_array[] = $row["taskaddress"];
        $sub_array[] = $row["taskcase"];
        $sub_array[] = $row["today"];
        $sub_array[] = $row["employeename"];  
        if($row["del"] < 1){  
        $sub_array[] = '<a href="javascript:;" type="button"  data-id="'. $row["id"] .'" class="btn btn-default btn-lm addcommentajax">اضافه تعليق</a>';        
        $sub_array[] = '<a href="javascript:;" type="button"  data-id="'. $row["id"] .'" class="btn btn-default btn-lm changetaskcase">تعديل الحاله</a>';     
        $sub_array[] = '<a href="javascript:;" type="button"  data-id="'. $row["id"] .'" class="btn btn-default btn-lm  tasksdetails"> تفاصيل</a>';    
        $sub_array[] = '<a href="tasksController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'"  type="button" class="btn btn-default btn-lg deleteicon removetask"  ></a>';
        }else{
          $sub_array[] = '';  
          $sub_array[] = '';  
          $sub_array[] = '<a href="javascript:;" type="button"  data-id="'. $row["id"] .'" class="btn btn-default btn-lg editicon tasksdetails"></a>';  
          $sub_array[] = '';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}






?>