<?php
include("../public/impOpreation.php");
include("../library/uploadImages.php");

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d");

if (empty($do)) {  

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

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("header.html");
    $smarty->display("studentview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $studentdata = R::load('students', $id);
    $smarty->assign('studentdata', $studentdata);
    $branchs = R::getAll('SELECT branch.* FROM `branch` WHERE 1 ');
    $smarty->assign('branchs', $branchs);
    $smarty->display("header.html");
    $smarty->display("studentview/edit.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removecontroller') {
  removecontroller();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $studentname = filter_input(INPUT_POST, 'studentname');
    $studentnumber = filter_input(INPUT_POST, 'studentnumber');
    $idnumber = filter_input(INPUT_POST, 'idnumber');
    $studentphone = filter_input(INPUT_POST, 'studentphone');
    $parentsphone = filter_input(INPUT_POST, 'parentsphone');
    $studentaddress = filter_input(INPUT_POST, 'studentaddress');
    $studentnote = filter_input(INPUT_POST, 'studentnote');
    $branchid = filter_input(INPUT_POST, 'branchid');
    $studentid = filter_input(INPUT_POST, 'studentid');
    $clientid = filter_input(INPUT_POST, 'clientid');

    if (!$studentid) {;
        $students = R::dispense('students');
        $students->del = 0;
        $students->addtoday = $today;          
        $students->adduserid = $userid;
        $students->deltoday = '';      
        $students->deluserid = '';
        $handle = new upload($_FILES['studentimage']);
        $studentimage = uploadImages($handle, "../views/default/images/students", 300, 300);
    }else{
        R::exec("UPDATE `client` SET `clientname`= '$studentname',`clientaddress`= '$studentaddress',`clientphone`= '$studentphone',`branchId`= $branchid WHERE clientid = $clientid");
        $students = R::load('students',$studentid);
        $students->del = 1;
        $students->updatetoday = $today;          
        $students->updateuserid = $userid; 
        $handle = new upload($_FILES['studentimage']);
        $studentimage = updateImages($handle, "oldstudentimage", "../views/default/images/students", 300, 300);
        unlink("../views/default/images/students" . $students->studentimage);
    }
    $students->studentname  = $studentname;
    $students->studentnumber = $studentnumber;
    $students->idnumber = $idnumber;
    $students->studentphone = $studentphone;
    $students->parentsphone = $parentsphone;
    $students->studentaddress = $studentaddress;
    $students->clientid = $clientid; 
    $students->branchid = $branchid; 
    $students->studentimage = $studentimage;
    $students->studentnote = $studentnote;
    try {
         $studentid = R::store($students);
            if (!$clientid) {
             R::exec("INSERT INTO `client`(`clientname`, `clientaddress`, `clientphone`, `clientdate`, `userid`, `branchId`, `studentid`) VALUES 
             ('$studentname', '$studentaddress', '$studentphone','$date', $userid, $branchid, $studentid)");
             $client = R::getCell("SELECT clientid FROM `client` WHERE studentid =  $studentid");
             $students = R::load('students',$studentid);
             $students->clientid = $client; 
             $studentid = R::store($students);
            }else{
               R::exec("UPDATE `client` SET `clientname`='$studentname',`clientaddress`='$studentaddress',`clientphone`='$studentphone',`branchId`= $branchid 
               WHERE clientid = $clientid");
            }
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
}


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

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( students.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR students.studentnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.idnumber LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.studentphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.parentsphone LIKE "%'.$_POST["search"]["value"].'%"
                    OR students.addtoday LIKE "%'.$_POST["search"]["value"].'%"
                    OR branchName LIKE "%'.$_POST["search"]["value"].'%"
                    OR employeename LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


    if(isset($_POST["order"]))
    {
    $searchQuery .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'  ';
    }
    else
    {
     $searchQuery .= "ORDER BY  students.id DESC ";
    }
    
     $totals = R::count('students','LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll('SELECT students.* ,employeename ,branchName  FROM `students` LEFT JOIN user
         ON students.adduserid = user.userid LEFT JOIN branch
         ON students.branchid = branch.branchId  WHERE 1 '.$searchQuery.' ');   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => intval($apps),
        "recordsFiltered" => $totals,
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $date = date('Y-m-d');
         $studentspays = R::count('studentspays',"studentid = ? and del < 2 and payenddate > '$date'",[$row['id']]);
        $sub_array = array();
        $sub_array[] = $row["id"];
         if ($row["studentimage"] != "." && $row["studentimage"] != "") {
           $sub_array[] = '<img src="../views/default/images/students/'. $row["studentimage"] .'"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;">';
        }else{
           $sub_array[] = ' <img src="../views/default/assets/img/blank.png"  style="width: 40px;height: 40px;border: 1px solid;border-radius: 6px;" alt="" class="card-img">';
        }
        $sub_array[] = $row["studentname"];
        $sub_array[] = $row["studentnumber"];
        $sub_array[] = $row["idnumber"];
        $sub_array[] = $row["studentphone"];
        $sub_array[] = $row["parentsphone"];
        if ($studentspays > 0 && $row["del"] < 2) {
            $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" type="button" class="btn btn-default btn-lm studentspaysend"  >الكود</a>';
        }else if ($studentspays > 0 && $row["del"] > 2) {
           $sub_array[] = ' موجود دفع ولكن الطالب محذوف   ';
        }else{
            $sub_array[] = 'لا يوجد';
        }
        $sub_array[] = $row["addtoday"];
        $sub_array[] = $row["branchName"];
        $sub_array[] = $row['employeename'] ;  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="studentController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
         $sub_array[] = '<a href="javascript:;" data-id="'. $row["id"] .'" data-controll="studentController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = '<a href="studentController.php?do=edit&id='. $row["id"] .'" type="button" class="btn btn-default btn-lm ">تفاصيل</a>';
          $sub_array[] = 'محذوف ';
        }
       
        $output['data'][] = $sub_array;
       }
    
       echo json_encode($output, JSON_UNESCAPED_SLASHES);

}



function removecontroller() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $id = filter_input(INPUT_POST, 'id');
    $tables = R::load('students',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;     
    try {
        R::store($tables);
        R::exec("UPDATE `client` SET `conditions`= 1 WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentaddsubjectdetails` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentsexamsval` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentid = '" . $id . "' ");
        R::exec("UPDATE `studentspays` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentid = '" . $id . "' ");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}





?>