<?php
include("../public/impOpreation.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)) {  
    $smarty->display("header.html");
    $smarty->display("studentsubjectsview/add.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} else if ($do == "addappend") { 
$itr = filter_input(INPUT_POST, 'itr');  
$dataitr = filter_input(INPUT_POST, 'dataitr'); 
$container = filter_input(INPUT_POST, 'container');  
$smarty->assign('itr', $itr);
$smarty->assign('dataitr', $dataitr);
$smarty->assign('student', 1);
$smarty->display("studentsubjectsview/".$container."row.html");
} else if ($do == "show") {
    include_once("../public/authentication.php");
    $studentsetting = R::load('studentsetting',1);
    $smarty->assign("studentsetting",$studentsetting);
     $smarty->assign('date', $date);
    $smarty->display("header.html");

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

    $smarty->display("studentsubjectsview/show.html");
    $smarty->assign("student", 1);
    $smarty->display("footer.html");
} else if ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');
    $subjects = R::load('studentsubjects', $id);
    $smarty->assign('subjects', $subjects);
    $groupsappend = R::findAll('studentsubjectgroups', 'studentsubjectid = ?  and del < 2',[$id]);
    foreach($groupsappend as $groupappend){
        $daysappend = R::findAll('studentsubjectgroupdays', 'studentsubjectgroupid = ?  and del < 2',[$groupappend->id]);
        $groupappend->daysappend = $daysappend;
    }
    $smarty->assign('groupsappend', $groupsappend);
    $smarty->display("header.html");
    $smarty->display("studentsubjectsview/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();
}else if ($do == 'removeappend') {
  removeappend();
}


function savedata() {
    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $subjectname = filter_input(INPUT_POST, 'subjectname');
    $subjectprice = filter_input(INPUT_POST, 'subjectprice');
    $deviceid = filter_input(INPUT_POST, 'deviceid');
    $ipaddress = filter_input(INPUT_POST, 'ipaddress');
    $subjectgroupsitr = filter_input(INPUT_POST, 'studentsubjectgroupsitr');
    $subjectid = filter_input(INPUT_POST, 'subjectid');
    $incometype = filter_input(INPUT_POST, 'incometype');

    if (!$subjectid) {
        $subjects = R::dispense('studentsubjects');
        $subjects->del = 0;
        $subjects->addtoday = $today;  
        $subjects->adduserid = $userid;
        $subjects->deltoday = '';  
        $subjects->deluserid = '';
    }else{
       $subjects = R::load('studentsubjects',$subjectid); 
       $subjects->del = 1;
       $subjects->updatetoday = $today;          
       $subjects->updateuserid = $userid;
    }
    $subjects->subjectname  = $subjectname;
    $subjects->subjectprice = $subjectprice;
    $subjects->ipaddress = $ipaddress;
    $subjects->deviceid = $deviceid;
    $subjects->useit  = 0;        
    try {
        $subjectid = R::store($subjects);
        if(!$incometype){
            R::exec("INSERT INTO `incometype`(`incomeTypeName`, `defaultValue`, `parent`, `incomeTypeDate`, `userid`, `conditions`, `studentsubjectid`) VALUES 
         ('$subjectname', '$subjectprice', 0,'$date', $userid, 0, $subjectid)");
           $incometype = R::getCell("SELECT incomeTypeId FROM `incometype` WHERE studentsubjectid =  $subjectid");
           $studentsubjects = R::load('studentsubjects',$subjectid);
           $studentsubjects->incometypeid = $incometype; 
           R::store($studentsubjects);
            
        }else{
             R::exec("UPDATE `incometype` SET `incomeTypeName`='$subjectname', `defaultValue`='$subjectprice' WHERE incometypeid = $subjects->incometypeid");
        }
         
        for ($i1 = 1; $i1 <= $subjectgroupsitr; $i1++) {
            $subjectgroupname = filter_input(INPUT_POST, 'subjectgroupname' . $i1);
            $subjectgroupprice = filter_input(INPUT_POST, 'subjectgroupprice' . $i1);
            $subjectgroupsdayitr = filter_input(INPUT_POST, 'studentsubjectgroupdaysitr' . $i1);
            $subjectgroupid = filter_input(INPUT_POST, 'subjectgroupid' . $i1);

            
            if (!$subjectgroupid) {
                $subjectgroups = R::dispense('studentsubjectgroups');
                $subjectgroups->del = 0;
                $subjectgroups->addtoday = $today;  
                $subjectgroups->adduserid = $userid;
                $subjectgroups->deltoday = '';  
                $subjectgroups->deluserid = '';

            }else{
               $subjectgroups = R::load('studentsubjectgroups',$subjectgroupid); 
                $subjectgroups->del = 1;
                $subjectgroups->updatetoday = $today;          
                $subjectgroups->updateuserid = $userid;

            }
            if (!$subjectgroupname  || $subjectgroupsdayitr < 1) {continue;}
            $subjectgroups->studentsubjectid = $subjectid;
            $subjectgroups->subjectgroupname = $subjectgroupname;  
            $subjectgroups->subjectgroupprice = empty($subjectgroupprice) ? $subjectprice : $subjectgroupprice;
            $subjectgroups->useit  = 0;  
            $subjectgroupid = R::store($subjectgroups);
            for ($i2 = 1; $i2 <= $subjectgroupsdayitr; $i2++) {
                $day = filter_input(INPUT_POST, 'day' .$i1.$i2);
                $subjectgroupdayid = filter_input(INPUT_POST, 'subjectgroupdayid' .$i1.$i2);
                $timeform = filter_input(INPUT_POST, 'timeform' . $i1.$i2);
                $timeto = filter_input(INPUT_POST, 'timeto' . $i1.$i2);
                $dayar = ['','السبت','الأحد','الاثنين','الثلاثاء','الاربعاء','الخميس','الجمعة'];
                $dayen = ['','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'];
                if (!$subjectgroupdayid) {
                    $subjectgroupdays = R::dispense('studentsubjectgroupdays');
                    $subjectgroupdays->del = 0;
                    $subjectgroupdays->addtoday = $today;  
                    $subjectgroupdays->adduserid = $userid;
                    $subjectgroupdays->deltoday = '';  
                    $subjectgroupdays->deluserid = '';
                }else{
                   $subjectgroupdays = R::load('studentsubjectgroupdays',$subjectgroupdayid); 
                   $subjectgroupdays->del = 1;
                   $subjectgroupdays->updatetoday = $today;          
                   $subjectgroupdays->updateuserid = $userid;
                }
                if (!$day || !$timeform || !$timeto) {continue;}
                $subjectgroupdays->studentsubjectid = $subjectid;
                $subjectgroupdays->studentsubjectgroupid = $subjectgroupid;
                $subjectgroupdays->dayar = $dayar[$day]; 
                $subjectgroupdays->dayen = $dayen[$day];  
                $subjectgroupdays->day = $day;  
                $subjectgroupdays->timeform = $timeform;  
                $subjectgroupdays->timeto = $timeto;  
                $subjectgroupdays->useit  = 0; 
                $subjectgroupdayid = R::store($subjectgroupdays);
            } 
        }   
        echo 1;
    } catch (Exception $e) {
        echo 0 ;
    }
   
}


function showajax() {
    $columns = array('id', 'subjectname', 'subjectprice', '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 studentsubjects.id = ".$data1. " ";
    }
    if($del == ''){
       $searchQuery .= " and studentsubjects.del < 2 "; 
    }

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


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( studentsubjects.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR studentsubjects.subjectname LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentsubjects.subjectprice LIKE "%'.$_POST["search"]["value"].'%"
                    OR studentsubjects.addtoday 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  studentsubjects.id DESC ";
    }
       $totals = R::count('studentsubjects','LEFT JOIN user
         ON studentsubjects.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 studentsubjects.* ,employeename  FROM `studentsubjects` LEFT JOIN user
             ON studentsubjects.adduserid = user.userid  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["subjectprice"];  
        $sub_array[] = $row["deviceid"];
        $sub_array[] = $row["ipaddress"];  
        $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="studentSubjectsController.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="studentSubjectsController" type="button" class="btn btn-default btn-lg deleteicon removecontroller"  ></a>';
        }else{
          $sub_array[] = 'لا يوجد ';
          $sub_array[] = '<a href="studentSubjectsController.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('studentsubjects',$id);
    $tables->del = 2;
    $tables->deltoday = $today;
    $tables->deluserid = $userid;          
    try {
        R::store($tables);
        R::exec("UPDATE `studentsubjectgroups` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid  WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentsubjectgroupdays` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid  WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentaddsubjects` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid  WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentaddsubjectdetails` SET `del`= 3, `deltoday`= '$today', `deluserid`= $userid  WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentsexams` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentsexamsval` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentspaymentsystems` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `studentspays` SET `del`= 3, `deltoday`= '$today', `deluserid`= '$userid' WHERE studentsubjectid = '" . $id . "' ");
        R::exec("UPDATE `incometype` SET `conditions`= 1 WHERE studentsubjectid = '" . $id . "' ");
        echo 1 ;
    } catch (Exception $e) {
        echo 0 ;
    }
}


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










?>