<?php
include("../public/impOpreation.php");
$do = $_GET['do'];

$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");
if (empty($do)) {  
    $smarty->display("header.html");
    $smarty->display("studentsaddsubjectview/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->display("header.html");
    $smarty->display("studentsaddsubjectview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $addstudent = filter_input(INPUT_GET, 'addstudent');
    $studentaddsubjectdata = R::load('studentaddsubjects', $id);
    $studentsubjects = R::findOne('studentsubjects','id = ? and del < 2',[$studentaddsubjectdata->studentsubjectid]);
    $studentsubjectgroups = R::findOne('studentsubjectgroups','id = ? and del < 2',[$studentaddsubjectdata->studentsubjectgroupid]);
    $studentaddsubjectdata->studentsubjects = $studentsubjects->subjectname.'/'.$studentsubjects->subjectprice;
    $studentaddsubjectdata->studentsubjectgroups = $studentsubjectgroups->subjectgroupname.'/'.$studentsubjectgroups->subjectgroupprice;
    $smarty->assign('studentaddsubjectdata', $studentaddsubjectdata);
    
    if ($addstudent != 1) {
    $smarty->display("header.html");
    $smarty->display("studentsaddsubjectview/edit.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
    }else{
    $studentaddsubjectdetails = R::findAll('studentaddsubjectdetails','studentaddsubjectid = ? and del < 2',[$id]);
    foreach($studentaddsubjectdetails as $studentaddsubjectdetail){
        $students = R::findOne('students','id = ? and del < 2',[$studentaddsubjectdetail->studentid]);
        $studentaddsubjectdetail->student = $students->studentname;
    }
    $smarty->assign('studentaddsubjectdetails', $studentaddsubjectdetails);
    $smarty->display("header.html");
    $smarty->display("studentsaddsubjectview/addstudent.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
    }
    
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removesubjectsstudent') {
  removesubjectsstudent();
}else if ($do == 'savedata2') {
  savedata2();
}else if ($do == 'removecontroller') {
  removecontroller();
}else if ($do == 'getstudentedit') {
  getstudentedit();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $subjectid = filter_input(INPUT_POST, 'subjectid');
    $subjectgroupid = filter_input(INPUT_POST, 'subjectgroupid');
    $studentaddsubjectid = filter_input(INPUT_POST, 'studentaddsubjectid');
    $studentp =$_POST['studentid'];
    $Explode = explode(',', $_POST['studentid']);

    if (!$studentaddsubjectid) {
        $studentaddsubjects = R::dispense('studentaddsubjects');
        $studentaddsubjects->del = 0;
        $studentaddsubjects->addtoday = $today;          
        $studentaddsubjects->adduserid = $userid;
        $studentaddsubjects->deltoday = '';      
        $studentaddsubjects->deluserid = '';
    }else{
       $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid); 
       $studentaddsubjects->del = 1;
       $studentaddsubjects->updatetoday = $today;          
       $studentaddsubjects->updateuserid = $userid;
    }
    $studentaddsubjects->studentsubjectid  = $subjectid;
    $studentaddsubjects->studentsubjectgroupid = $subjectgroupid;
    $studentaddsubjects->studentid = $studentp;
    try {
        $studentaddsubjectid2 = R::store($studentaddsubjects);
        if (!$studentaddsubjectid) {
           for ($i = 0; $i < count($Explode); $i++) { 
            $studentdata = R::load('students',$Explode[$i]); 
            $studentaddsubjectdetails = R::dispense('studentaddsubjectdetails');
            $studentaddsubjectdetails->del = 0;
            $studentaddsubjectdetails->addtoday = $today;          
            $studentaddsubjectdetails->adduserid = $userid;
            $studentaddsubjectdetails->studentid  = $Explode[$i];
            $studentaddsubjectdetails->studentsubjectid  = $subjectid;
            $studentaddsubjectdetails->studentsubjectgroupid = $subjectgroupid;
            $studentaddsubjectdetails->studentaddsubjectid = $studentaddsubjectid2;
            R::store($studentaddsubjectdetails);
            }  
        }else{
            $studentaddsubjectdetailsd = R::findAll('studentaddsubjectdetails', 'studentaddsubjectid = ? ',[$studentaddsubjectid]);
            foreach ($studentaddsubjectdetailsd as $value) {
                if (!in_array($value->studentid, $Explode)) {
                R::exec("UPDATE `studentaddsubjectdetails` SET SET `del`= 2, `deltoday`= '$today', `deluserid`= $userid WHERE id = $value->id ");

                }
            }

            for ($i = 0; $i < count($Explode); $i++) { 
                $count = R::count('studentaddsubjectdetails', 'studentaddsubjectid = ? and studentid = ? and del < 2', [$studentaddsubjectid, $Explode[$i]]);
                if ($count == 0) {
                    $studentdata = R::load('students',$Explode[$i]); 
                    $studentaddsubjectdetails = R::dispense('studentaddsubjectdetails');
                    $studentaddsubjectdetails->del = 0;
                    $studentaddsubjectdetails->addtoday = $today;          
                    $studentaddsubjectdetails->adduserid = $userid;
                    $studentaddsubjectdetails->updatetoday = $today;          
                    $studentaddsubjectdetails->updateuserid = $userid;
                    $studentaddsubjectdetails->deltoday = '';      
                    $studentaddsubjectdetails->deluserid = '';
                    $studentaddsubjectdetails->studentid  = $Explode[$i];
                    $studentaddsubjectdetails->studentsubjectid  = $subjectid;
                    $studentaddsubjectdetails->studentsubjectgroupid = $subjectgroupid;
                    $studentaddsubjectdetails->studentaddsubjectid = $studentaddsubjectid2;
                    R::store($studentaddsubjectdetails);
                }
            }  
        }
    

   
        if ($studentaddsubjectid && $studentaddsubjects->studentsubjectgroupid  != $subjectgroupid) {
            R::exec("UPDATE `studentsubjectgroups` SET `useit`= 0 WHERE  id = '" . $studentaddsubjects->studentsubjectgroupid . "' ");
        }
        R::exec("UPDATE `studentsubjectgroups` SET `useit`= 1 WHERE  id = '" . $subjectgroupid . "' ");
         

        if ($studentaddsubjectid && $studentaddsubjects->studentsubjectid  != $subjectid) {
            $countsubjects = R::count('studentsubjectgroups', 'studentsubjectid = ? and useit = 0 and del < 2',[$studentaddsubjects->studentsubjectid]);
            if ($countsubjects == 0) {
              R::exec("UPDATE `studentsubjects` SET `useit`= 1 WHERE  id = '" . $studentaddsubjects->studentsubjectid . "' ");
            }
        }
        $countsubjects = R::count('studentsubjectgroups', 'studentsubjectid = ? and useit = 0 and del < 2',[$subjectid]);
        if ($countsubjects == 0) {
          R::exec("UPDATE `studentsubjects` SET `useit`= 1 WHERE  id = '" . $subjectid . "' ");
        }

        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}



function showajax() {
    $columns = array('id', 'subjectname', 'subjectgroupname','subjectgroupprice', '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 studentaddsubjects.studentsubjectid = ".$data1. " ";
    }

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

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( studentaddsubjects.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR studentaddsubjects.subjectname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentaddsubjects.subjectgroupname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentaddsubjects.subjectgroupprice LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentaddsubjects.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR employeename LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }
 $totals = R::count('studentaddsubjects'," LEFT JOIN user ON studentaddsubjects.adduserid = user.userid 
 LEFT JOIN studentsubjects ON studentaddsubjects.studentsubjectid = studentsubjects.id 
 LEFT JOIN studentsubjectgroups ON studentaddsubjects.studentsubjectgroupid = studentsubjectgroups.id
 WHERE 1 $searchQuery");  

    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  studentaddsubjects.id DESC ";
    }
    


    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }
 $rResult = R::getAll('SELECT studentaddsubjects.id as id, studentaddsubjects.addtoday as addtoday, studentaddsubjects.del as del, employeename ,studentsubjects.del as studentsubjectsdel ,studentsubjectgroups.del as studentsubjectgroupsdel,  
 subjectname, subjectgroupname, subjectgroupprice FROM `studentaddsubjects` LEFT JOIN user ON studentaddsubjects.adduserid = user.userid 
 LEFT JOIN studentsubjects ON studentaddsubjects.studentsubjectid = studentsubjects.id 
 LEFT JOIN studentsubjectgroups ON studentaddsubjects.studentsubjectgroupid = studentsubjectgroups.id
 WHERE studentsubjects.del < 2 and studentsubjectgroups.del < 2  '.$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["subjectgroupname"];
        $sub_array[] = $row["subjectgroupprice"];
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["employeename"];   
        if($row["studentsubjectgroupsdel"] < 2 && $row["studentsubjectsdel"] < 2  && $row["del"] < 2){ 
             $sub_array[] = '<a href="studentsAddSubject.php?do=edit&id='. $row["id"] .'&addstudent=1" type="button" class="btn btn-default btn-lm ">+</a>'; 
             $sub_array[] = '<a href="studentsAddSubject.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
        }else{
            $sub_array[] = ' <a href="studentsAddSubject.php?do=edit&id='. $row["id"] .'&addstudent=1" type="button" class="btn btn-default btn-lm ">تفاصيل</a>  ';
            $sub_array[] = '<a href="studentsAddSubject.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lm">تفاصيل</a>';
        }
      
        if($row["del"] < 2){ 
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-controll="studentsAddSubject" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}

function removesubjectsstudent() {
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('studentaddsubjectdetails',$id);
    $tables->del = 2;
    $tables->deltoday = date("Y-m-d H:i:s");     
    $tables->deluserid = $_SESSION['userid']; 
    try {
        R::store($tables);
        $subjectsstudents = R::findAll('studentaddsubjectdetails','studentaddsubjectid = ? and del < 2',[$tables->studentaddsubjectid]);
        $studentid = '0';
        foreach($subjectsstudents as $data){
         $studentid .= ','.$data->studentid;
        }
        $studentsaddubjects = R::load('studentaddsubjects',$tables->studentaddsubjectid);
        $studentsaddubjects->studentid = $studentid;
        if ($studentsaddubjects->studentid == 0) {
        R::exec("UPDATE `studentsubjects` SET `useit`= 0 WHERE id = '" . $studentsaddubjects->studentsubjectid . "' ");
        R::exec("UPDATE `studentsubjectgroups` SET `useit`= 0 WHERE id = '" . $studentsaddubjects->studentsubjectgroupid . "' ");
        $studentsaddubjects->del = 2;
        }

        R::store($studentsaddubjects);

        

         
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


function savedata2() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $studentaddsubjectid = filter_input(INPUT_POST, 'studentaddsubjectid');
    $studentp =$_POST['studentid'];
    $Explode = explode(',', $_POST['studentid']);

    
    $studentaddsubjects = R::load('studentaddsubjects',$studentaddsubjectid); 
    $studentaddsubjects->del = 1;
    $studentaddsubjects->updatetoday = $today;          
    $studentaddsubjects->updateuserid = $userid;
    $studentaddsubjects->studentid = $studentaddsubjects->studentid.','.$studentp;
    try {
        $studentaddsubjectid2 = R::store($studentaddsubjects);
        for ($i = 0; $i < count($Explode); $i++) { 
            $studentdata = R::load('students',$Explode[$i]); 
            $studentaddsubjectdetails = R::dispense('studentaddsubjectdetails');
            $studentaddsubjectdetails->studentid  = $Explode[$i];
            $studentaddsubjectdetails->studentsubjectid  = $studentaddsubjects->studentsubjectid;
            $studentaddsubjectdetails->studentsubjectgroupid = $studentaddsubjects->studentsubjectgroupid;
            $studentaddsubjectdetails->del = 0;
            $studentaddsubjectdetails->studentaddsubjectid = $studentaddsubjectid;
            R::store($studentaddsubjectdetails);
            
        }  
        
    

   

        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}



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('studentaddsubjects',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;      
    try {
        R::store($tables);
        R::exec("UPDATE `studentsubjects` SET `useit`= 0 WHERE del < 2 and id = '" . $tables->studentsubjectid . "' ");
        R::exec("UPDATE `studentsubjectgroups` SET `useit`= 0 WHERE del < 2 and id = '" . $tables->studentsubjectgroupid . "' ");
        R::exec("UPDATE `studentaddsubjectdetails` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid WHERE studentaddsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentsexams` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentaddsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentsexamsval` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentaddsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentspaymentsystems` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentaddsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentspays` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentaddsubjectid = '" . $id . "' ");
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}



function getstudentedit() {
    $ids =$_POST['ids'];
    $subjectsstudents = R::findAll('studentaddsubjectdetails','studentaddsubjectid = ? and del < 2',[$ids]);
    $studentid = '0';
    foreach($subjectsstudents as $data){
     $studentid .= ','.$data->studentid;
    }
    $students = R::getAll('SELECT id, CONCAT(studentname,"/",studentphone) as text FROM students WHERE id in ('.$studentid.') ');
    echo json_encode($students);
}


?>