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



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

if (empty($do)) {  
    $projects = R::findAll('project','del = 0 and finish = 0 ');
    // foreach ($projects as $project) {
    //     $project->projectstagechosse = R::findAll('projectstagechosse', 'projectid = ? ', [$project->id]);
    // }
    $smarty->assign('projects', $projects);
    $smarty->display("header.html");
    $smarty->display("projectstagesdataview/add.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
} elseif ($do == "show") {
    include_once("../public/authentication.php");
    $smarty->assign('date', $date);
    $search_params = '';
    if( $_SESSION['projectids'] != 0){
        $search_params = ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }


    $projects = R::getAll('SELECT project.* FROM `project` WHERE project.del = 0  ' .  $search_params);
    $smarty->assign('projects', $projects);
    $smarty->display("header.html");
    $smarty->display("projectstagesdataview/show.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $project = R::load('project', $id);
    $projectstagechosse = R::findAll('projectstagechosse', 'projectid = ? ', [$id]);
    foreach ($projectstagechosse as  $projectstagecho) {
        $projectstagecho->projectstage = R::findOne('projectstages', 'id = ? ', [$projectstagecho->projectstageid]);
        $projectstagecho->images = explode(',', $projectstagecho->projectstageimages);
        $projectstagefiles = explode(',', $projectstagecho->projectstagefiles);
        $oldnamefiles = explode(',', $projectstagecho->oldnamefiles);
        $files = [];
        for ($i=0; $i < count($projectstagefiles); $i++) { 
           $files[] = [ 'name' => $oldnamefiles[$i],'file' => $projectstagefiles[$i]];
        }
        $projectstagecho->files = $files;
    }
    $smarty->assign('projectstagechosse', $projectstagechosse);
    $smarty->assign('project', $project);
    $smarty->display("header.html");
    $smarty->display("projectstagesdataview/edit.html");
    $smarty->assign("project", 1);
    $smarty->display("footer.html");
} elseif ($do == "detail") {
    include_once("../public/authentication.php");

    $id = filter_input(INPUT_GET, 'id');
    $project = R::load('project', $id);
    $projectstagechosse = R::findAll('projectstagechosse', 'projectid = ? ', [$id]);
    foreach ($projectstagechosse as  $projectstagecho) {
        $projectstagecho->projectstage = R::findOne('projectstages', 'id = ? ', [$projectstagecho->projectstageid]);
        $projectstagecho->images = explode(',', $projectstagecho->projectstageimages);
        $projectstagefiles = explode(',', $projectstagecho->projectstagefiles);
        $oldnamefiles = explode(',', $projectstagecho->oldnamefiles);
        $files = [];
        for ($i=0; $i < count($projectstagefiles); $i++) { 
           $files[] = [ 'name' => $oldnamefiles[$i],'file' => $projectstagefiles[$i]];
        }
        $projectstagecho->files = $files;
    }

    $smarty->assign('projectstagechosse', $projectstagechosse);
    $smarty->assign('project', $project);
    $smarty->display("header.html");
    $smarty->display("projectstagesdataview/detail.html");
    $smarty->display("footer.html");    
}else if ($do == 'savedata') {
  savedata();
}else if ($do == 'showajax') {
  showajax();
}else if ($do == 'removecontroller') {
  removecontroller();
}


function savedata() {
   
include("../library/uploadImages.php");

    $today = date("Y-m-d H:i:s");
    $date = date('Y-m-d');
    $userid = $_SESSION['userid'];
    $projectstagechosseitr = filter_input(INPUT_POST, 'projectstagechosseitr', FILTER_DEFAULT);


    

    try {

         for ($i2=1; $i2 <= $projectstagechosseitr; $i2++) { 
            $projectstagechoid = filter_input(INPUT_POST, 'projectstagechoid'.$i2, FILTER_DEFAULT);
            $title = filter_input(INPUT_POST, 'title'.$i2, FILTER_DEFAULT);
            $descripe = filter_input(INPUT_POST, 'descripe'.$i2, FILTER_DEFAULT);
            $oldeimages = filter_input(INPUT_POST, 'oldeimages'.$i2, FILTER_DEFAULT);
            $oldefiles = filter_input(INPUT_POST, 'oldefiles'.$i2, FILTER_DEFAULT);
            if ($oldeimages) {
                if (isset($_FILES["projectstageimages".$i2]) && !empty($_FILES["projectstageimages".$i2])) {
                $projectstageimages = uploadfileMultipleWithName("projectstageimages".$i2, '../upload/project', explode(',', $oldeimages));
                }
            }else{
                $projectstageimages = uploadfileMultipleWithName("projectstageimages".$i2, '../upload/project');    
            }
            if ($oldefiles) {
                if (isset($_FILES["projectstagefiles".$i2]) && !empty($_FILES["projectstagefiles".$i2])) {
                $projectstagefiles = uploadfileMultipleWithName("projectstagefiles".$i2, '../upload/project', explode(',', $oldefiles));
               }
            }else{
                $projectstagefiles = uploadfileMultipleWithName("projectstagefiles".$i2, '../upload/project');
            }
            
            
            if ($projectstagechoid) {
                $projectstagechosse = R::load('projectstagechosse',$projectstagechoid);
                $projectstagechosse->title = $title;
                $projectstagechosse->descripe = $descripe;  
                $projectstagechosse->projectstageimages = implode(',', $projectstageimages[0]);
                $projectstagechosse->oldnameimages = implode(',', $projectstageimages[1]);
                $projectstagechosse->projectstagefiles = implode(',', $projectstagefiles[0]);
                $projectstagechosse->oldnamefiles = implode(',', $projectstagefiles[1]);
                $projectstagechosse->chosseuserid = $_SESSION['userid'];
                R::store($projectstagechosse);
             }

        }

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


function showajax() {
    $columns = array('project.id','name', '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 = " ";
    $joinQuery = " ";
    if($data1 != ''){
      $searchQuery .=  " and project.id = ".$data1. " ";
    }else if( $_SESSION['projectids'] != 0  ){
        $searchQuery .= ' AND project.id in (' . $_SESSION['projectids'] . ')';
    } if( $_SESSION['projectids'] != 0){
        $searchQuery .= ' AND project.id in (' . $_SESSION['projectids'] . ')';
    }
    // if($del == ''){
    //    $searchQuery .= " and project.del < 2 "; 
    // }

    // if($data3 != ''){
    //    $joinQuery .= " LEFT JOIN webclientprojects ON webclients.id = webclientprojects.webclientid ";
    //    $searchQuery .= " and webclientprojects.clientid = ".$data3. " ";
    // }
    
    // if($start_date != '' && $end_date != ''){
    //    $searchQuery .='and  project.addtoday  >= "' . $start_date . ' 00-00-00" and project.addtoday <= "' . $end_date . ' 23-59-55" ';
    // }else{
    //     $today = date("Y-m-d");
    //     $searchQuery .='and  project.addtoday  >= "' . $today . ' 00-00-00" and project.addtoday <= "' . $today . ' 23-59-55" ';
    // }


    if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    $searchQuery .= "and ( project.id LIKE "%'.$_POST["search"]["value"].'%" 
                    OR project.name LIKE "%'.$_POST["search"]["value"].'%"
        )
     ";
    }


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


     $totals = R::count('project',"  WHERE 1 $searchQuery ");
    
    if (isset($_POST['start']) && $_POST['length'] != '-1') {
       $searchQuery .= "LIMIT " . intval($_POST['start']) . ", " .
                intval($_POST['length']);
    }

    $rResult = R::getAll("SELECT project.*  FROM `project`  $joinQuery  WHERE 1 $searchQuery ");   
    $apps = count($rResult);
    
    
     
    $output = array(  
        "draw" => intval($_POST["draw"]),
        "recordsTotal" => $totals,
        "recordsFiltered" =>intval($apps),
        "data" => array()
    );
  
       foreach ($rResult as $row) {
        $date = date('Y-m-d');
        
        $sub_array = array();
        $sub_array[] = $row["id"];
        //  if ($row["filepdf"] != "." && $row["filepdf"] != "") {
        //    $sub_array[] = '<a src="../views/default/images/students/'. $row["filepdf"] .'"  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["name"];
    
        // 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[] = 'لا يوجد';
        // }
  
        if($row["del"] < 2){  
        $sub_array[] = '<a href="projectstagesdataController.php?do=detail&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';    
        $sub_array[] = '<a href="projectstagesdataController.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="projectstagesdataController.php?do=detail&id='. $row["id"] .'" type="button" class="btn btn-default btn-lg editicon"></a>';
          $sub_array[] = '';
          $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 ;
    }
}





?>