<?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)) {  
    $smarty->display("header.html");
    $smarty->display("executors/add.html");
    $smarty->display("footer.html");
} elseif ($do == "show") {
    $smarty->display("header.html");
    $smarty->display("executors/show.html");
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    $id = filter_input(INPUT_GET, 'id');
    $executors = R::load('executors', $id);
    $smarty->assign('executors', $executors);
    $client = R::getRow('SELECT * FROM client where conditions = 0 and clientid = ? ',[$executors->executorsclientid]);
    $smarty->assign('client', $client);
    $sellbill = R::getRow('SELECT * FROM sellbill where conditions = 0 and sellbillid = ? ',[$executors->executorssellid]);
    $smarty->assign('sellbill', $sellbill);
    $users = R::getAll('SELECT * FROM user where conditions = 0 and userid  in ('.$executors->executorsuserids.')');
    $smarty->assign('users', $users);
    $smarty->display("header.html");
    $smarty->display("executors/edit.html");
    $smarty->display("footer.html"); 
}else if ($do == 'del') {
   
    $id = filter_input(INPUT_POST, 'id');  
    $tasks = R::load('executors', $id);
    $tasks->del = 1;
    $tasks->useriddel = $userid;
    $tasks->todaydel = $today;
    try {
        R::store($tasks);   
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }  

}else if ($do == 'select2client') {
  select2client();
}else if ($do == 'select2user') {
  select2user();
}else if ($do == 'select2sellbill') {
  select2sellbill();  
}else if ($do == 'showajax') {
  showajax();      
}else if ($do == 'add') {
    $executorsclientid = filter_input(INPUT_POST, 'executorsclientid');
    $executorssellid = filter_input(INPUT_POST, 'executorssellid');
    $executorsuserids = explode(',', $_POST['executorsuserids']);
    $executors = R::dispense('executors');
    $executors->del = 0;
    $executors->today = $today;          
    $executors->executorsclientid = $executorsclientid;
    $executors->executorssellid = $executorssellid;
    $executors->executorsuserids = $_POST['executorsuserids'];
    $executors->userid = $userid;
    $executors->executorsdate = date("Y-m-d");
    try {
         $executorsid = R::store($executors);  
          for ($i = 0; $i <= count($executorsuserids); $i++) {
            $executorsuserid = $executorsuserids[$i];
            if (!$executorsuserid) {continue;}
                $executorsusergroup = R::dispense('executorsusers');
                $executorsusergroup->del = 0;
                $executorsusergroup->today = $today;  
                $executorsusergroup->executorsid = $executorsid;
                $executorsusergroup->executorsuserid = $executorsuserid;
                R::store($executorsusergroup);   
          }    
       header("location:executors.php?do=show");
    } catch (Exception $e) {
       header("location:executors.php");
    }
}else if ($do == 'update') {
    $id = filter_input(INPUT_POST, 'id');
    $executorsclientid = filter_input(INPUT_POST, 'executorsclientid');
    $executorssellid = filter_input(INPUT_POST, 'executorssellid');
    $executorsuserids = explode(',', $_POST['executorsuserids']);
    $executors = R::load('executors',$id);
    $executors->executorsclientid = $executorsclientid;
    $executors->executorssellid = $executorssellid;
    $executors->executorsuserids = $_POST['executorsuserids'];
    try {
         R::store($executors);  
          $executorsusers = R::findAll('executorsusers', 'executorsid = ? ',[$id]);
          foreach ($executorsusers as $value) {
            if (!in_array($value->executorsid, $executorsuserids)) {
              R::exec("DELETE FROM `executorsusers` WHERE id = $value->id ");
            }
          }
          for ($i = 0; $i <= count($executorsuserids); $i++) {
            $executorsuserid = $executorsuserids[$i];
             $count = R::count('executorsusers', 'executorsid = ? and executorsuserid = ?', [$id, $executorsuserid]);
            if (!$executorsuserid || $count > 0) {continue;}
                $executorsusergroup = R::dispense('executorsusers');
                $executorsusergroup->del = 0;
                $executorsusergroup->today = $today;  
                $executorsusergroup->executorsid = $id;
                $executorsusergroup->executorsuserid = $executorsuserid;
                R::store($executorsusergroup);   
          }    
       header("location:executors.php?do=show");
    } catch (Exception $e) {
       header("location:executors.php");
    }
}


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 select2sellbill() {
    $row_array = array();
    $return_arr = array();
    $name = $_POST['searchTerm'];
    $clientid = $_POST['clientid'];
    
    $productsData = R::getAll("SELECT sellbillid, CONCAT(sellbillid,'/',datestarting) as texts
    FROM sellbill 
    WHERE conditions = 0 and CONCAT(sellbillid,'/',datestarting) LIKE '%" . $name . "%' and  sellbill.sellbillclientid = $clientid limit 50");
    foreach ($productsData as $pro) {
        $row_array['id'] = $pro['sellbillid'];
        $row_array['text'] = $pro['texts'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}



function showajax() {
    $columns = array('id', 'clientname', 'executorsuserids', 'executorsdate', 'executors.today', 'user.employeename', 'id', 'id', 'id', 'id', 'id');
    $start_date = $_POST['fromdate'];
    $end_date   = $_POST['todate'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];
    $data4      = $_POST['data4'];
    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and executors.executorsclientid = ".$data1. " ";
    }

    if($data2 != ''){
       $searchQuery .= " and executors.userid = ".$data2. " ";
    }
    $searchjoin = '';
    if($data3 != ''){
       $searchQuery .= " and executorsusers.executorsuserid = ".$data3. " ";
       $searchjoin .= " LEFT JOIN executorsusers ON executorsusers.executorsid = executors.id  ";
    }

    if($data4 != ''){
       $searchQuery .= " and executors.executorssellid = ".$data4. " ";
    }

    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  executors.executorsdate  >= "' . $start_date . '" and executors.executorsdate <= "' . $end_date . '" ';
    }

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


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  executors.id DESC ";
    }
    
     $totals = R::count('executors','
          LEFT JOIN user ON executors.userid = user.userid 
         LEFT JOIN client ON executors.executorsclientid = client.clientid   
         LEFT JOIN sellbill ON executors.executorssellid = sellbill.sellbillid 
         '.$searchjoin.' 
          WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT executors.* ,clientname , user.employeename, sellbilldate, sellbillfinalbill , datestarting FROM `executors`
        LEFT JOIN user ON executors.userid = user.userid 
         LEFT JOIN client ON executors.executorsclientid = client.clientid   
         LEFT JOIN sellbill ON executors.executorssellid = sellbill.sellbillid 
         '.$searchjoin.' 
         WHERE 1 '.$searchQuery.' '); 
           
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" =>  $totals,
        "recordsFiltered" => count($rResult),
        "data" => array()
    );
  
       foreach ($rResult as $row) {
         $users = R::getAll('select * from user where userid in  ('.$row["executorsuserids"] .')');
         $usertext = '';
         foreach($users as $user){
            $usertext .= $user['employeename'] . '/';

         }
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["clientname"];
        $sub_array[] = $usertext;
        $sub_array[] = $row["sellbilldate"] . '  / ' . $row["sellbillfinalbill"] ;
        $sub_array[] = $row["datestarting"];
        $sub_array[] = $row["today"];
        $sub_array[] = $row["employeename"];  
        if($row["del"] < 1){  
        $sub_array[] = '<a href="executors.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[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}






?>