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

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");
$time = date("H:i:s");
$smarty->assign('date', $date);
$smarty->assign('time', $time);
$smarty->assign('username', $_SESSION['username']);
if (empty($do)) {  
    $smarty->display("header.html");
    $smarty->display("visitsview/add.html");
    $smarty->assign("visits", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    // $maintenancecases = R::findAll('maintenancecases','conditions = 0');
    // $smarty->assign('maintenancecases', $maintenancecases);


    $smarty->display("header.html");
    $smarty->display("visitsview/show.html");
    $smarty->assign("visits", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $del = filter_input(INPUT_GET, 'del');
    $visitsdata = R::load('visits',$id);
    $smarty->assign('HostURL', Host_URL);


    // $users =R::getCell("SELECT employeename FROM `user` WHERE userid = ? ",[$visitsdata->userid]);
    // $visitsdata->employeename =  $users;

    $client =R::getCell("SELECT clientname FROM `client` WHERE clientid = ? ",[$visitsdata->clientid]);
    $visitsdata->client =  $client;

    $delegate =R::getCell("SELECT employeename FROM `user` WHERE userid = ? ",[$visitsdata->delegateid]);
    $visitsdata->delegate =  $delegate;
    
     $cases =R::getCell("SELECT cases FROM `visitcases` WHERE id = ? ",[$visitsdata->visitcaseid]);
    $visitsdata->cases =  $cases;
    // $new_time = explode(" ",$maintenancedata['dateatime']);
    // $smarty->assign('get_date', $new_time[0]);
    // $smarty->assign('get_time', $new_time[1]);
    $smarty->assign('visitsdata', $visitsdata);
    // $maintenancecomments = R::findAll('maintenancecomments','maintenanceid = ? and conditions = 0 order by id desc',[$id]);
    // foreach($maintenancecomments  as $comments){
    //     $last =R::getCell("SELECT employeename FROM `user` WHERE userid = ? ",[$comments->userid]);
    //     $comments->employeename =  $last;
    // }
    // $smarty->assign('maintenancecomments', $maintenancecomments);
    $smarty->assign('del', $del);
    $smarty->display("header.html");
    $smarty->display("visitsview/edit.html");
    $smarty->assign("visits", 1);
    $smarty->display("footer.html");
} elseif ($do == "allclient") {
    include_once("../public/authentication.php");
    $clientareaid = filter_input(INPUT_POST, 'clientareaid');
    $smarty->assign("clientareaid", $clientareaid);
    $clients =R::getAll("SELECT * FROM `client` WHERE clientareaid = ? ",[$clientareaid]);
    $smarty->assign("clients", $clients);

    $smarty->display("visitsview/appentcomment.html");
} elseif ($do == "recordattendance") {
    include_once("../public/authentication.php");
    // $maintenancecases = R::findAll('maintenancecases','conditions = 0');
    // $smarty->assign('maintenancecases', $maintenancecases);
    $smarty->display("header.html");
    $smarty->display("visitsview/recordattendance.html");
    $smarty->assign("visits", 1);
    $smarty->display("footer.html");    
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'rshowajax') {
  rshowajax();  
}else if ($do == 'savebranch') {
  savebranch();
}else if ($do == 'savecenter') {
  savecenter();
}else if ($do == 'savecase') {
  savecase();
}else if($do == 'savecomment') {
  savecomment();
}else if ($do == 'changecase') {
  changecase();
}else if ($do == 'changecenter') {
  changecenter();
}else if ($do == 'appentcomment') {  
$itr = filter_input(INPUT_POST, 'itr');
$appendname = filter_input(INPUT_POST, 'appendname');
$smarty->assign('itr', $itr);
$smarty->display("visitsview/".$appendname.".html");  
}else if ($do == 'updatecomment') {
  updatecomment();
}



function savecomment() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $comments = filter_input(INPUT_POST, 'comments');
    $maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecommentid) {
            $maintenancecomments = R::dispense('maintenancecomments');
            $maintenancecomments->maintenancecommentdate = $today;  
            $maintenancecomments->conditions = 0;
            $maintenancecomments->userid = $userid;
        }else{
            $maintenancecomments = R::load('maintenancecomments', $maintenancecommentid);
            $maintenancecomments->euserid = $userid;
        }
        $maintenancecomments->comments =  $comments;  
        $maintenancecomments->maintenanceid =  $selectitr;  
        $maintenancecommentid = R::store($maintenancecomments);
           
        $selectiditr = 'maintenancecommentid'.$selectitr;
        echo json_encode(array('id' => $maintenancecommentid,'selectname' => 'maintenancecommentid','selectid' => $selectiditr,'text' => $comments,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}

function savecase() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $casename = filter_input(INPUT_POST, 'casename');
    $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecaseid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecaseid) {
             $maintenancecases = R::dispense('maintenancecases');
        }else{
            $maintenancecases = R::load('maintenancecases', $maintenancecaseid);
        }
        $maintenancecases->casename =  $casename;  
        $maintenancecases->maintenancecasedate = $today;  
        $maintenancecases->conditions = 0;
        $maintenancecases->userid = $userid;
        $maintenancecaseid = R::store($maintenancecases);
        $selectiditr = 'maintenancecaseid'.$selectitr;
        echo json_encode(array('id' => $maintenancecaseid,'selectname' => 'maintenancecaseid','selectid' => $selectiditr,'text' => $casename,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savebranch() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $branchName = filter_input(INPUT_POST, 'branchName');
    $phone = filter_input(INPUT_POST, 'phone');
    $mobile = filter_input(INPUT_POST, 'mobile');
    $branchNo = filter_input(INPUT_POST, 'branchNo');
    $branchAddress = filter_input(INPUT_POST, 'branchAddress');
    $branchId = filter_input(INPUT_POST, 'branchId');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$branchId) {
          R::exec("INSERT INTO `branch`(`branchName`, `branchDate`, `phone`, `mobile`, `branchNo`, `branchAddress`) VALUES ('$branchName','$date','$phone','$mobile','$branchNo','$branchAddress')");
          $last =R::getROW("SELECT branchId, branchName FROM `branch` order by branchId desc");
          $branchId = $last['branchId'];
          $text = $last['branchName'];
        }else{
           R::exec("UPDATE `branch` SET `branchName`='$branchName',`phone`='$phone',`mobile`= '$mobile' ,`branchNo`= '$branchNo',`branchAddress`= '$branchAddress' WHERE branchId = $branchId");
           $text = $branchName;
        }

       $selectiditr = 'branchId'.$selectitr;
        echo json_encode(array('id' => $branchId,'selectname' => 'branchId','selectid' => $selectiditr,'text' => $text,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savecenter() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $centername = filter_input(INPUT_POST, 'centername');
    $centerphone = filter_input(INPUT_POST, 'centerphone');
    $centermobile = filter_input(INPUT_POST, 'centermobile');
    $centeraddress = filter_input(INPUT_POST, 'centeraddress');
    $administrator = filter_input(INPUT_POST, 'administrator');
    $administratorphone = filter_input(INPUT_POST, 'administratorphone');
    $administratordebt = filter_input(INPUT_POST, 'administratordebt');
    $maintenancecenterid = filter_input(INPUT_POST, 'maintenancecenterid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    try {
        if (!$maintenancecenterid) {
            $maintenancecenters = R::dispense('maintenancecenters');
            $maintenancecenters->maintenancecenterdate = $today;  
            $maintenancecenters->conditions = 0;
            $maintenancecenters->userid = $userid;
        }else{
            $maintenancecenters = R::load('maintenancecenters',$maintenancecenterid);
            $maintenancecenters->euserid = $userid;
        }
            $maintenancecenters->centername =  $centername;  
            $maintenancecenters->centerphone =  $centerphone;  
            $maintenancecenters->centermobile =  $centermobile;  
            $maintenancecenters->centeraddress =  $centeraddress;  
            $maintenancecenters->administrator =  $administrator;  
            $maintenancecenters->administratorphone =  $administratorphone;  
            $maintenancecenters->administratordebt =  $administratordebt;  
            $maintenancecenterid = R::store($maintenancecenters);
            if ($selectitr) {
              R::exec("UPDATE `maintenances` SET `maintenancecenterid`= $maintenancecenterid WHERE id = $selectitr");
            }
           
        $selectiditr = 'maintenancecenterid'.$selectitr;
        echo json_encode(array('id' => $maintenancecenterid,'selectname' => 'maintenancecenterid','selectid' => $selectiditr,'text' => $centername,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
  
    $clientid = filter_input(INPUT_POST, 'client');
    $dateofvisit = filter_input(INPUT_POST, 'dateofvisit'); 
    $delegateid = filter_input(INPUT_POST, 'delegateid');
    $selectitr  = filter_input(INPUT_POST, 'selectitr');
    $visitid = filter_input(INPUT_POST, 'visitid');
    $clients = filter_input(INPUT_POST, 'clients');
    try {
        if (!$visitid) {
            for ($i = 1; $i <= $clients; $i++) {
                $client_idi = filter_input(INPUT_POST, 'client_id_' . $i);
                $clientcode = filter_input(INPUT_POST, 'clientcode_' . $i);
                if($client_idi){
                    $visits = R::dispense('visits');
                    $visits->visitsdate = $today;  
                    $visits->conditions = 0;
                    $visits->userid = $userid;
                    $visits->clientid = $client_idi;          
                    $visits->vclientcode = $clientcode;          
                    $visits->delegateid = $delegateid;
                    $visits->dateofvisit = $dateofvisit;
                    $visits->newvisit = 0;
                    $visitid = R::store($visits);
                }
                
            }
            // $visits->start_lat = '';
            // $visits->start_long = '';
            // $visits->textdiffbetvisit = '';
            // $visits->start_date = $today;
            // $visits->end_lat = '';
            // $visits->end_long = '';
            // $visits->imageendvisit = '';
            // $visits->end_date = $today;
        }else{
            $clientcode =R::getCell("SELECT clientcode FROM `client` WHERE client_id = ? ",[$clientid]);

            $visits = R::load('visits',$visitid);
            $visits->euserid = $userid;
            $visits->clientid = $clientid;    
            $visits->vclientcode = $clientcode;         
            $visits->delegateid = $delegateid;
            $visits->dateofvisit = $dateofvisit;
            $visits->newvisit = 0;
            $visitid = R::store($visits);
        }
            

            // for ($i = 1; $i <= $commentitr; $i++) {
            //     $maintenancecommentid = filter_input(INPUT_POST, 'maintenancecommentid_' . $i);
            //     $comments = filter_input(INPUT_POST, 'comments_' . $i);

            //     if (!$comments) {
            //         continue;
            //     }
            //     if (!$maintenancecommentid) {
            //         $maintenancecomments = R::dispense('maintenancecomments');
            //         $maintenancecomments->maintenancecommentdate = $today;  
            //         $maintenancecomments->conditions = 0;
            //         $maintenancecomments->userid = $userid;
            //     }else{
            //         $maintenancecomments = R::load('maintenancecomments', $maintenancecommentid);
            //         $maintenancecomments->euserid = $userid;
            //     }
            //     $maintenancecomments->comments =  $comments;  
            //     $maintenancecomments->maintenanceid = $maintenanceid;  
            //     R::store($maintenancecomments);
            // }

        $selectiditr = 'visitid'.$selectitr;
        echo json_encode(array('id' => $visitid,'selectname' => 'visitid','selectid' => $selectiditr,'text' => $text,'selectid' => $selectiditr,'selectitr' => $selectitr));
    } catch (Exception $e) {
        echo 0 ;
    }
}


function rshowajax() {
    $columns = array('id', 'employeename', 'lat', 'long', 'addtoday', 'user.usergroupid');
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];
    $data4      = $_POST['data4'];
    $data5      = $_POST['data5'];

    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and recordattendance.user_id = ".$data1. " ";
    }

    if($data2 != ''){
      $searchQuery .=  " and visits.clientid = ".$data2. " ";
    }
    // if($del == ''){
       $searchQuery .= " and recordattendance.conditions = 0 "; 
    // }

    // if($data3 != ''){
    //    $searchQuery .= " and maintenances.branchid = ".$data3. " ";
    // }

    // if($data4 != '' && $data4 > 0){
    //    $searchQuery .= " and maintenances.maintorguar = ".$data4. " ";
    // }

    // if($data5 != ''){
    //    $searchQuery .= " and maintenances.maintenancecaseid = ".$data5. " ";
    // }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .=' and  recordattendance.addtoday  >= "' . $start_date . ' 00-00-00" and recordattendance.addtoday <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( recordattendance.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR employeename LIKE "%'.$_POST["search"]["value"].'%"
                    OR lat LIKE "%'.$_POST["search"]["value"].'%"
                    OR long LIKE "%'.$_POST["search"]["value"].'%"
                    OR addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR user.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  recordattendance.id DESC ";
    }
    
     $totals = R::count('recordattendance','LEFT JOIN user ON recordattendance.user_id = user.userid 
        LEFT JOIN usergroup ON user.usergroupid = usergroup.usergroupid 
        
    
          WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT recordattendance.* ,user.employeename , usergroupname FROM `recordattendance` 
        LEFT JOIN user ON recordattendance.user_id = user.userid 
        LEFT JOIN usergroup ON user.usergroupid = usergroup.usergroupid 
        WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        // $comments = R::findOne('maintenancecomments','maintenanceid = ? order by id desc',[$row['id']]);
        // $products = R::getAll("SELECT productName FROM product  WHERE productId in (".$row['productid'].")");
        // $productName = '';
        // foreach($products as $product){
        //       $productName .= $product['productName']. ' / ';
        // }
          
        $sub_array = array();
          $sub_array[] = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                            <input type="checkbox" class="checkboxes" value="' . $row["id"] . '" />
                            <span></span>
                        </label>';
        $sub_array[] = $row["employeename"];
        $sub_array[] = $row["lat"];
        $sub_array[] = $row["long"];
        $sub_array[] = '<a style="background:#000000;color:#ffffff;font-size:15px;padding:3px 7px;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;
                             text-decoration:none;" href="https://www.google.es/maps/place/'.$row["lat"].','.$row["long"].'" target="_blank" >open   </a>';
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["usergroupname"];
        // $sub_array[] = $row['employeename']; 
        // if($row["maintorguar"] == 1){  
        // $sub_array[] = ' <input id="maintenancecenterid'.$row["id"].'" type="text" name="maintenancecenters"  class="getselectjoin2 maintenancecenterid'.$row["id"].'"  data-placeholder=" المراكز    "   data-table="maintenancecenters" data-tableid="id"  data-join=""   data-filter="" data-parent="" data-itr="'.$row["id"].'"  data-search="centername"/>
        //     <input  type="hidden" name="maintenancecenterid" class="selectedit2" data-itr="'.$row["id"].'" data-join="" data-table="maintenancecenters" data-tableid="id" data-tableidname="maintenancecenterid" data-search="centername" value="'.$row["maintenancecenterid"].'" /><br>
        //     <button type="button" class="btn btn-primary adddatamodal" data-table="maintenancecenters" data-tableid="maintenancecenterid" data-toggle="modal" data-target="#Modalmaintenancecenterid" data-whatever="@maintenancecenters" data-formt="formmaintenancecenters" data-selectitr="'.$row["id"].'"> A</button>
        //     <button type="button" class="btn btn-primary editdatamodal"  data-model="#Modalmaintenancecenterid" data-table="maintenancecenters" data-name="maintenancecenterid" data-tableid="id" data-join="" data-formt="formmaintenancecenters" data-selectitr="'.$row["id"].'">E</button>'; 
        // }else{
        //      $sub_array[] = 'ضمان'; 
        // }
        // $sub_array[] = ' <input  id="maintenancecommentid'.$row["id"].'"   type="text" class="form-control maintenancecomments" value="'.$comments->comments.'" data-id="'.$comments->id.'" data-maintenanceid="'.$row["id"].'"  />
        //     <button type="button" class="btn btn-primary adddatamodal" data-table="maintenancecomments" data-tableid="maintenancecommentid" data-toggle="modal" data-target="#Modalmaintenancecommentid" data-whatever="@maintenancecomments" data-formt="formmaintenancecomments" data-selectitr="'.$row["id"].'"> A</button>
          
        //      ';  
        if($row["conditions"] == 0){  
        // $sub_array[] = '<a href="visitsController.php?do=edit&id='. $row["id"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-tableid="id" data-table="recordattendance" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="visitsController.php?do=edit&id='. $row["id"] .'&del=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          // $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}



function showajax() {
    $columns = array('visits.id', 'visits.clientid', 'dateofvisit', 'start_date','end_date','vdiffminutes','vspacestrue','visitcaseid','newvisit','employeename', 'visits.id', 'visits.id');
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];
    $data4      = $_POST['data4'];
    $data5      = $_POST['data5'];

    $searchQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and visits.delegateid = ".$data1. " ";
    }
    // else{
    //   $output = array(  
    //     "draw" => intval($_POST["draw"]),
    //     "recordsTotal" => 0,
    //     "recordsFiltered" =>0,
    //     "data" => array()
    //   );  
    //   echo json_encode($output, JSON_UNESCAPED_SLASHES);
    //   exit();
    // }

    if($data2 != ''){
      $searchQuery .=  " and visits.clientid = ".$data2. " ";
    }
    if($del == ''){
       $searchQuery .= " and visits.conditions = 0 "; 
    }

    if($data3 != ''){
        $searchQuery .= " and visits.visitcaseid = ".$data3. " ";
    }

    // if($data4 != '' && $data4 > 0){
    //    $searchQuery .= " and maintenances.maintorguar = ".$data4. " ";
    // }

    // if($data5 != ''){
    //    $searchQuery .= " and maintenances.maintenancecaseid = ".$data5. " ";
    // }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .=' and  visits.visitsdate  >= "' . $start_date . ' 00-00-00" and visits.visitsdate <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( visits.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR clientname LIKE "%'.$_POST["search"]["value"].'%"
                    OR visitsdate LIKE "%'.$_POST["search"]["value"].'%"
                    OR start_date LIKE "%'.$_POST["search"]["value"].'%"
                    OR end_date LIKE "%'.$_POST["search"]["value"].'%"
                    OR user.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  visits.id DESC ";
    }
    
    
    
     $totals = R::count('visits','LEFT JOIN user ON visits.userid = user.userid 
        LEFT JOIN client ON visits.clientid = client.clientid
        LEFT JOIN visitcases ON visits.visitcaseid = visitcases.id
        WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT visits.* ,user.employeename ,clientname, duser.employeename as delegate, cases  FROM `visits` 
        LEFT JOIN user ON visits.userid = user.userid 
        LEFT JOIN user as duser ON visits.delegateid = duser.userid 
        LEFT JOIN client ON visits.clientid = client.clientid 
        LEFT JOIN visitcases ON visits.visitcaseid = visitcases.id
        WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        // $comments = R::findOne('maintenancecomments','maintenanceid = ? order by id desc',[$row['id']]);
        // $products = R::getAll("SELECT productName FROM product  WHERE productId in (".$row['productid'].")");
        // $productName = '';
        // foreach($products as $product){
        //       $productName .= $product['productName']. ' / ';
        // }
          
        $sub_array = array();
          $sub_array[] = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                            <input type="checkbox" class="checkboxes" value="' . $row["id"] . '" />
                            <span></span>
                        </label>';
        $sub_array[] = $row["clientname"];
        $sub_array[] = $row["dateofvisit"];
        // $sub_array[] = $row["delegate"];
        $sub_array[] = $row["start_date"];
        $sub_array[] = $row["end_date"];
        $sub_array[] = $row["vdiffminutes"];
        if($row["vspacestrue"] == 1){
             $sub_array[] = ' داخل النطاق';
        }else{
            $sub_array[] = 'خارج النطاق  ';
        }
        $sub_array[] = $row["cases"];
        if($row["newvisit"] == 0){
             $sub_array[] = 'زياره جديده';
        }elseif($row["newvisit"]  == 1){
            $sub_array[] = 'تم بدأ الزياره';
        }else{
            $sub_array[] = 'تم انهاء الزياره';
        }
        $sub_array[] = $row["visitsdate"];
        $sub_array[] = $row['employeename']; 
        if($row["conditions"] == 0){  
        $sub_array[] = '<a href="visitsController.php?do=edit&id='. $row["id"] .'&del=0" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-tableid="id" data-table="visits" type="button" class="btn btn-default btn-lg deleteicon removeteble"  ></a>';
        }else{
          $sub_array[] = '<a href="visitsController.php?do=edit&id='. $row["id"] .'&del=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
        $output['data'][] = $sub_array;
        
        if($data1 != ''){
            if($row["before_visitid"] > 0){
            $checknewvisit = R::getROW("select * from visits where id = ?",[$row["before_visitid"]]);    
     
            $sub_array2 = array();
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = $checknewvisit['dateofvisit'];
            $sub_array2[] = $checknewvisit['end_date'];
            $sub_array2[] = $row["start_date"];
            $sub_array2[] = $row["textdiffbetvisit"];
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = '';
            $sub_array2[] = '';
            $output['data'][] = $sub_array2;
            }
        }
        
        // print_r($output['data']);
        // exit();
        
        
        
        
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}





function changecase() {
    $id = filter_input(INPUT_POST, 'myid');
    $maintenancecaseid = filter_input(INPUT_POST, 'maintenancecaseid');
    $tables = R::load('maintenances',$id);
    $tables->maintenancecaseid = $maintenancecaseid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function changecenter() {
    $id = filter_input(INPUT_POST, 'id');
    $maintenancecenterid = filter_input(INPUT_POST, 'maintenancecenterid');
    $tables = R::load('maintenances',$id);
    $tables->maintenancecenterid = $maintenancecenterid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}

function updatecomment() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'myid');
    $values = filter_input(INPUT_POST, 'values');
    $maintenanceid = filter_input(INPUT_POST, 'maintenanceid');
    $tables = R::load('maintenancecomments',$id);
    $tables->comments = $values;
    $tables->conditions = 0;
    $tables->maintenanceid = $maintenanceid;
    $tables->maintenancecommentdate = $today;  
    $tables->userid = $userid;
    try {
        R::store($tables);
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}





?>