<?php
include("../public/impOpreation.php");
require_once('../library/http_call.php');
$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

if (empty($do)) { 
    $studentsetting = R::load('studentsetting',1);
    $user = R::getRow("SELECT user.* FROM `user` WHERE userid = ? ",[$_SESSION['userid']]);
    if($user['searchinonesave'] == 0){
         $saveusers = R::getAll("SELECT save.* FROM `save` WHERE conditions = 0 ");
         $smarty->assign("saveusers",$saveusers);
    }else{
         $saveuser = R::getRow("SELECT save.* FROM `save` WHERE saveid = ? ",[$_SESSION['saveid']]);
         $smarty->assign("saveuser",$saveuser);
    }
    $smarty->assign("saveid",$user['saveid']); 
    $smarty->assign("searchinonesave",$user['searchinonesave']);
   
    
    $lastday = date("Y-m-d", strtotime("last day of this month"));
    $smarty->assign("lastday",$lastday);
    
    $studentsettingpays = R::findAll('studentsettingpays','stopping = 1');
    $smarty->assign("studentsettingpays",$studentsettingpays);

    // $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);
    $smarty->assign('date', $date);
    $smarty->display("header.html"); 
    $smarty->display("studentspayview/add.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    $smarty->assign('usergroupid', $_SESSION['usergroupid']);
    include_once("../public/authentication.php");
    $studentsetting = R::load('studentsetting',1);
        $smarty->assign("showpayedit",explode(",",$studentsetting->showpayedit));
    $smarty->assign("showpaydel",explode(",",$studentsetting->showpaydel));
    $smarty->assign("studentsetting",$studentsetting);
      $show = filter_input(INPUT_GET, 'show');
      if($show == 2){
           $smarty->assign('show', 2);
      }
    $smarty->assign('date', $date);
    $smarty->display("header.html"); 
    $smarty->display("studentspayview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $detail = filter_input(INPUT_GET, 'detail');
    $studentspaydata = R::load('studentspays', $id);
    $studentsubjects = R::load('studentsubjects', $studentspaydata->studentsubjectid);
    $studentsubjectgroups = R::load('studentsubjectgroups', $studentspaydata->studentsubjectid);
    $studentspaydata->studentsubjects =$studentsubjects->subjectname.'/'.$studentsubjectgroups->subjectgroupname.'/'.$studentsubjectgroups->subjectgroupprice;
    $studentspaymentsystems = R::load('studentspaymentsystems', $studentspaydata->studentspaymentsystemid);
    $studentspaydata->studentspaymentsystems = $studentspaymentsystems->paymentname.'/'.$studentspaymentsystems->paymentprice;
    $students = R::load('students', $studentspaydata->studentid);
    $studentspaydata->students = $students->studentname.'/'.$students->studentphone;
    if($detail == 1){
      $studentspaydata->del = 2 ;
    }
  
  
    $studentsettingpays = R::findAll('studentsettingpays','stopping = 1');
    $smarty->assign("studentsettingpays",$studentsettingpays);
    $smarty->assign('studentspaydata', $studentspaydata);
    $studentsetting = R::load('studentsetting',1);
    $smarty->assign("studentsetting",$studentsetting);
    $smarty->assign('student', 1);
    $smarty->display("header.html"); 
    $smarty->display("studentspayview/edit.html");
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'showajax2') {
  showajax2();  
}else if ($do == 'getselectpayment') {
  getselectpayment();
}else if ($do == 'removerowstudentspays') {
  removerowstudentspays();
}else if ($do == 'studentspaysend') {
  studentspaysend();
}else if ($do == 'getpaystudent') {
  getpaystudent();
} elseif ($do == "printdata") {
    // include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $studentspaydata = R::load('studentspays', $id);
    $studentsubjects = R::load('studentsubjects', $studentspaydata->studentsubjectid);
    $smarty->assign('studentsubjects', $studentsubjects);
    $studentsubjectgroups = R::load('studentsubjectgroups', $studentspaydata->studentsubjectid);
    $smarty->assign('studentsubjectgroups', $studentsubjectgroups);
    $studentspaymentsystems = R::load('studentspaymentsystems', $studentspaydata->studentspaymentsystemid);
    $smarty->assign('studentspaymentsystems', $studentspaymentsystems);
    $students = R::load('students', $studentspaydata->studentid);
    $smarty->assign('students', $students);
    $smarty->assign('studentspaydata', $studentspaydata);
   
  
 
    $smarty->display("studentspayview/printdata.html");

}else if ($do == 'getstudentid') {
  getstudentid();
}else if ($do == 'getpaystudent2') {
  getpaystudent2();
}





function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $studentaddsubjectid = filter_input(INPUT_POST, 'studentaddsubjectid');
    $studentspaymentsystemid = filter_input(INPUT_POST, 'studentspaymentsystemid');
    $studentaddsubjectdetailid = filter_input(INPUT_POST, 'studentaddsubjectdetailid');
    $payenddate = filter_input(INPUT_POST, 'payenddate');
    $countmonths = filter_input(INPUT_POST, 'countmonths');
    $newprice = filter_input(INPUT_POST, 'newprice');
    $studentspayid = filter_input(INPUT_POST, 'studentspayid');
    $paytypered = filter_input(INPUT_POST, 'paytypered');
    $paykind = filter_input(INPUT_POST, 'paykind');
    $namepay = filter_input(INPUT_POST, 'namepay');
    $commentpay = filter_input(INPUT_POST, 'commentpay');
    $save_id = (int)filter_input(INPUT_POST, 'save_id');
    $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid);
    $studentaddsubjectdetails = R::load('studentaddsubjectdetails',$studentaddsubjectdetailid);
    $studentsubjectgroups = R::load('studentsubjectgroups',$studentaddsubjects->studentsubjectgroupid);
    $studentspaymentsystems = R::load('studentspaymentsystems',$studentspaymentsystemid);
    if($save_id > 0){
        $saveid =  $save_id;
    }else{
         $saveid =  $_SESSION['saveid'];
    }

    if ($studentaddsubjectid && !$studentspaymentsystemid && !$newprice && !$countmonths) {
        $studentsubjects = R::load('studentsubjects',$studentaddsubjects->studentsubjectid);
        $paymonths = 1;
        $paytype = 'دفع عن طريق  الماده';
        $payprice = $studentsubjectgroups->subjectgroupprice;
        $paytypenum = 1;
        $textpay = $studentsubjects->subjectname;

     }else if ($studentaddsubjectid && $studentspaymentsystemid && !$newprice && !$countmonths) {
        $paymonths = $studentspaymentsystems->paymentmonth;
        $paytype = "نظام دفع";
        $payprice = $studentspaymentsystems->paymentprice;
        $paytypenum = 2;
        $textpay = $studentspaymentsystems->paymentname;
     }else{
        if($countmonths){
            $studentsettingpays = R::load('studentsettingpays',$countmonths);
            $countmonths = $studentsettingpays->countmonths;
            $namepay = $studentsettingpays->name;
             $payapplied = $studentsettingpays->id;
        }
        $paymonths = $countmonths;
        $paytype = 'دفع  خاص';
        $payprice = $newprice;
        $paytypenum = 3;
        $textpay = $namepay;
     } 
      

    
    if (!$studentspayid) {
        $studentspays = R::dispense('studentspays');
        $studentspays->del = 0;
        $studentspays->addtoday = $today;          
        $studentspays->adduserid = $userid;
        $studentspays->deltoday = '';  
        $studentspays->deluserid = '';
    }else{
       $studentspays = R::load('studentspays',$studentspayid); 
       $studentspays->del = 1;
       $studentspays->updatetoday = $today;          
       $studentspays->updateuserid = $userid;
       $paystartdates = date('Y-m-d', strtotime("-".$studentspays->paymonths." month", strtotime($studentspays->paystartdate)));
       $payenddates = date('Y-m-d', strtotime("-".$studentspays->paymonths." month", strtotime($studentspays->payenddate)));
        R::exec("UPDATE `studentspays` SET `paystartdate`= '$paystartdates' , `payenddate`= '$payenddates' WHERE id = $studentspayid ");
    }
    $getstudentpaysubject = R::findOne('studentspays','studentid = ? and studentsubjectid = ? and del < 2 order by id desc',[$studentaddsubjectdetails->studentid,$studentaddsubjects->studentsubjectid]); 
    if ($getstudentpaysubject->id < 1 || $getstudentpaysubject->payenddate < date('Y-m-d')) {
        $paystartdate = date('Y-m-d');
    }else {
        $paystartdate = $getstudentpaysubject->payenddate;
    }
    
     if(!$countmonths){
        $countmonths = (int)abs((strtotime($paystartdate) - strtotime($payenddates))/(60*60*24*30));
        $paymonths = $countmonths;
             
    }
    
    $studentspays->studentaddsubjectid = $studentaddsubjectid;
    $studentspays->studentsubjectid = $studentaddsubjects->studentsubjectid;
    $studentspays->studentsubjectgroupid = $studentaddsubjects->studentsubjectgroupid;
    $studentspays->studentspaymentsystemid = $studentspaymentsystemid;
    $studentspays->studentaddsubjectdetailid = $studentaddsubjectdetailid;
    $studentspays->studentid = $studentaddsubjectdetails->studentid;
    $studentspays->paymonths  = $paymonths;
    $studentspays->paytype = $paytype;
    $studentspays->paytypenum = $paytypenum;
    $studentspays->payprice = $payprice;
    $studentspays->countmonths = $countmonths;
    $studentspays->newprice = $newprice;
    $studentspays->paystartdate  = $paystartdate;
    $studentspays->payenddate  = $payenddate;
    $studentspays->paytypered  = $paytypered;
    $studentspays->paykind  = $paykind;
    $studentspays->namepay  = $textpay;
    $studentspays->commentpay  = $commentpay;
    $studentspays->studentsettingpayid = $studentsettingpay->id;

    try {
        $studentspayid2 = R::store($studentspays);
        $students2 = R::load('students',$studentaddsubjectdetails->studentid);
        $students2->studentaddsubjectid = $studentaddsubjectid;
        $students2->studentsubjectid = $studentaddsubjects->studentsubjectid;
        $students2->studentsubjectgroupid = $studentaddsubjects->studentsubjectgroupid;
        $students2->studentspaymentsystemid = $studentspaymentsystemid;
        $students2->studentaddsubjectdetailid = $studentaddsubjectdetailid;
        $students2->paymonths  = $paymonths;
        $students2->paytype = $paytype;
        $students2->paytypenum = $paytypenum;
        $students2->payprice = $payprice;
        $students2->countmonths = $countmonths;
        $students2->newprice = $newprice;
        $students2->paystartdate  = $paystartdate;
        $students2->payenddate  = $payenddate;
        $students2->studentspayid  = $studentspayid2;
        $students2->saveid  = $payenddate;
        R::store($students2);
        $studentsubjects = R::load('studentsubjects',$studentaddsubjects->studentsubjectid);
        $incomeName = $students2->studentname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate;
        
        if (!$studentspayid) {
             $send_data = array(
            'clientid' => $students2->clientid,
            'saveid' => $saveid,
            'Costcenterid' => -1,
            'Value' => $payprice,
            'comment' => $paytype,
            'name' => $students2->studentname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate . 'تاريخ الميلاد  ' .$students2->datebirth,
            'parent' => $studentsubjects->incometypeid,
            );
            $client = R::getRow("SELECT * FROM `client` where clientid = ? ",[$students2->clientid]);
            $after = $payprice + $client->clientdebt;
            R::exec("INSERT INTO `clientdebtchange`(`clientid`, `clientdebtchangebefore`, `clientdebtchangeamount`, `clientdebtchangetype`,
           `clientdebtchangeafter`, `clientdebtchangedate`, `userid`, `tablename`) VALUES
            ($students2->clientid,'$client->clientdebt','$payprice',1,'$after','$today','$userid','clientPayedDeptController.php')");
            CURL_IT2($send_data, 'incomeController.php?do=add');
        }else{
             $income = R::getRow("SELECT * FROM `income` where clientid = ? order by incomeId desc",[$students2->clientid]);
             $send_data = array(
            'clientid' => $students2->clientid,
            'incomeId' => $income['incomeId'],
            'dailyentryid' => $income['dailyentryid'],
            'saveid' => $saveid,
            'Costcenterid' => -1,
            'Value' => $payprice,
            'comment' => $paytype,
            'name' => $students2->studentname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate . 'تاريخ الميلاد  ' .$students2->datebirth,
            'parent' => $studentsubjects->incometypeid,
            );
            CURL_IT2($send_data, 'incomeController.php?do=update');
        }        
        echo $studentspayid2;
    } catch (Exception $e) {
        echo 0 ;
    }
}





function showajax() {
    $columns = array('id', 'paymentname', 'studentname', 'studentphone', 'namepay'. 'datebirth','numbermonths','subjectname','subjectprice','subjectgroupname', 'paystartdate', 'payenddate', '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 = " ";
    if($data1 != ''){
        $searchQuery .= " and studentspays.studentid = ".$data1. " ";
    }

    if($data2 != ''){
       $searchQuery .= " and studentspays.studentsubjectid = ".$data2. " "; 
    }
    if($del == ''){
       $searchQuery .= " and studentspays.del < 2 "; 
    }

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( studentspays.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR studentspays.paymentname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.studentname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.studentphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.namepay LIKE "%'.$_POST["search"]["value"].'%"
                    OR datebirth LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.numbermonths LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.subjectname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.subjectgroupname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.payprice LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  studentspays.id DESC ";
    }
    
          $totals = R::count('studentspays','LEFT JOIN user ON studentspays.adduserid = user.userid WHERE 1 '.$searchQuery.' ');

    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }
    
     $rResult = R::getAll('SELECT studentspays.paytype, studentspays.paymonths, studentspays.payprice, studentspays.paystartdate, students.datebirth, studentspays.payenddate,
     studentspays.id as id, studentspays.addtoday as addtoday, studentspays.del as del, employeename, studentid, students.namepay
     ,studentsubjects.del as studentsubjectsdel ,studentsubjectgroups.del as studentsubjectgroupsdel,  
 subjectname, subjectgroupname, subjectgroupprice, studentname, studentphone  FROM `studentspays` 
 LEFT JOIN user ON studentspays.adduserid = user.userid 
  LEFT JOIN studentsubjects ON studentspays.studentsubjectid = studentsubjects.id 
 LEFT JOIN studentsubjectgroups ON studentspays.studentsubjectgroupid = studentsubjectgroups.id 
 LEFT JOIN students ON studentspays.studentid = students.id 
 WHERE studentsubjects.del < 2 and studentsubjectgroups.del < 2 and students.del < 2 '.$searchQuery.' '); 
 
 
    $studentsetting = R::load('studentsetting',1);
    $showpayedit = explode(",",$studentsetting->showpayedit);
    $showpaydel = explode(",",$studentsetting->showpaydel);

    
    
    $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['studentid']]);
        $countstudentspays = R::count('studentspays','studentid = '.$row["studentid"].' and id > '.$row["id"].' and del < 2'); 

        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["paytype"];
        $sub_array[] = $row["studentname"];
        $sub_array[] = $row["studentphone"];
        $sub_array[] = $row["namepay"];
        $sub_array[] = $row["datebirth"];
        $sub_array[] = $row["paymonths"];
        $sub_array[] = $row["subjectname"];
        $sub_array[] = $row["subjectgroupname"];
        $sub_array[] = $row["payprice"];
        if (in_array($_SESSION['usergroupid'], $showpayedit)) {
            
            $sub_array[] = '<input type="text" data-end="'.$row["id"] .'" id="datestart'.$row["id"].'" class="form-control changeenddate" value="'.$row["paystartdate"].'"/>
        <div  class="changeenddatee" style=" display: none;">'.$row["paystartdate"].'</div>';
        $sub_array[] ='<input type="text" data-end="'.$row["id"] .'" id="dateend'.$row["id"].'" class="form-control changeenddate" value="'.$row["payenddate"].'"/> 
        <div class="changeenddatee"  style=" display: none;">'.$row["payenddate"].'</div>';
        
        }else{
           $sub_array[] = $row["paystartdate"].'<div  class="changeenddatee" style=" display: none;" >'.$row["paystartdate"].'</div>';
        ;
        $sub_array[] =$row["payenddate"] .'<div class="changeenddatee"  style=" display: none;">'.$row["payenddate"].'</div>'; 
        }
        
        
        
        if ($studentspays > 0) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["studentid"] .'" type="button" class="btn btn-default btn-lm studentspaysend"  >     نسخ  الكود  </a>';
        }else{
           $sub_array[] = 'لا يوجد';
        }
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["employeename"];   
        // $sub_array[] = '<a href="studentsExamsController.php?do=edit&id='. $row["id"] .'&addstudent=1" type="button" class="btn btn-default btn-lm ">+</a>'; 
         if($row["del"] < 2 && $countstudentspays == 0){ 
            
            $sub_array[] = '<a href="studentsPay.php?do=printdata&id='. $row["id"] .'"   target="_blank"      type="button" class="btn btn-default btn-lm ">طباعه</a>';
            if (in_array($_SESSION['usergroupid'], $showpayedit)) {
                $sub_array[] = '<a href="studentsPay.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
            }
            if (in_array($_SESSION['usergroupid'], $showpaydel)) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'"   type="button" class="btn btn-default btn-lg deleteicon removerowstudentspays"  ></a>';
            }
        }else if($countstudentspays > 0){
                         $sub_array[] = '';

          $sub_array[] = '<a href="studentsPay.php?do=edit&id='. $row["id"] .'&detail=1" type="button" class="btn btn-default btn-lm">تفاصيل</a>';
           $sub_array[] = 'لا يوجد حذف ';

        }else{
                                     $sub_array[] = '';

          $sub_array[] = '<a href="studentsPay.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', 'paymentname', 'studentname', 'studentphone', 'namepay'. 'datebirth','numbermonths','subjectname','subjectprice','subjectgroupname', 'paystartdate', 'payenddate', '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 = " ";
    if($data1 != ''){
        $searchQuery .= " and studentspays.studentid = ".$data1. " ";
    }

    if($data2 != ''){
       $searchQuery .= " and studentspays.studentsubjectid = ".$data2. " "; 
    }

       $searchQuery .= " and studentspays.del = 5 "; 
    

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( studentspays.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR studentspays.paymentname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.studentname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.studentphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.namepay LIKE "%'.$_POST["search"]["value"].'%"
                    OR datebirth LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.numbermonths LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.subjectname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.subjectgroupname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.payprice LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentspays LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  studentspays.id DESC ";
    }
    
          $totals = R::count('studentspays','LEFT JOIN user ON studentspays.adduserid = user.userid WHERE 1 '.$searchQuery.' ');

    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }
    
     $rResult = R::getAll('SELECT studentspays.paytype, studentspays.paymonths, studentspays.payprice, studentspays.paystartdate, students.datebirth, studentspays.payenddate,
     studentspays.id as id, studentspays.addtoday as addtoday, studentspays.del as del, employeename, studentid, students.namepay
     ,studentsubjects.del as studentsubjectsdel ,studentsubjectgroups.del as studentsubjectgroupsdel,  
 subjectname, subjectgroupname, subjectgroupprice, studentname, studentphone  FROM `studentspays` 
 LEFT JOIN user ON studentspays.adduserid = user.userid 
  LEFT JOIN studentsubjects ON studentspays.studentsubjectid = studentsubjects.id 
 LEFT JOIN studentsubjectgroups ON studentspays.studentsubjectgroupid = studentsubjectgroups.id 
 LEFT JOIN students ON studentspays.studentid = students.id 
 WHERE studentsubjects.del < 2 and studentsubjectgroups.del < 2 and students.del < 2 '.$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['studentid']]);
        $countstudentspays = R::count('studentspays','studentid = '.$row["studentid"].' and id > '.$row["id"].' and del < 6'); 

        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["paytype"];
        $sub_array[] = $row["studentname"];
        $sub_array[] = $row["studentphone"];
        $sub_array[] = $row["namepay"];
        $sub_array[] = $row["datebirth"];
        $sub_array[] = $row["paymonths"];
        $sub_array[] = $row["subjectname"];
        $sub_array[] = $row["subjectgroupname"];
        $sub_array[] = $row["payprice"];
        $sub_array[] = '<input type="text" data-end="'.$row["id"] .'" id="datestart'.$row["id"].'" class="form-control changeenddate" value="'.$row["paystartdate"].'"/>
        <div  class="changeenddatee" style=" display: none;">'.$row["paystartdate"].'</div>';
        $sub_array[] ='<input type="text" data-end="'.$row["id"] .'" id="dateend'.$row["id"].'" class="form-control changeenddate" value="'.$row["payenddate"].'"/> 
        <div class="changeenddatee"  style=" display: none;">'.$row["payenddate"].'</div>';
        
        if ($studentspays > 0) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["studentid"] .'" type="button" class="btn btn-default btn-lm studentspaysend"  >     نسخ  الكود  </a>';
        }else{
           $sub_array[] = 'لا يوجد';
        }
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["employeename"];   
        // $sub_array[] = '<a href="studentsExamsController.php?do=edit&id='. $row["id"] .'&addstudent=1" type="button" class="btn btn-default btn-lm ">+</a>'; 
         if($row["del"] < 6 && $countstudentspays == 0){ 
         $sub_array[] = '<a href="studentsPay.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 removerowstudentspays"  ></a>';
        }else if($countstudentspays > 0){
          $sub_array[] = '<a href="studentsPay.php?do=edit&id='. $row["id"] .'&detail=1" type="button" class="btn btn-default btn-lm">تفاصيل</a>';
           $sub_array[] = 'لا يوجد حذف ';

        }else{
          $sub_array[] = '<a href="studentsPay.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 getselectpayment() {
    $searchterm = $_POST['searchTerms']; 
    $tablesearch = $_POST['tablesearch'];
    $table = $_POST['table'];
    $del = $_POST['del'];
    $filter = $_POST['filter'];
    $parentid = $_POST['parentid'];
    $parentcol = $_POST['parentcol'];

    $search = '';
    if ($parentid) {
    $search .= " and $table.del < 2"; 
    }
    $studentsaddubjects = R::load('studentsaddubjects',$parentid); 
    $search .= " and studentsubjectid = $studentsaddubjects->studentsubjectid "; 
    

    if ($filter) {
       $search .= $filter;
    }

    $row_array = array();
    $return_arr = array();

     $allData = R::getAll("SELECT $table.id,CONCAT($tablesearch) as name
        FROM $table 
        WHERE  CONCAT($tablesearch) LIKE '%" . $searchterm . "%' $search limit 50");
    foreach ($allData as $data) {
        $row_array['id'] = $data['id'];
        $row_array['text'] = $data['name'];
        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}


function removerowstudentspays() {
    $today = date("Y-m-d H:i:s");
    $date = date("Y-m-d");
    $id = filter_input(INPUT_POST, 'id');
    $studentspays = R::load('studentspays', $id);
    $studentspays->del = 2;
    $studentspays->deltoday = $today;          
    $studentspays->deluserid = $_SESSION['userid'];
    try {
        R::store($studentspays);
        $students = R::load('students',$studentspays->studentid);
         $income = R::getRow("SELECT income.* FROM `income` WHERE clientid = $students->clientid order by incomeId desc");
         $send_data = array(
        'incomeId' => $income['incomeId'],
        );
        CURL_IT2($send_data, 'incomeController.php?do=deletepost');
        $students = R::load('students',$studentspays->studentid);
        $studentspaysold = R::findOne('studentspays','studentid = ? and del < 2 order by id desc',[$students->id]); 
        $students->startdate = $studentspaysold->paystartdate;
        $students->enddate = $studentspaysold->payenddate;
        $students->paymonths  = $studentspaysold->paymonths;
        $students->paytype = $studentspaysold->paytype;
        $students->payprice = $studentspaysold->payprice;
        $students->studentspayid = $studentspaysold->id;
        R::store($students);
        echo 1;
    } catch (Exception $e) {
        echo 0;
    }
} 


function studentspaysend() {
    
    $studentid = ($_POST['studentid'] > 0) ? $_POST['studentid'] : 0;;
    $date = date("Y-m-d");
     $studentspays = R::getAll("SELECT MAX(id) AS id FROM `studentspays` where 
     studentid = $studentid and studentspays.del < 2 and payenddate > '$date' 
     group by studentspays.studentsubjectid  desc limit 6"); 
     $text ='00'.$studentid.'?';
     $i = 1;
     foreach($studentspays as $studentspay){
         $studentspaydata = R::load('studentspays',$studentspay['id']);
         $studentsubjects = R::load('studentsubjects',$studentspaydata->studentsubjectid);
         if ($i < 7){
          $text .= $studentsubjects->deviceid.','.date('Ym', strtotime($studentspaydata->payenddate)).'?';
         }
          $i++;
        
        
     }
     $countstudentspayval = count($studentspays);
     if ($countstudentspayval < 6) {
        for ($i = $countstudentspayval; $i <= 5; $i++) {
            $text .= '00,000000?';
        } 
       
    }
    // $send_data = array();
    // $send_data['text'] = $text;
    // $response_data = HTTPRequester::HTTPPost('http://shop.gt4host.com/calendar/full/api/studentsdata', $send_data);
    // $receive_data = json_decode($response_data);
    echo trim($text);

}


function getpaystudent() {
    
    $studentid = $_POST['studentid'];
    $studentaddsubjectid = $_POST['studentaddsubjectid'];
    $paykind = $_POST['paykind'];
    $countmonth = $_POST['countmonth'];
    $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid);
    $getstudentpaysubject = R::findOne('studentspays','studentid = ? and studentsubjectgroupid = ? and del < 2 order by id desc',[$studentid,$studentaddsubjects->studentsubjectgroupid]); 
    if ($getstudentpaysubject->id  == '') {
        $getstudentpaysubject->payenddate = date('Y-m-d');
    }
    // if ($paykind == 1) {
    //     $text = date('Y-m-d', strtotime("+1 month", strtotime($getstudentpaysubject->payenddate))); 
    // }else if ($paykind == 2) {
    //     $studentspaymentsystems = R::load('studentspaymentsystems',$countmonth);
    //     $text = date('Y-m-d', strtotime("+".$studentspaymentsystems->paymentmonth." month",  strtotime($getstudentpaysubject->payenddate)));
    // }else if($paykind == 3){
    //     $text = date('Y-m-d', strtotime("+".$countmonth." month",  strtotime($getstudentpaysubject->payenddate)));
    // }else{
    //     $text = 4;

    // }
    
    $studentsdata = R::load('students',$studentid);
    if($getstudentpaysubject->payenddate < date('Y-m-d')){
        if(!$countmonth){
        $countmonth = $getstudentpaysubject->countmonths;
        }
       $getstudentpaysubject->payenddate = date('Y-m-d', strtotime(" +$countmonth months"));
    }
    echo json_encode(array('datenew' =>  $getstudentpaysubject->payenddate,'namepay' => $studentsdata->namepay,'commentpay' => $studentsdata->commentpay, 'countmonth'=> $countmonth));

}


function getpaystudent2() {
    $payenddate = $_POST['payenddate'];
    $countmonth = $_POST['countmonths'];
    $text = date('Y-m-d', strtotime("+".$countmonth." month",  strtotime($payenddate)));
     echo trim($text);

}


function getstudentid() {
    $studentspayid = $_POST['studentspayid'];
    $studentspays = R::load('studentspays',$studentspayid);
    echo $studentspays->studentid;

}


function CURL_IT2($data_arr, $url) {
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);

    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    curl_close($ch);
    return $response;
}


?>