<?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)) {  
    // include "../library/phpqrcode/qrlib.php";    
    // $studentdata = R::findAll('students');
    // foreach($studentdata as $student){
    //     $studentid = $student->id;
    //     $PNG_TEMP_DIR = "../views/default/images/studentsparcode/";
    //     if (!file_exists($PNG_TEMP_DIR))
    //     mkdir($PNG_TEMP_DIR);
    //     $filename = $PNG_TEMP_DIR.$studentid.'student.png';
    //     $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/studentControllerAjax.php?do=detailstudent&studentid=' . $studentid;
    //     QRcode::png($url, $filename, 'L', 9, 2);     
    // }
    
    
    
    $studentsetting = R::load('studentsetting',1);
    $studentaddsubjects = R::load('studentaddsubjects',$studentsetting->studentaddsubjectid);
    $studentsubjects = R::load('studentsubjects',$studentaddsubjects->studentsubjectid);
    $studentsubjectgroups = R::load('studentsubjectgroups',$studentaddsubjects->studentsubjectgroupid);
    $subjectgroups =$studentsubjects->subjectname.'/'.$studentsubjectgroups->subjectgroupname.'/'.$studentsubjectgroups->subjectgroupprice;
    $smarty->assign("subjectgroups",$subjectgroups);
    $smarty->assign("studentaddsubjects",$studentaddsubjects);
    $smarty->assign("studentsetting",$studentsetting);

    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    $smarty->display("header.html");
    $smarty->display("studentview/add.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $studentsetting = R::load('studentsetting',1);
    $smarty->assign("studentsetting",$studentsetting);
      $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("studentview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
    
 
    
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $studentdata = R::load('students', $id);
    $smarty->assign('studentdata', $studentdata);
    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    $smarty->display("header.html");
    $smarty->display("studentview/edit.html");
    $smarty->assign("student", 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'];
    $studentname = filter_input(INPUT_POST, 'studentname');
    $studentnumber = filter_input(INPUT_POST, 'studentnumber');
    $idnumber = filter_input(INPUT_POST, 'idnumber');
    $studentphone = filter_input(INPUT_POST, 'studentphone');
    $parentsname = filter_input(INPUT_POST, 'parentsname');
    $parentsphone = filter_input(INPUT_POST, 'parentsphone');
    $parentsjob = filter_input(INPUT_POST, 'parentsjob');
    $parentsname2 = filter_input($studentaddsubjectidINPUT_POST, 'parentsname2');
    $parentsphone2 = filter_input(INPUT_POST, 'parentsphone2');
    $parentsjob2 = filter_input(INPUT_POST, 'parentsjob2');
    
    
    $studentaddress = filter_input(INPUT_POST, 'studentaddress');
    $studentnote = filter_input(INPUT_POST, 'studentnote');
    $branchid = filter_input(INPUT_POST, 'branchid');
    $datebirth = filter_input(INPUT_POST, 'datebirth');
    $namepay = filter_input(INPUT_POST, 'namepay');
    $commentpay = filter_input(INPUT_POST, 'commentpay');
    $studentaddsubjectid = filter_input(INPUT_POST, 'studentaddsubjectid');
    $studentid = filter_input(INPUT_POST, 'studentid');
    $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 (!$studentid) {;
        $students = R::dispense('students');
        $stopping = 0;
        $students->del = 0;
        $students->addtoday = $today;          
        $students->adduserid = $userid;
        $students->deltoday = '';      
        $students->deluserid = '';
        $handle = new upload($_FILES['studentimage']);
        $studentimage = uploadImages($handle, "../views/default/images/students", 300, 300);
    }else{
        $students = R::load('students',$studentid);
        if( $students->del != 5){
              R::exec("UPDATE `client` SET `clientname`= '$studentname',`clientaddress`= '$studentaddress',`clientphone`= '$studentphone',`branchId`= $branchid WHERE clientid = $clientid");
        
        }
      
        $students->del = 1;
        $students->updatetoday = $today;          
        $students->updateuserid = $userid; 
        $handle = new upload($_FILES['studentimage']);
        $studentimage = updateImages($handle, "oldstudentimage", "../views/default/images/students", 300, 300);
        unlink("../views/default/images/students" . $students->studentimage);
    }
    $students->nickname  = $nickname;
    $students->payvalnew  = $payvalnew;
    $students->gender  = $gender;
    $students->nationality  = $nationality;
    $students->placebirth  = $placebirth;
    $students->schoolname  = $schoolname;
    $students->classroom  = $classroom;
    $students->playerfavoriteclub  = $playerfavoriteclub;
    $students->playerfavoriteplayer  = $playerfavoriteplayer;
    $students->playedsoccer  = $playedsoccer;
    $students->clubacademy  = $clubacademy;
    $students->studentname  = $studentname;
    $students->studentnumber = $idnumber;
    $students->idnumber = $idnumber;
    $students->studentphone = $studentphone;
    $students->parentsname = $parentsname;
    $students->parentsphone = $parentsphone;
    $students->parentsjob = $parentsjob;
    $students->parentsname2 = $parentsname2;
    $students->parentsphone2 = $parentsphone2;
    $students->parentsjob2 = $parentsjob2;
    $students->studentaddress = $studentaddress;
    $students->clientid = $clientid; 
    $students->branchid = $branchid; 
    $students->studentimage = $studentimage;
    $students->studentnote = $studentnote;
    $students->datebirth = $datebirth;
    $students->namepay = $namepay;
    $students->commentpay = $commentpay;
    $students->stopping = $stopping;
    $students->stopcomment = $stopcomment;
    try {
         $studentid = R::store($students);
            if (!$clientid) {
             R::exec("INSERT INTO `client`(`clientname`, `clientaddress`, `clientphone`, `clientdate`, `userid`, `branchId`, `clientStoreIds`, `typeclientid`, `priceTypeId`, `studentid`) VALUES 
             ('$studentname', '$studentaddress', '$studentphone','$date', $userid, $branchid, '-10', ',-20,', -1, $studentid)");
             $client = R::getCell("SELECT clientid FROM `client` WHERE studentid =  $studentid");
             $students = R::load('students',$studentid);
             $students->clientid = $client; 
             $studentid = R::store($students);
            }else{
               R::exec("UPDATE `client` SET `clientname`='$studentname',`clientaddress`='$studentaddress',`conditions`= 0,`clientphone`='$studentphone',`branchId`= $branchid 
               WHERE clientid = $clientid");
            }
          if($studentaddsubjectid){
                $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid); 
                $studentaddsubjects->del = 1;
                $studentaddsubjects->updatetoday = $today;          
                $studentaddsubjects->updateuserid = $userid;
                $studentaddsubjects->studentid = $studentaddsubjects->studentid.','.$studentid;
                R::store($studentaddsubjects);
                // $studentdata = R::load('students',$Explode[$i]); 
                $studentaddsubjectdetails = R::dispense('studentaddsubjectdetails');
                $studentaddsubjectdetails->studentid  = $studentid;
                $studentaddsubjectdetails->studentsubjectid  = $studentaddsubjects->studentsubjectid;
                $studentaddsubjectdetails->studentsubjectgroupid = $studentaddsubjects->studentsubjectgroupid;
                $studentaddsubjectdetails->del = 0;
                $studentaddsubjectdetails->studentaddsubjectid = $studentaddsubjectid;
                R::store($studentaddsubjectdetails); 
          }
           
            if ($students->del == 0 || $agrees == 5) {
                $PNG_TEMP_DIR = "../views/default/images/studentsparcode/";
                $filename = $PNG_TEMP_DIR.$studentid.'student.png';
                $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/studentControllerAjax.php?do=detailstudent&studentid=' . $studentid;
                QRcode::png($url, $filename, 'L', 9, 2);    
            }
    
   
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function showajax() {
    $columns = array('id', 'id', 'studentname', 'studentnumber','idnumber', 'studentphone', 'parentsphone', 'studentspayid', '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 students.id = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and students.del < 2 "; 
    }

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( students.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR students.studentnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.idnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.studentphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.parentsphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.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  students.id DESC ";
    }
    
     $totals = R::count('students','LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.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 students.* ,employeename ,branchName  FROM `students` LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.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');
         $studentspays = R::count('studentspays',"studentid = ? and del < 2 and payenddate > '$date'",[$row['id']]);
         $studentpaylast = R::findone('studentspays',"studentid = ? and del < 2 order by id desc",[$row['id']]);
        $sub_array = array();
        $sub_array[] = $row["id"];
         if ($row["studentimage"] != "." && $row["studentimage"] != "") {
           $sub_array[] = '<img src="../views/default/images/students/'. $row["studentimage"] .'"  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["studentname"];
        $sub_array[] = $row["studentnumber"];
        $sub_array[] = $row["idnumber"];
        $sub_array[] = $row["studentphone"];
        $sub_array[] = $row["parentsjob"];
        $sub_array[] = $row["parentsphone"];
        //http://www.chicosportingclub.com/erp/controllers/clientController.php?do=edit&id=1
        $sub_array[] = '<a href="studentControllerAjax.php?do=payed&studentid='. $row["id"] .'&deviceid=01" type="button" class="btn btn-default btn-lm ">حضور</a>';

        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[] = $studentpaylast->paystartdate;
        $sub_array[] = $studentpaylast->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/studentsparcode/'. $row["id"] .'student.png" download> باركود </a>' ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="studentController.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  if($row["del"] == 5){
              $sub_array[] = '<a href="studentController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
              $sub_array[] = 'انتظار القبول ';
        }else{
          $sub_array[] = '<a href="studentController.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', 'studentname', 'studentnumber','idnumber', 'studentphone', 'parentsphone', 'studentspayid', '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 students.id = ".$data1. " ";
    }
   
       $searchQuery .= " and students.del = 5 "; 
    

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( students.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR students.studentnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.idnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.studentphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.parentsphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.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  students.id DESC ";
    }
    
     $totals = R::count('students','LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.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 students.* ,employeename ,branchName  FROM `students` LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.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');
         $studentspays = R::count('studentspays',"studentid = ? and del < 2 and payenddate > '$date'",[$row['id']]);
         $studentpaylast = R::findone('studentspays',"studentid = ? and del < 2 order by id desc",[$row['id']]);
        $sub_array = array();
        $sub_array[] = $row["id"];
         if ($row["studentimage"] != "." && $row["studentimage"] != "") {
           $sub_array[] = '<img src="../views/default/images/students/'. $row["studentimage"] .'"  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["studentname"];
        $sub_array[] = $row["studentnumber"];
        $sub_array[] = $row["idnumber"];
        $sub_array[] = $row["studentphone"];
        $sub_array[] = $row["parentsjob"];
        $sub_array[] = $row["parentsphone"];
        http://www.chicosportingclub.com/erp/controllers/clientController.php?do=edit&id=1
        $sub_array[] = '<a href="studentControllerAjax.php?do=payed&studentid='. $row["id"] .'&deviceid=01" type="button" class="btn btn-default btn-lm ">حضور</a>';

        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[] = $studentpaylast->paystartdate;
        $sub_array[] = $studentpaylast->payenddate;
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["payvalnew"];
        $sub_array[] = $row["branchName"];
        $sub_array[] = $row['employeename'];  
          $sub_array[] = '<a href="../views/default/images/studentsparcode/'. $row["id"] .'student.png" download> باركود </a>' ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="studentController.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  if($row["del"] == 5){
              $sub_array[] = '<a href="studentController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
              $sub_array[] = 'انتظار القبول ';
        }else{
          $sub_array[] = '<a href="studentController.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 ;
    }
}





?>