<?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)) {  
    
    
    $trainerssetting = R::load('trainerssetting',1);
    // $trainersaddsubjects = R::load('trainersaddsubjects',$trainersetting->trainersaddsubjectid);
    // $trainersubjects = R::load('trainersubjects',$trainersaddsubjects->trainersubjectid);
    // $trainersubjectgroups = R::load('trainersubjectgroups',$trainersaddsubjects->trainersubjectgroupid);
    // $subjectgroups =$trainersubjects->subjectname.'/'.$trainersubjectgroups->subjectgroupname.'/'.$trainersubjectgroups->subjectgroupprice;
    // $smarty->assign("subjectgroups",$subjectgroups);
    // $smarty->assign("trainersaddsubjects",$trainersaddsubjects);
    $smarty->assign("trainerssetting",$trainerssetting);

    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    $smarty->display("header.html");
    $smarty->display("trainersview/add.html");
    $smarty->assign("trainers", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $trainerssetting = R::load('trainerssetting',1);
    $smarty->assign("trainerssetting",$trainerssetting);
      $show = filter_input(INPUT_GET, 'show');
      if($show == 2){
           $smarty->assign('show', 2);
      }
     
    $smarty->assign('date', $date);
    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    
    $smarty->display("header.html");
    $smarty->display("trainersview/show.html");
    $smarty->assign("trainers", 1);
    $smarty->display("footer.html");
    
 
    
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $trainersdata = R::load('trainers', $id);
    $smarty->assign('trainersdata', $trainersdata);
    
    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    
    $trainerssetting = R::load('trainerssetting',1);
    $smarty->assign("trainerssetting",$trainerssetting);
    $smarty->display("header.html");
    $smarty->display("trainersview/edit.html");
    $smarty->assign("trainers", 1);
    $smarty->display("footer.html");
    
    
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'showajax2') {
  showajax2();  
}else if ($do == 'removecontroller') {
  removecontroller();
}


function savedata() {
  include "../library/phpqrcode/qrlib.php";    
   
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $trainersname = filter_input(INPUT_POST, 'trainersname');
    $trainersnumber = filter_input(INPUT_POST, 'trainersnumber');
    $idnumber = filter_input(INPUT_POST, 'idnumber');
    $trainersphone = filter_input(INPUT_POST, 'trainersphone');
    // $parentsname = filter_input(INPUT_POST, 'parentsname');
    // $parentsphone = filter_input(INPUT_POST, 'parentsphone');
    // $parentsjob = filter_input(INPUT_POST, 'parentsjob');
    // $parentsname2 = filter_input($trainersaddsubjectidINPUT_POST, 'parentsname2');
    // $parentsphone2 = filter_input(INPUT_POST, 'parentsphone2');
    // $parentsjob2 = filter_input(INPUT_POST, 'parentsjob2');
    
    
    $trainersaddress = filter_input(INPUT_POST, 'trainersaddress');
    $trainersnote = filter_input(INPUT_POST, 'trainersnote');
    $branchid = filter_input(INPUT_POST, 'branchid');
    // $datebirth = filter_input(INPUT_POST, 'datebirth');
    // $namepay = filter_input(INPUT_POST, 'namepay');
    // $commentpay = filter_input(INPUT_POST, 'commentpay');
    // $trainersaddsubjectid = filter_input(INPUT_POST, 'trainersaddsubjectid');
    $trainersid = filter_input(INPUT_POST, 'trainersid');
    $clientid = filter_input(INPUT_POST, 'clientid');
    // $nickname = filter_input(INPUT_POST, 'nickname');
    // $gender = filter_input(INPUT_POST, 'gender');
    // $nationality = filter_input(INPUT_POST, 'nationality');
    // $placebirth = filter_input(INPUT_POST, 'placebirth');
    // $schoolname = filter_input(INPUT_POST, 'schoolname');
    // $classroom = filter_input(INPUT_POST, 'classroom');
    // $playerfavoriteclub = filter_input(INPUT_POST, 'playerfavoriteclub');
    // $playerfavoriteplayer = filter_input(INPUT_POST, 'playerfavoriteplayer');
    // $playedsoccer = filter_input(INPUT_POST, 'playedsoccer');
    // $clubacademy = filter_input(INPUT_POST, 'clubacademy');
    $agrees = filter_input(INPUT_POST, 'agrees');
    // $payvalnew  = filter_input(INPUT_POST, 'payvalnew');
    $stopping  = filter_input(INPUT_POST, 'stopping');
    $stopcomment  = filter_input(INPUT_POST, 'stopcomment');

    if (!$trainersid) {;
        $trainers = R::dispense('trainers');
        $stopping = 0;
        $trainers->del = 0;
        $trainers->addtoday = $today;          
        $trainers->adduserid = $userid;
        $trainers->deltoday = '';      
        $trainers->deluserid = '';
        $handle = new upload($_FILES['trainersimage']);
        $trainersimage = uploadImages($handle, "../views/default/images/trainers", 300, 300);
    }else{
        $trainers = R::load('trainers',$trainersid);
        if( $trainers->del != 5){
             R::exec("UPDATE `client` SET `clientname`= '$trainersname',`clientaddress`= '$trainersaddress',`clientphone`= '$trainersphone',`branchId`= $branchid WHERE clientid = $clientid");
        }
      
        $trainers->del = 1;
        $trainers->updatetoday = $today;          
        $trainers->updateuserid = $userid; 
        $handle = new upload($_FILES['trainersimage']);
        $trainersimage = updateImages($handle, "oldtrainersimage", "../views/default/images/trainers", 300, 300);
        unlink("../views/default/images/trainers" . $trainers->trainersimage);
    }
    // $trainers->nickname  = $nickname;
    // $trainers->payvalnew  = $payvalnew;
    // $trainers->gender  = $gender;
    // $trainers->nationality  = $nationality;
    // $trainers->placebirth  = $placebirth;
    // $trainers->schoolname  = $schoolname;
    // $trainers->classroom  = $classroom;
    // $trainers->playerfavoriteclub  = $playerfavoriteclub;
    // $trainers->playerfavoriteplayer  = $playerfavoriteplayer;
    // $trainers->playedsoccer  = $playedsoccer;
    // $trainers->clubacademy  = $clubacademy;
    $trainers->trainersname  = $trainersname;
    $trainers->trainersnumber = $trainersnumber;
    $trainers->idnumber = $idnumber;
    $trainers->trainersphone = $trainersphone;
    // $trainers->parentsname = $parentsname;
    // $trainers->parentsphone = $parentsphone;
    // $trainers->parentsjob = $parentsjob;
    // $trainers->parentsname2 = $parentsname2;
    // $trainers->parentsphone2 = $parentsphone2;
    // $trainers->parentsjob2 = $parentsjob2;
    $trainers->trainersaddress = $trainersaddress;
    $trainers->clientid = $clientid; 
    $trainers->branchid = $branchid; 
    $trainers->trainersimage = $trainersimage;
    $trainers->trainersnote = $trainersnote;
    // $trainers->datebirth = $datebirth;
    // $trainers->namepay = $namepay;
    // $trainers->commentpay = $commentpay;
    $trainers->stopping = $stopping;
    $trainers->stopcomment = $stopcomment;
    try {
         $trainersid = R::store($trainers);
            if (!$clientid) {
             R::exec("INSERT INTO `client`(`clientname`, `clientaddress`, `clientphone`, `clientdate`, `userid`, `branchId`, `clientStoreIds`, `typeclientid`, `priceTypeId`, `trainersid`) VALUES 
             ('$trainersname', '$trainersaddress', '$trainersphone','$date', $userid, $branchid, '-10', ',-20,', -1, $trainersid)");
             $client = R::getCell("SELECT clientid FROM `client` WHERE trainersid =  $trainersid");
             $trainers = R::load('trainers',$trainersid);
             $trainers->clientid = $client; 
             $trainersid = R::store($trainers);
            }else{
               R::exec("UPDATE `client` SET `clientname`='$trainersname',`clientaddress`='$trainersaddress',`conditions`= 0,`clientphone`='$trainersphone',`branchId`= $branchid 
               WHERE clientid = $clientid");
            }
        //   if($trainersaddsubjectid){
        //         $trainersaddsubjects = R::load('trainersaddsubjects',$trainersaddsubjectid); 
        //         $trainersaddsubjects->del = 1;
        //         $trainersaddsubjects->updatetoday = $today;          
        //         $trainersaddsubjects->updateuserid = $userid;
        //         $trainersaddsubjects->trainersid = $trainersaddsubjects->trainersid.','.$trainersid;
        //         R::store($trainersaddsubjects);
        //         // $trainersdata = R::load('trainers',$Explode[$i]); 
        //         $trainersaddsubjectdetails = R::dispense('trainersaddsubjectdetails');
        //         $trainersaddsubjectdetails->trainersid  = $trainersid;
        //         $trainersaddsubjectdetails->trainersubjectid  = $trainersaddsubjects->trainersubjectid;
        //         $trainersaddsubjectdetails->trainersubjectgroupid = $trainersaddsubjects->trainersubjectgroupid;
        //         $trainersaddsubjectdetails->del = 0;
        //         $trainersaddsubjectdetails->trainersaddsubjectid = $trainersaddsubjectid;
        //         R::store($trainersaddsubjectdetails); 
        //   }
           
            if ($trainers->del == 0 || $agrees == 5) {
                $PNG_TEMP_DIR = "../views/default/images/trainersparcode/";
                $filename = $PNG_TEMP_DIR.$trainersid.'trainers.png';
                $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/trainersControllerAjax.php?do=detailtrainers&trainersid=' . $trainersid;
                QRcode::png($url, $filename, 'L', 9, 2);    
            }
    
   
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    $columns = array('id', 'id', 'trainersname', 'trainersphone', 'paystartdate', 'payenddate', 'addtoday', 'payvalnew', 'branchName', 'employeename', 'id', '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 = " ";
    if($data1 != ''){
      $searchQuery .=  " and trainers.id = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and trainers.del < 2 "; 
    }

    if($data3 != ''){
       $searchQuery .= " and trainers.branchid = ".$data3. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  trainers.addtoday  >= "' . $start_date . ' 00-00-00" and trainers.addtoday <= "' . $end_date . ' 23-59-55" ';
    }else{
        // $today = date("Y-m-d");
        // $searchQuery .='and  trainers.addtoday  >= "' . $today . ' 00-00-00" and trainers.addtoday <= "' . $today . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( trainers.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR trainers.trainersnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.idnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.trainersphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR branchName 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  trainers.id DESC ";
    }
    
     $totals = R::count('trainers','LEFT JOIN user
         ON trainers.adduserid = user.userid LEFT JOIN branch
         ON trainers.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT trainers.* ,employeename ,branchName  FROM `trainers` LEFT JOIN user
         ON trainers.adduserid = user.userid LEFT JOIN branch
         ON trainers.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $date = date('Y-m-d');
         $trainerspays = R::count('trainerspays',"trainersid = ? and del < 2 and payenddate > '$date'",[$row['id']]);
         $trainerspaylast = R::findone('trainerspays',"trainersid = ? and del < 2 order by id desc",[$row['id']]);
        $sub_array = array();
        $sub_array[] = $row["id"];
         if ($row["trainersimage"] != "." && $row["trainersimage"] != "") {
           $sub_array[] = '<img src="../views/default/images/trainers/'. $row["trainersimage"] .'"  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["trainersname"];
        // $sub_array[] = $row["trainersnumber"];
        // $sub_array[] = $row["idnumber"];
        $sub_array[] = $row["trainersphone"];
        $sub_array[] = '<a href="trainersControllerAjax.php?do=payed&studentid='. $row["id"] .'&deviceid=01" type="button" class="btn btn-default btn-lm ">حضور</a>';
        if ($trainerspays > 0 && $row["del"] < 2) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" type="button" class="btn btn-default btn-lm trainerspaysend"  >الكود</a>';
        }else if ($trainerspays > 0 && $row["del"] > 2) {
           $sub_array[] = ' موجود دفع ولكن الطالب محذوف   ';
        }else{
            $sub_array[] = 'لا يوجد';
        }
        $sub_array[] = $trainerspaylast->paystartdate;
        $sub_array[] = $trainerspaylast->payenddate;
        $sub_array[] = $row["addtoday"];
        $sub_array[] = '<input    value="'.$row['payvalnew'].'"   type="text" name="payvalnew" digits="true"  class="form-control nummbers" placeholder=" قيمة الدفع     " />     '; 
        $sub_array[] = $row["branchName"];
        $sub_array[] = $row['employeename'];  
          $sub_array[] = '<a href="../views/default/images/trainersparcode/'. $row["id"] .'trainers.png" download> باركود </a>' ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="trainersController.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="trainersController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
         
        }else  if($row["del"] == 5){
              $sub_array[] = '<a href="trainersController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
              $sub_array[] = 'انتظار القبول ';
        }else{
          $sub_array[] = '<a href="trainersController.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 showajax2() {
    $columns = array('id', 'id', 'trainersname', 'trainersnumber','idnumber', 'trainersphone', 'parentsphone', 'trainerspayid', 'paystartdate', 'payenddate', 'addtoday', 'payvalnew', 'branchName', 'employeename', 'id', '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 = " ";
    if($data1 != ''){
      $searchQuery .=  " and trainers.id = ".$data1. " ";
    }
   
       $searchQuery .= " and trainers.del = 5 "; 
    

    if($data3 != ''){
       $searchQuery .= " and trainers.branchid = ".$data3. " ";
    }
    
    if($start_date != '' && $end_date != ''){
       $searchQuery .='and  trainers.addtoday  >= "' . $start_date . ' 00-00-00" and trainers.addtoday <= "' . $end_date . ' 23-59-55" ';
    }else{
        // $today = date("Y-m-d");
        // $searchQuery .='and  trainers.addtoday  >= "' . $today . ' 00-00-00" and trainers.addtoday <= "' . $today . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( trainers.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR trainers.trainersnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.idnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.trainersphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.parentsphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainers.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR branchName 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  trainers.id DESC ";
    }
    
     $totals = R::count('trainers','LEFT JOIN user
         ON trainers.adduserid = user.userid LEFT JOIN branch
         ON trainers.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT trainers.* ,employeename ,branchName  FROM `trainers` LEFT JOIN user
         ON trainers.adduserid = user.userid LEFT JOIN branch
         ON trainers.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $date = date('Y-m-d');
         $trainerspays = R::count('trainerspays',"trainersid = ? and del < 2 and payenddate > '$date'",[$row['id']]);
         $trainerspaylast = R::findone('trainerspays',"trainersid = ? and del < 2 order by id desc",[$row['id']]);
        $sub_array = array();
        $sub_array[] = $row["id"];
         if ($row["trainersimage"] != "." && $row["trainersimage"] != "") {
           $sub_array[] = '<img src="../views/default/images/trainers/'. $row["trainersimage"] .'"  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["trainersname"];
        $sub_array[] = $row["trainersnumber"];
        $sub_array[] = $row["idnumber"];
        $sub_array[] = $row["trainersphone"];
        $sub_array[] = $row["parentsjob"];
        $sub_array[] = $row["parentsphone"];
        http://www.chicosportingclub.com/erp/controllers/clientController.php?do=edit&id=1
        $sub_array[] = '<a href="trainersControllerAjax.php?do=payed&studentid='. $row["id"] .'&deviceid=01" type="button" class="btn btn-default btn-lm ">حضور</a>';

        if ($trainerspays > 0 && $row["del"] < 2) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" type="button" class="btn btn-default btn-lm trainerspaysend"  >الكود</a>';
        }else if ($trainerspays > 0 && $row["del"] > 2) {
           $sub_array[] = ' موجود دفع ولكن الطالب محذوف   ';
        }else{
            $sub_array[] = 'لا يوجد';
        }
        $sub_array[] = $trainerspaylast->paystartdate;
        $sub_array[] = $trainerspaylast->payenddate;
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["payvalnew"];
        $sub_array[] = $row["branchName"];
        $sub_array[] = $row['employeename'];  
          $sub_array[] = '<a href="../views/default/images/trainersparcode/'. $row["id"] .'trainers.png" download> باركود </a>' ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="trainersController.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="trainersController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
         
        }else  if($row["del"] == 5){
              $sub_array[] = '<a href="trainersController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
              $sub_array[] = 'انتظار القبول ';
        }else{
          $sub_array[] = '<a href="trainersController.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('trainers',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        R::exec("UPDATE `client` SET `conditions`= 1 WHERE trainersid = '" . $id . "' ");
        R::exec("UPDATE `trainersaddsubjectdetails` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid WHERE trainersid = '" . $id . "' ");
        R::exec("UPDATE `trainersexamsval` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE trainersid = '" . $id . "' ");
        R::exec("UPDATE `trainerspays` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE trainersid = '" . $id . "' ");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}





?>