<?php
/**
 * /subs/register_backend.php
 * @version 1.5
 * @desc backend for register
 * @author Fándly Gergő Zoltán (fandlygergo@gmail.hu, systemtest.tk)
 * @copy 2017 Fándly Gergő Zoltán
 * License:
    Result Manager for managing results of students in bilingual school systems.
    Copyright (C) 2017  Fándly Gergő Zoltán

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

try{
    
    if(isset($_GET['list'])){
        $filter="WHERE r.id<>0 and r.schoolyear=?";
        $filter_array=array($_GET['list']);
        if(isset($_POST['filter'])){
            if(isset($_POST['f_search'])){
                if($_POST['f_search']!=""){
                    $filter.=" and (s.fullname LIKE ? or c.name_1 LIKE ? or c.name_2 LIKE ? or p.name_1 LIKE ? or p.name_2 LIKE ? or t.fullname LIKE ?)";
                    array_push($filter_array, "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%");
                }
            }
            
            if(isset($_POST['f_student'])){
                for($i=0; $i<count($_POST['f_student']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.student=?";
                    array_push($filter_array, $_POST['f_student'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_contest'])){
                for($i=0; $i<count($_POST['f_contest']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.contest=?";
                    array_push($filter_array, $_POST['f_contest'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_phase'])){
                for($i=0; $i<count($_POST['f_phase']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.phase=?";
                    array_push($filter_array, $_POST['f_phase'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_teacher'])){
                for($i=0; $i<count($_POST['f_teacher']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.teacher=?";
                    array_push($filter_array, $_POST['f_teacher'][$i]);
                }
                $filter.=")";
            }
        }
        
        $sql=$db->prepare("SELECT r.id, s.fullname AS student, s.class AS class, sb.name_1 AS subject_1, sb.name_2 AS subject_2, c.name_1 AS contest_1, c.name_2 AS contest_2, c.description AS contest_desc, c.ministry_support, c.ministry_place, p.name_1 AS phase_1, p.name_2 AS phase_2, t.fullname AS teacher, r.place, r.mention FROM register AS r INNER JOIN users AS s ON (s.id=r.student) INNER JOIN contests AS c ON (c.id=r.contest) INNER JOIN subjects AS sb ON (sb.id=c.subject) INNER JOIN phases AS p ON (p.id=r.phase) INNER JOIN users AS t ON (t.id=r.teacher) ".$filter." ORDER BY id ASC");
        $sql->execute($filter_array);
        
        echo "
        <table class=\"table\">
            <thead>
                <tr>
                    <th data-breakpoints=\"xs sm md\">".$lang['id']."</th>
                    <th>".$lang['student']."</th>
                    <th>".$lang['class']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['subject_1']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['subject_2']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['contest_1']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['contest_2']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['contest_desc']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['ministry_support']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['ministry_place']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['phase_1']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['phase_2']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['teacher']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['place']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['mention']."</th>
                    <th data-breakpoints=\"xs sm md\">".$lang['tools']."</th>
                </tr>
            </thead>
            <tbody>
        ";
        while($row=$sql->fetch(PDO::FETCH_ASSOC)){
            echo "
            <tr>
                <td>".$row['id']."</td>
                <td>".$row['student']."</td>
                <td>".$row['class']."</td>
                <td>".$row['subject_1']."</td>
                <td>".$row['subject_2']."</td>
                <td>".$row['contest_1']."</td>
                <td>".$row['contest_2']."</td>
                <td>".$row['contest_desc']."</td>
                <td>".$lang['ministry_'.$row['ministry_support']]."</td>
                <td>".($row['ministry_support']==0?"":$row['ministry_place'])."</td>
                <td>".$row['phase_1']."</td>
                <td>".$row['phase_2']."</td>
                <td>".$row['teacher']."</td>
                <td>".($row['place']<0?$lang['places'][$row['place']]:$row['place'])."</td>
                <td>".str_replace(array("\n"), array("<br>"), $row['mention'])."</td>
                <td>
                    <button type=\"button\" onclick=\"registerEdit(".$row['id'].")\">".$lang['edit']."</button>
                    <button type=\"button\" onclick=\"registerDelete(".$row['id'].", this)\">".$lang['delete']."</button>
                </td>
            </tr>
            ";
        }
    }
    
    if(isset($_POST['delete'])){
        $sql=$db->prepare("DELETE FROM register WHERE id=:id");
        $sql->execute(array(":id"=>$_POST['delete']));
        $res=$sql->rowCount();
        if($res>0){
            functions::setMessage(4);
        }
        else{
            functions::setError(4);
        }
    }
    
    if(isset($_POST['new'])){
        $new=array("student"=>$_POST['student'], "contest"=>$_POST['contest'], "phase"=>$_POST['phase'], "teacher"=>$_POST['teacher'], "place"=>($_POST['place']<0?$_POST['place']:$_POST['place_c']), "mention"=>$_POST['mention']);
        
        $sql=$db->prepare("SELECT r.id, p.name_1 AS phase_1, p.name_2 AS phase_2, t.fullname AS teacher, r.place, r.mention FROM register AS r INNER JOIN users AS s ON (s.id=r.student) INNER JOIN phases AS p ON (p.id=r.phase) INNER JOIN users AS t ON (t.id=r.teacher) WHERE r.student=:stud and r.contest=:cont ORDER BY r.id ASC");
        $sql->execute(array(":stud"=>$_POST['student'], ":cont"=>$_POST['contest']));
        $found="";
        while($row=$sql->fetch(PDO::FETCH_ASSOC)){
            $found.="
            <tr>
                <td>".$row['id']."</td>
                <td>".$row['phase_1']."</td>
                <td>".$row['phase_2']."</td>
                <td>".$row['teacher']."</td>
                <td>".($row['place']<0?$lang['places'][$row['place']]:$row['place'])."</td>
                <td>".str_replace(array("\n"), array("<br>"), $row['mention'])."</td>
                <td><button type=\"button\" onclick=\"registerDelete(".$row['id'].", this)\">".$lang['delete']."</button></td>
            </tr>
            ";
        }
        
        $exp=array("params"=>$new, "prev"=>$found);
        echo json_encode($exp);
    }
    
    if(isset($_POST['newSubmit'])){
        $data=json_decode($_POST['newSubmit']);
        $sql=$db->prepare("INSERT INTO register (student, contest, phase, teacher, place, mention, schoolyear) VALUES (:stud, :cont, :phase, :teacher, :place, :mention, :sy)");
        $sql->execute(array(":stud"=>$data->student, ":cont"=>$data->contest, ":phase"=>$data->phase, ":teacher"=>$data->teacher, ":place"=>$data->place, ":mention"=>$data->mention, ":sy"=>$schoolyear));
        $res=$sql->rowCount();
        if($res>0){
            functions::setMessage(3);
        }
        else{
            functions::setError(4);
        }
    }
    
    if(isset($_GET['getdata'])){
        $sql=$db->prepare("SELECT COUNT(id) AS count, id, student, contest, phase, teacher, place, mention FROM register WHERE id=:id");
        $sql->execute(array(":id"=>$_GET['getdata']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        if($res['count']<1){
            functions::setError(6);
        }
        else{
            echo json_encode($res);
        }
    }
    
    if(isset($_POST['edit'])){
        $sql=$db->prepare("SELECT COUNT(id) AS count FROM register WHERE id=:id");
        $sql->execute(array(":id"=>$_POST['edit']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        if($res['count']<1){
            functions::setError(6);
        }
        else{
            $sql=$db->prepare("UPDATE register SET student=:stud, contest=:cont, phase=:phase, teacher=:teacher, place=:place, mention=:mention WHERE id=:id");
            $sql->execute(array(":stud"=>$_POST['student'], ":cont"=>$_POST['contest'], ":phase"=>$_POST['phase'], ":teacher"=>$_POST['teacher'], ":place"=>($_POST['place']<0?$_POST['place']:$_POST['place_c']), ":mention"=>$_POST['mention'], ":id"=>$_POST['edit']));
            $res=$sql->rowCount();
            if($res>0){
                functions::setMessage(5);
            }
            else{
                functions::setError(4);
            }
        }
    }
    
    if(isset($_POST['export'])){
        //allow to run for a long time since this is a long process. 10 minute is more than enough
        set_time_limit(600); 
        
        $filter="WHERE r.id<>0";
        $filter_array=array();
        if(isset($_POST['filter'])){
            if(isset($_POST['f_search'])){
                if($_POST['f_search']!=""){
                    $filter.=" and (s.fullname LIKE ? or c.name_1 LIKE ? or c.name_2 LIKE ? or p.name_1 LIKE ? or p.name_2 LIKE ? or t.fullname LIKE ?)";
                    array_push($filter_array, "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%", "%".$_POST['f_search']."%");
                }
            }
            
            if(isset($_POST['f_student'])){
                for($i=0; $i<count($_POST['f_student']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.student=?";
                    array_push($filter_array, $_POST['f_student'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_contest'])){
                for($i=0; $i<count($_POST['f_contest']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.contest=?";
                    array_push($filter_array, $_POST['f_contest'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_phase'])){
                for($i=0; $i<count($_POST['f_phase']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.phase=?";
                    array_push($filter_array, $_POST['f_phase'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_teacher'])){
                for($i=0; $i<count($_POST['f_teacher']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.teacher=?";
                    array_push($filter_array, $_POST['f_teacher'][$i]);
                }
                $filter.=")";
            }
            
            if(isset($_POST['f_schoolyear'])){
                for($i=0; $i<count($_POST['f_schoolyear']); $i++){
                    if($i==0){
                        $filter.=" and (";
                    }
                    else{
                        $filter.=" or ";
                    }
                    $filter.="r.schoolyear=?";
                    array_push($filter_array, $_POST['f_schoolyear'][$i]);
                }
                $filter.=")";
            }
                    
        }
        
        $sql=$db->prepare("SELECT r.id, s.fullname AS student, s.class AS class, sb.name_1 AS subject_1, sb.name_2 AS subject_2, c.name_1 AS contest_1, c.name_2 AS contest_2, c.description AS contest_desc, c.ministry_support, c.ministry_place, p.name_1 AS phase_1, p.name_2 AS phase_2, t.fullname AS teacher, r.place, r.mention, r.schoolyear FROM register AS r INNER JOIN users AS s ON (s.id=r.student) INNER JOIN contests AS c ON (c.id=r.contest) INNER JOIN subjects AS sb ON (sb.id=c.subject) INNER JOIN phases AS p ON (p.id=r.phase) INNER JOIN users AS t ON (t.id=r.teacher) ".$filter." ORDER BY r.schoolyear ASC, subject_1 ASC, contest_1 ASC, student ASC");
        $sql->execute($filter_array);
        
        //setting up file
        $exp=$BOM;
        $exp.="\"".strtr($config['general']['title'], array("\""=>"\"\""))."\"\n";
        $exp.="\"".strtr($config['general']['org'], array("\""=>"\"\""))."\"\n";
        $exp.="\"".strtr($lang['exported'], array("\""=>"\"\"")).": ".date("Y-m-d H:i:s")."\"\n\n";
        
        //build header
        $header="";
        foreach($_POST['export'] as $e){
            $header.="\"".strtr($lang[$e], array("\"", "\"\""))."\",";
        }
        $header=rtrim($header, ",");
        $exp.=$header."\n";
        
        //build content
        while($row=$sql->fetch(PDO::FETCH_ASSOC)){
            $push="";
            foreach($_POST['export'] as $e){
                if($e=="ministry_support"){
                    $push.="\"".strtr($lang['ministry_'.$row['ministry_support']], array("\""=>"\"\""))."\",";
                }
                else if($e=="ministry_place"){
                    $push.="\"".strtr($row['ministry_support']==0?"":$row['ministry_place'], array("\""=>"\"\""))."\",";
                }
                else if($e=="place"){
                    $push.="\"".strtr($row['place']<0?$lang['places'][$row['place']]:$row['place'], array("\""=>"\"\""))."\",";
                }
                else{
                    $push.="\"".strtr($row[$e], array("\""=>"\"\""))."\",";
                }
            }
            $push=rtrim($push, ",");
            $exp.=$push."\n";
        }
        
        //save it to a temporary file
        $file=tempnam(sys_get_temp_dir(), "resmanExp_");
        file_put_contents($file, $exp);
        
        //return file name for download
        echo $file;
    }
    
    if(isset($_GET['expdownload'])){
        if(!file_exists($_GET['expdownload'])){
            functions::setError(404);
            header("Location: ".$_SERVER['HTTP_REFERER']);
        }
        else{
            //download exported file
            header("Content-type: application/octet-stream");
            header("Content-disposition: attachment; filename='".$config['general']['title']."_export_".date("Y-m-d H-i-s").".csv'");
            readfile($_GET['expdownload']);
            unlink($_GET['expdownload']);
            die();
        }
    }
    
}
catch(Exception $e){
    functions::setError(500);
    error_log($e);
}