<?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");
$times = date("H:i:s");
$time1hour = date('H:i:s', strtotime('+1 hour'));
$day = date('l');
if (empty($do)) {
    $smarty->assign("day", $day);
    $smarty->display("header.html");
    $smarty->display("studentabsenceview/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);
    $smarty->assign('date', $date);
    $smarty->assign('times', $times);
    $studentaddsubjects = R::getAll("SELECT *,studentaddsubjects.id as studentaddsubjectid FROM studentaddsubjects 
    left JOIN studentsubjectgroupdays ON studentaddsubjects.studentsubjectid = studentsubjectgroupdays.studentsubjectid 
     left JOIN studentsubjectgroups ON studentsubjectgroupdays.studentsubjectgroupid = studentsubjectgroups.id 
      left JOIN studentsubjects ON studentsubjectgroupdays.studentsubjectid = studentsubjects.id 
    WHERE studentaddsubjects.del < 2 and studentsubjectgroupdays.del < 2 and dayen = '$day' 
    group by studentsubjectgroupdays.studentsubjectgroupid");
    $smarty->assign("studentaddsubjects", $studentaddsubjects);
    $smarty->display("header.html");

    $smarty->display("studentabsenceview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $smarty->assign('date', $date);
    $deviceid = filter_input(INPUT_GET, 'id');
    $handle = file_get_contents($deviceid.'/'.date('Y-m-d').".txt");
    $i = 0;    
    if ($handle) {
        $lists = explode("\n",$handle);
      foreach ($lists as $data) {
             $data = explode('?', $data);
             $studentabsencesadd = R::count('studentabsences',"uniqid = ? and deviceid = ? and todaysend = '$date' ",[$data[0], $data[5]]);
             if ($studentabsencesadd == 0 && $data[0]) {
                $studentsubjects = R::findOne('studentsubjects',"deviceid = ?",[$data[5]]);
                $studentaddsubjectdetails = R::findOne('studentaddsubjectdetails','studentid = ? and studentsubjectid = ? and del < 2  order by id desc',[$data[1], $studentsubjects->id]); 
                $studentabsences = R::dispense('studentabsences');
                $studentabsences->onlys = $studentabsencesadd;
                $studentabsences->del = 0;
                $studentabsences->addtoday = $today;          
                $studentabsences->adduserid = $_SESSION['userid'];
                $studentabsences->uniqid = $data[0];
                $studentabsences->studentid = $data[1];
                $studentabsences->todaysend = $data[2];
                $studentabsences->timesend = $data[3];
                $studentabsences->type = $data[4];
                $studentabsences->deviceid = $data[5];
                $studentabsences->status = $data[6];
                $studentabsences->studentsubjectid = $studentaddsubjectdetails->studentsubjectid;
                $studentabsences->studentsubjectgroupid = $studentaddsubjectdetails->studentsubjectgroupid;
                $studentabsences->studentaddsubjectid = $studentaddsubjectdetails->studentaddsubjectid;
                $studentabsences->studentaddsubjectdetailid = $studentaddsubjectdetails->id;
                $studentabsences->ipaddrees = $id;
                R::store($studentabsences);
            }
           

        }

        fclose($handle);
    } 
    $studentabsencesall = R::findAll('studentabsences','todaysend = ? ',[$date]);
    $smarty->assign('studentabsencesall', $studentabsencesall);
    $smarty->display("header.html");
    $smarty->display("studentabsenceview/showdata.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "sendmassage") {
    include_once("../public/authentication.php");
    $date = date("Y-m-d");
    $times = date("H:i:s");
    $today = date("Y-m-d H:i:s");
    $studentsubjectgroupid = filter_input(INPUT_POST, 'studentsubjectgroupid');
    try {
        $studentaddsubjectdetails = R::findAll('studentaddsubjectdetails',' studentsubjectgroupid = ? and del < 2 ',[$studentsubjectgroupid]); 
         foreach($studentaddsubjectdetails as $studentaddsubjectdetail){
            $studentsubjects = R::load('studentsubjects',$studentaddsubjectdetail->studentsubjectid);
             $studentabsencesc = R::count('studentabsences', " studentid = ? and deviceid = ? and todaysend = '$date' and del < 2",[$studentaddsubjectdetail->studentid, $studentsubjects->deviceid]);        
                if ($studentabsencesc == 0) {
                    $studentabsences = R::dispense('studentabsences');
                    $studentabsences->del = 0;
                    $studentabsences->onlys = 1;
                    $studentabsences->arrivedtime = '0';
                    $studentabsences->addtoday = $today;          
                    $studentabsences->adduserid = $_SESSION['userid'];
                    $studentabsences->studentid = $studentaddsubjectdetail->studentid;
                    $studentabsences->todaysend = $date;
                    $studentabsences->deviceid = $studentsubjects->deviceid;
                    $studentabsences->timesend = $times;
                    $studentabsences->studentsubjectid = $studentaddsubjectdetail->studentsubjectid;
                    $studentabsences->studentsubjectgroupid = $studentaddsubjectdetail->studentsubjectgroupid;
                    $studentabsences->studentaddsubjectid = $studentaddsubjectdetail->studentaddsubjectid;
                    $studentabsences->studentaddsubjectdetailid = $studentaddsubjectdetail->id;
                    R::store($studentabsences);
                }
         }
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'receivedata') {
  receivedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removecontroller') {
  removecontroller();
}else if ($do == 'getstudentabsence') {
  getstudentabsence();
}else if ($do == 'sendmassagemanual') {
  sendmassagemanual();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date("Y-m-d");
    $times = date("H:i:s");
    $day = date('l');
    $userid = $_SESSION['userid'];
    $studentaddsubjectid = filter_input(INPUT_POST, 'studentaddsubjectid');
    $studentp =$_POST['studentid'];
    $Explode = explode(',', $_POST['studentid']);
    try {
        $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid);
        $studentsubjects = R::load('studentsubjects',$studentaddsubjects->studentsubjectid);
        for ($i = 0; $i < count($Explode); $i++) { 
            $studentabsencesc = R::count('studentabsences', " studentid = ? and deviceid = ? and todaysend = '$date' and del < 2",[$Explode[$i], $studentsubjects->deviceid]);
            if ( $studentabsencesc == 0) {
                $studentaddsubjectdetails = R::findOne('studentaddsubjectdetails','studentid = ? and studentsubjectid = ? and del < 2  order by id desc',[$Explode[$i], $studentsubjects->id]);
                $studentabsences = R::dispense('studentabsences');
                $studentabsences->onlys = 0;
                $studentabsences->del = 0;
                $studentabsences->arrivedtime = '0';
                $studentabsences->addtoday = $today;   
                $studentabsences->studentid = $Explode[$i];
                $studentabsences->adduserid = $_SESSION['userid'];
                $studentabsences->todaysend = $date;
                $studentabsences->deviceid = $studentsubjects->deviceid;
                $studentabsences->timesend = $times;
                $studentabsences->studentsubjectid = $studentaddsubjects->studentsubjectid;
                $studentabsences->studentsubjectgroupid = $studentaddsubjects->studentsubjectgroupid;
                $studentabsences->studentaddsubjectid = $studentaddsubjects->id;
                $studentabsences->studentaddsubjectdetailid = $studentaddsubjectdetails->id;
                R::store($studentabsences);
            }
        }
    
       
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function sendmassagemanual() {
$userid = $_SESSION['userid'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");
$times = date("H:i:s");
$time1hour = date('H:i:s', strtotime('+1 hour'));
$day = date('l');
    $studentsubjectgroupid = filter_input(INPUT_POST, 'studentsubjectgroupid');
    try {
        $studentaddsubjectdetails = R::findAll('studentaddsubjectdetails',' studentsubjectgroupid = ? and del < 2 ',[$studentsubjectgroupid]); 
         foreach($studentaddsubjectdetails as $studentaddsubjectdetail){
             $studentabsencesc = R::count('studentabsences', " studentid = ? and deviceid = ? and todaysend = '$date' and del < 2",[$studentaddsubjectdetail->studentid, $studentaddsubjectdetail->deviceid]);        
                if ($studentabsencesc == 0) {
                    $studentabsences = R::dispense('studentabsences');
                    $studentabsences->del = 0;
                    $studentabsences->onlys = 1;
                    $studentabsences->arrivedtime = '0';
                    $studentabsences->addtoday = $today;  
                    $studentabsences->todaysend = $date;        
                    $studentabsences->adduserid = $_SESSION['userid'];
                    $studentabsences->studentid = $studentaddsubjectdetail->studentid;
                    $studentabsences->deviceid = $studentaddsubjectdetail->deviceid;
                    $studentabsences->studentsubjectid = $studentaddsubjectdetail->studentsubjectid;
                    $studentabsences->studentsubjectgroupid = $studentaddsubjectdetail->studentsubjectgroupid;
                    $studentabsences->studentaddsubjectid = $studentaddsubjectdetail->studentaddsubjectid;
                    $studentabsences->studentaddsubjectdetailid = $studentaddsubjectdetail->id;
                    R::store($studentabsences);
                }
         }
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}
function showajax() {
    $columns = array('id', 'subjectname', 'subjectgroupname','dayar','','', 'addtoday', '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 studentabsences.studentaddsubjectid = ".$data1. " ";
    }

    if($data2 != ''){
      $searchQuery .= " and studentabsences.studentaddsubjectdetailid = ".$data2. " "; 
      // $joinQuery = " LEFT JOIN studentabsencedetails ON studentabsences.id = studentabsencedetails.studentabsenceid "; 
    }
    if($del == ''){
      $searchQuery .= " and studentabsences.del < 2 "; 
    }

    if($data3 != ''){
      $searchQuery .= " and studentabsences.onlys =  ".$data3. " "; 
    }
    
    if($start_date != '' && $end_date != ''){
      $searchQuery .='and  studentabsences.addtoday  >= "' . $start_date . ' 00-00-00" and studentabsences.addtoday <= "' . $end_date . ' 23-59-55" ';
    }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( studentabsences.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR studentabsences.subjectname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentabsences.subjectgroupname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentabsences.dayar LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentabsences.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR employeename LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }
    if($data1 == ''){
      $searchQuery .= " group by studentsubjects.deviceid ";
    }

    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  studentabsences.id DESC ";
    }
        $totals = R::count('studentabsences','LEFT JOIN user
         ON studentabsences.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  studentabsences.id as id, studentabsences.addtoday as addtoday, studentabsences.del as del, employeename, studentid
     ,studentsubjects.del as studentsubjectsdel ,studentsubjectgroups.del as studentsubjectgroupsdel,  
 subjectname, subjectgroupname, subjectgroupprice, studentname, studentphone, studentsubjects.deviceid, todaysend, timesend, ipaddress
 FROM `studentabsences`  
 LEFT JOIN user ON studentabsences.adduserid = user.userid 
  LEFT JOIN studentsubjects ON studentabsences.studentsubjectid = studentsubjects.id 
 LEFT JOIN studentsubjectgroups ON studentabsences.studentsubjectgroupid = studentsubjectgroups.id 
 LEFT JOIN students ON studentabsences.studentid = students.id 
 WHERE 1 '.$searchQuery.' ');  
    $apps = count($rResult);
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row["subjectname"];
        $sub_array[] = $row["deviceid"];
        $sub_array[] = $row["studentname"];
        $sub_array[] = $row["todaysend"].' '.$row["timesend"];
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["employeename"]; 
        if($row["del"] < 2){ 
        $sub_array[] = '<a href="studentAbsence.php?do=edit&id='. $row["ipaddress"] .'" type="button" class="btn btn-default btn-lm ">مراجعه</a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-controll="studentAbsence"  type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = ' لا يوجد ';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}



function removecontroller() {
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('studentabsences',$id);
    $tables->del = 2;
    $tables->deltoday = date("Y-m-d H:i:s");     
    $tables->deluserid = $_SESSION['userid']; 
    try {
        R::store($tables);
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function getstudentabsence() {
    $searchterm = $_POST['searchTerms']; 
    $tablesearch = $_POST['tablesearch'];
    $studentaddsubjectid = $_POST['studentaddsubjectid'];

    $row_array = array();
    $return_arr = array();
    $search = '';
    $studentid = '0';
    $studentaddsubjectdetails = R::findAll('studentaddsubjectdetails', "studentaddsubjectdetails.del < 2 and studentaddsubjectdetails.studentaddsubjectid = ? ",[$studentaddsubjectid]);
    foreach($studentaddsubjectdetails as $studentaddsubjectdetail){
        $studentsubjects = R::load('studentsubjects',$studentaddsubjectdetail->studentsubjectid);
        $date = date("Y-m-d");
        $studentabsences = R::count('studentabsences', "studentid = ? and deviceid = ? and todaysend = '$date' and del < 2",[$studentaddsubjectdetail->studentid, $studentsubjects->deviceid]);
        if ($studentabsences == 0) {
             $studentid .= ','.$studentaddsubjectdetail->studentid;
        }
    }
    $search .= " and students.id in ($studentid) ";
    
    $allData = R::getAll("SELECT  students.id,CONCAT($tablesearch) as name
        FROM students
        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);
}


?>