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



$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

if (empty($do)) {  

    $search_params = '';
    if( $_SESSION['projectids'] != 0){
        $search_params = ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }
    $projects = R::getAll('SELECT project.* FROM `project` WHERE project.del = 0  ' .  $search_params);
    $smarty->assign('projects', $projects);
    $smarty->display("header.html");
    $smarty->display("projectclientsview/add.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $smarty->assign('date', $date);
      $search_params = '';
    if( $_SESSION['projectids'] != 0){
        $search_params = ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }
    $projects = R::getAll('SELECT project.* FROM `project` WHERE project.del = 0  ' .  $search_params);
    $smarty->assign('projects', $projects);
    $smarty->display("header.html");
    $smarty->display("projectclientsview/show.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $webclientdata = R::load('webclients', $id);
    $webclientdata->clientids = explode(',', $webclientdata->clientids);
    $smarty->assign('webclientdata', $webclientdata);
     $search_params = '';
    if( $_SESSION['projectids'] != 0){
        $search_params = ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }
    $projects = R::getAll('SELECT project.* FROM `project` WHERE project.del = 0  ' .  $search_params);
    $smarty->assign('projects', $projects);

    $smarty->display("header.html");
    $smarty->display("projectclientsview/edit.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removecontroller') {
  removecontroller();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $name = filter_input(INPUT_POST, 'name');
    $mobile = filter_input(INPUT_POST, 'mobile');
    $user_name = filter_input(INPUT_POST, 'user_name');
    $password = filter_input(INPUT_POST, 'password');
    $showpdf = filter_input(INPUT_POST, 'showpdf');
    $is_active = filter_input(INPUT_POST, 'is_active');
    $clientids = filter_input(INPUT_POST, 'clientids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $webclientidold = filter_input(INPUT_POST, 'webclientid');
    // print_r($webclientidold);
    // exit();

    if (!$webclientidold) {;
        $projectclients = R::dispense('webclients');
        $projectclients->del = 0;
        $projectclients->addtoday = $today;          
        $projectclients->adduserid = $userid;
        $projectclients->deltoday = '';      
        $projectclients->deluserid = '';
        $handle = new upload($_FILES['filepdf']);
        $filepdf = uploadImages($handle, "../views/default/images/webclients", 300, 300);
    }else{
        $projectclients = R::load('webclients',$webclientidold);
        $projectclients->del = 1;
        $projectclients->updatetoday = $today;   
        $projectclients->adduserid = $userid;
        $projectclients->updateuserid = $userid; 
        $handle = new upload($_FILES['filepdf']);
        $filepdf = updateImages($handle, "oldfilepdf", "../views/default/images/webclients", 300, 300);
        unlink("../views/default/images/webclients" . $projectclients->filepdf);
    }
    $projectclients->name  = $name;
    $projectclients->mobile = $mobile;
    $projectclients->user_name = $user_name; 
    $projectclients->password = $password; 
    $projectclients->filepdf = $filepdf;
    $projectclients->showpdf = $showpdf;
    $projectclients->is_active = $is_active;
    $projectclients->device_id = '';
    if (in_array("0", $clientids)) {
        $projectclients->clientids =  '0';
    }else{
        $projectclients->clientids =  '-1,'.implode(",", $clientids);
    }
    try {
         $webclientid = R::store($projectclients);

         for ($i=0; $i <= count($clientids); $i++) { 
             if (!$clientids[$i]) {continue;}
             if (!$webclientidold) {
                $project = R::findOne('project', 'clientid = ? ',[$clientids[$i]]);
                $webclientprojects = R::dispense('webclientprojects');
                $webclientprojects->webclientid = $webclientid;
                $webclientprojects->clientid = $clientids[$i];          
                $webclientprojects->projectid =  $project->id;
                R::store($webclientprojects);
             }else{
                $webclientprojectsold = R::findAll('webclientprojects', 'webclientid = ? ',[$webclientid]);
                foreach ($webclientprojectsold as $value) {
                    if (!in_array($value->clientid, $clientids)) {
                       R::trash($value);
                    }
                }
                $count = R::count('webclientprojects', 'webclientid = ? and clientid = ?', [$webclientid, $clientids[$i]]);
                if ($count == 0) {
                    $webclientprojects = R::dispense('webclientprojects');
                    $webclientprojects->webclientid = $webclientid;
                    $webclientprojects->clientid = $clientids[$i];          
                    $webclientprojects->projectid =  $project->id;
                    R::store($webclientprojects);
                }
             }
           
         }
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    $columns = array('webclients.id','name', 'webclients.mobile','user_name', 'clientids', 'addtoday','employeename', 'id', 'id');
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $del        = $_POST['del'];
    $data1      = $_POST['data1'];
    $data2      = $_POST['data2'];
    $data3      = $_POST['data3'];

    $searchQuery = " ";
    $joinQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and webclients.id = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and webclients.del < 2 "; 
    }

    if($data3 != ''){
       $joinQuery .= " LEFT JOIN webclientprojects ON webclients.id = webclientprojects.webclientid ";
       $searchQuery .= " and webclientprojects.clientid = ".$data3. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  webclients.addtoday  >= "' . $start_date . ' 00-00-00" and webclients.addtoday <= "' . $end_date . ' 23-59-55" ';
    }else{
        $today = date("Y-m-d");
        $searchQuery .='and  webclients.addtoday  >= "' . $today . ' 00-00-00" and webclients.addtoday <= "' . $today . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( webclients.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR webclients.name LIKE "%'.$_POST["search"]["value"].'%"
                    OR webclients.mobile LIKE "%'.$_POST["search"]["value"].'%"
                    OR webclients.user_name LIKE "%'.$_POST["search"]["value"].'%"
                    OR webclients.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR 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  webclients.id DESC ";
    }


     $totals = R::count('webclients',"LEFT JOIN user ON webclients.adduserid = user.userid $joinQuery  WHERE 1 $searchQuery ");
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll("SELECT webclients.* ,employeename   FROM `webclients` LEFT JOIN user
         ON webclients.adduserid = user.userid $joinQuery  WHERE 1 $searchQuery ");   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => $totals,
        "recordsFiltered" =>intval($apps),
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $date = date('Y-m-d');
         $clients = R::getAll('SELECT client.* FROM `client` LEFT JOIN webclientprojects ON client.clientid = webclientprojects.clientid WHERE webclientprojects.webclientid = ?',[$row["id"]]);
         $clientname = '';
         foreach ($clients as  $value) {
             $clientname .= $value['clientname'] . ' / ';
         }

        $sub_array = array();
        $sub_array[] = $row["id"];
        //  if ($row["filepdf"] != "." && $row["filepdf"] != "") {
        //    $sub_array[] = '<a src="../views/default/images/students/'. $row["filepdf"] .'"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;">';
        // }else{
        //    $sub_array[] = ' <img src="../views/default/assets/img/blank.png"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;" alt="" class="card-img">';
        // }
        $sub_array[] = $row["name"];
        $sub_array[] = $row["mobile"];
        $sub_array[] = $row["user_name"];
        // if ($studentspays > 0 && $row["del"] < 2) {
        //     $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" type="button" class="btn btn-default btn-lm studentspaysend"  >الكود</a>';
        // }else if ($studentspays > 0 && $row["del"] > 2) {
        //    $sub_array[] = ' موجود دفع ولكن الطالب محذوف   ';
        // }else{
        //     $sub_array[] = 'لا يوجد';
        // }
        $sub_array[] =  rtrim($clientname, " /");
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row['employeename'] ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="projectclientsController.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"] .'" data-controll="studentController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = '<a href="projectclientsController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}



function removecontroller() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('students',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        R::exec("UPDATE `client` SET `conditions`= 1 WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentaddsubjectdetails` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentsexamsval` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentspays` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentid = '" . $id . "' ");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}





?>