<?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)) { 
     $trainerssetting = R::load('trainerssetting',1);
    $smarty->assign("trainerssetting",$trainerssetting);
    $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);
    
    $trainerspaymentsystems = R::findAll('trainerspaymentsystems','del < 2');
    $smarty->assign("trainerspaymentsystems",$trainerspaymentsystems);

    
    $smarty->assign('date', $date);
    $smarty->display("header.html"); 
    $smarty->display("trainerssubscriptionview/add.html");
    $smarty->assign("trainers", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    $smarty->assign('usergroupid', $_SESSION['usergroupid']);
    include_once("../public/authentication.php");
    $trainerssetting = R::load('trainerssetting',1);
    
    
        $smarty->assign("showpayedit",explode(",",$trainerssetting->showpayedit));
    $smarty->assign("showpaydel",explode(",",$trainerssetting->showpaydel));
    $smarty->assign("trainerssetting",$trainerssetting);
      $show = filter_input(INPUT_GET, 'show');
      if($show == 2){
           $smarty->assign('show', 2);
      }
    $smarty->assign('date', $date);
    $smarty->display("header.html"); 
    $smarty->display("trainerssubscriptionview/show.html");
    $smarty->assign("trainers", 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');
    $trainerspaydata = R::load('trainerspays', $id);
   
   
      
    $trainerspaymentsystems = R::findAll('trainerspaymentsystems','del < 2');
    $smarty->assign("trainerspaymentsystems",$trainerspaymentsystems);

    
   
    $trainers = R::load('trainers', $trainerspaydata->trainersid);
    $trainerspaydata->trainers = $trainers->trainersname.'/'.$trainers->trainersphone;
    if($detail == 1){
      $trainerspaydata->del = 2 ;
    }
    $smarty->assign('trainerspaydata', $trainerspaydata);
    $trainerssetting = R::load('trainerssetting',1);
    $smarty->assign("trainerssetting",$trainerssetting);
    $smarty->assign('trainers', 1);
    $smarty->display("header.html"); 
    $smarty->display("trainerssubscriptionview/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('trainerspays', $id);
    $studentspaymentsystems = R::load('trainerspaymentsystems', $studentspaydata->trainerspaymentsystemid);
    $smarty->assign('studentspaymentsystems', $studentspaymentsystems);
    $students = R::load('trainers', $studentspaydata->trainersid);
    $smarty->assign('students', $students);
    $smarty->assign('studentspaydata', $studentspaydata);
   
  
 
    $smarty->display("trainerssubscriptionview/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'];
    $trainersid = filter_input(INPUT_POST, 'trainersid');
    $trainerspaymentsystemsid = filter_input(INPUT_POST, 'trainerspaymentsystemsid');
    $payenddate = filter_input(INPUT_POST, 'payenddate');
    $newprice = filter_input(INPUT_POST, 'newprice');
    $trainerspayid = filter_input(INPUT_POST, 'trainerspayid');
    $commentpay = filter_input(INPUT_POST, 'commentpay');
    $save_id = (int)filter_input(INPUT_POST, 'save_id');
    
    $trainers = R::load('trainers',$trainersid);
    $trainerspaymentsystems = R::load('trainerspaymentsystems',$trainerspaymentsystemsid);
    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 = $trainerspaymentsystems->paymentprice;
        $paytypenum = 2;
        $textpay = $trainerspaymentsystems->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 (!$trainerspayid) {
        $studentspays = R::dispense('trainerspays');
        $studentspays->del = 0;
        $studentspays->addtoday = $today;          
        $studentspays->adduserid = $userid;
        $studentspays->deltoday = '';  
        $studentspays->deluserid = '';
        $paystartdate = date('Y-m-d');
        $studentspays->usenumbercatarrh = 0;
        $studentspays->endtrainerspays = 0;
        $studentspays->numbercatarrh = $trainerspaymentsystems->numbercatarrh;
        $numbercatarrh = $trainers->numbercatarrh + $trainerspaymentsystems->numbercatarrh;
    }else{
       
       $studentspays = R::load('trainerspays',$trainerspayid); 
       $trainerspaymentsystemsold = R::load('trainerspaymentsystems',$studentspays->trainerspaymentsystemsid);
       $paystartdate = $trainerspaysolde->payenddate;
       $studentspays->del = 1;
       $studentspays->updatetoday = $today;          
       $studentspays->updateuserid = $userid;
       $studentspays->numbercatarrh =  ($studentspays->numbercatarrh + $trainerspaymentsystems->numbercatarrh) - $trainerspaymentsystemsold->numbercatarrh;
       $numbercatarrh = ($trainers->unumbercatarrh + $trainerspaymentsystems->numbercatarrh) - $trainerspaymentsystemsold->numbercatarrh;
    //   $paystartdates = date('Y-m-d', strtotime("-".$studentspays->paymonths." month", strtotime($studentspays->paystartdate)));
    //   $payenddates = date('Y-m-d', strtotime("-".$studentspays->paymonths." month", strtotime($studentspays->payenddate)));
    }
    
    // $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->trainerspaymentsystemsid = $trainerspaymentsystemsid;
    $studentspays->trainersid = $trainersid;
    $studentspays->paymonths  = $paymonths;
    $studentspays->paytype = $paytype;
    $studentspays->paytypenum = $paytypenum;
    $studentspays->payprice = $payprice;
    $studentspays->newprice = $newprice;
    $studentspays->paystartdate  = $paystartdate;
    $studentspays->payenddate  = $payenddate;
    $studentspays->paykind  = $paykind;
    $studentspays->namepay  = $textpay;
    $studentspays->commentpay  = $commentpay;

    try {
        $trainerspayid2 = R::store($studentspays);
        
        $students2 = R::load('trainers',$trainersid);
        $students2->trainerspaymentsystemsid = $trainerspaymentsystemsid;
        $students2->paytype = $paytype;
        $students2->paytypenum = $paytypenum;
        $students2->payprice = $payprice;
        $students2->unumbercatarrh = $numbercatarrh;
        $students2->newprice = $newprice;
        $students2->paystartdate  = $paystartdate;
        $students2->payenddate  = $payenddate;
        $students2->saveid  = $payenddate;
        $students2->trainerspayid  = $trainerspayid->id;
        R::store($students2);
        $incomeName = $students2->trainersname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate;
        
        if (!$trainerspayid) {
             $send_data = array(
            'clientid' => $students2->clientid,
            'saveid' => $saveid,
            'Costcenterid' => -1,
            'Value' => $payprice,
            'comment' => $paytype,
            'name' => $students2->trainersname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate,
            'parent' => 4,
            );
            $client = R::getRow("SELECT * FROM `client` where trainersid = ? ",[$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->trainersname. 'دفع  ' . $textpay . 'تاريخ الانتهاء  ' .$payenddate,
            'parent' => 4,
            );
            CURL_IT2($send_data, 'incomeController.php?do=update');
        }        
        echo $trainerspayid2;
    } catch (Exception $e) {
        echo 0 ;
    }
}





function showajax() {
    $columns = array('id', 'paymentname', 'trainersname', 'trainersphone', 'namepay','payprice', '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 trainerspays.trainersid = ".$data1. " ";
    }

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

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( trainerspays.id LIKE "%'.$_POST["search"]["value"].'%" 
                    // OR studentspays.paymentname LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainersname LIKE "%'.$_POST["search"]["value"].'%"
                    OR trainersphone 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  trainerspays.id DESC ";
    }
    
          $totals = R::count('trainerspays','LEFT JOIN user ON trainerspays.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 trainerspays.paytype, trainerspays.paymonths, trainerspays.payprice, trainerspays.paystartdate,  trainerspays.payenddate,
     trainerspays.id as id, trainerspays.addtoday as addtoday, trainerspays.del as del, employeename, trainersid, trainersname, trainersphone  FROM `trainerspays` 
 LEFT JOIN user ON trainerspays.adduserid = user.userid 
 LEFT JOIN trainers ON trainerspays.trainersid = trainers.id 
 WHERE  trainers.del < 2 '.$searchQuery.' '); 

    $studentsetting = R::load('trainerssetting',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('trainerspays',"trainersid = ? and del < 2 and  payenddate >= '$date'",[$row['trainersid']]);
        $countstudentspays = R::count('trainerspays','trainersid = '.$row["trainersid"].' and id > '.$row["id"].' and del < 2'); 

        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["paytype"];
        $sub_array[] = $row["trainersname"];
        $sub_array[] = $row["trainersphone"];
        // $sub_array[] = $row["namepay"];
        // $sub_array[] = $row["paymonths"];
        $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["trainersid"] .'" 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="trainersSubscription.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="trainersSubscription.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="trainersSubscription.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="trainersSubscription.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('trainerspays', $id);
    $studentspays->del = 2;
    $studentspays->deltoday = $today;          
    $studentspays->deluserid = $_SESSION['userid'];
    try {
        R::store($studentspays);
        $students = R::load('trainers',$studentspays->trainersid);
         $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');
        $studentspaysold = R::findOne('trainerspays','trainersid = ? and del < 2 order by id desc',[$students->id]); 
        $students->startdate = $studentspaysold->paystartdate;
        $students->enddate = $studentspaysold->payenddate;
        $students->numbercatarrh  = $studentspaysold->numbercatarrh;
        $students->paytype = $studentspaysold->paytype;
        $students->payprice = $studentspaysold->payprice;
        $students->trainerspayid = $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 `trainerspays` where 
     trainersid = $studentid and trainerspays.del < 2 and payenddate > '$date'  limit 6"); 
     $text ='00'.$studentid.'?';
     $i = 1;
     foreach($studentspays as $studentspay){
         $studentspaydata = R::load('trainerspays',$studentspay['id']);
         if ($i < 7){
          $text .= '01,'.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() {
    
    $trainersid = $_POST['trainersid'];
    $trainerspaymentsystemsid = $_POST['trainerspaymentsystemsid'];
    
    
    
    // $paykind = $_POST['paykind'];
    // $countmonth = $_POST['countmonth'];
    $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid);
    $gettrainerspays = R::findOne('trainerspays','trainersid = ? and del < 2 order by id desc',[$trainersid]); 
    if (!$gettrainerspays->id) {
        $gettrainerspays->payenddate = date('Y-m-d', strtotime(" +1 months"));
    }else{
       $gettrainerspays->payenddate = date('Y-m-d', strtotime("+1 months", strtotime($gettrainerspays->payenddate)));

    }
    $trainersdata = R::load('trainers',$trainersid);
    if($gettrainerspays->payenddate < date('Y-m-d')){
       $gettrainerspays->payenddate = date('Y-m-d', strtotime(" +1 months"));
    }
        $trainerspaymentsystems = R::load('trainerspaymentsystems',$trainerspaymentsystemsid);

    echo json_encode(array('datenew' =>  $gettrainerspays->payenddate, 'numbercatarrh' => $trainerspaymentsystems->numbercatarrh,'newprice' => $trainerspaymentsystems->paymentprice));

}


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;
}


?>