<?php
    header("Content-Type:application/json");
    include("../connection.php");
    include("../utils.php");
    
    //Parametros obligatorios
    $parmsob = array("sessionid","id","schoolid","name","surname","gender","birthdate","level","section");
    if (!parametrosValidos($_POST, $parmsob))
        badEnd("400", array("msg"=>"Parametros invalidos " . implode(", ", $parmsob)));
        
    //Inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = $_POST["sessionid"];
    $id = $_POST["id"];
    $schoolid = $_POST["schoolid"];
    $name = $_POST["name"];
    $surname = $_POST["surname"];
    $ci = $_POST["ci"];
    $gender = $_POST["gender"];
    $birthdate = $_POST["birthdate"];
    $level = $_POST["level"];
    $section = $_POST["section"];
    
    //Validamos que la session sea valida para continuar
    isSessionValid($db, $sessionid);
    
    
    //Si es 0 insertamos un nuevo registro, si no actualizamos
    if($id != 0){
        $sql = "UPDATE pupils SET name='".$name."', ".
        "       surname='".$surname."', ".
        "       ci='".$ci."', ".
        "       gender='".$gender."', ".
        "       birthdate='".$birthdate."', ".
        "       level=".$level.", ".
        "       section='".$section."' ".
        "       WHERE id=".$id." AND schoolid=".$schoolid."";
        
        if (!$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
        if ($db->affected_rows == 0){
            badEnd("404",array("msg"=>"No se pudo modificar"));
        }
        
    }else{
        
        //Validamos que sea privado
        $sql = "SELECT private FROM schools WHERE id = ".$schoolid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $rs->fetch_assoc();
        
        // Validamos que sea privado
        if($row['private'] == 1){
            // Obtenemos la cantidad de alumnos registrados
            $sql = "SELECT COUNT(id) AS qty FROM pupils WHERE schoolid=".$schoolid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $registered = $rs->fetch_assoc();
            
            // SI es privado obtenemos la cantidad estimada y validamos que no pase la data que trae
            $sql = "SELECT SUM(qty) as qty FROM estimatedpupils WHERE schoolid=".$schoolid;
            if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $estimated = $rs->fetch_assoc();
            
            // Obtenemos la cantidad de registros nuevos
            $arrName = explode('~',$name);
            
            if($estimated['qty'] < (sizeof($arrName) + $registered['qty'])){
                badEnd("402",array("msg"=>"Limite excedido"));
            }
        }
        
        $sql = "INSERT INTO pupils (schoolid, name, surname, ci, gender, birthdate, level, section) ".
        "       VALUES ".insertVal($schoolid,$name,$surname,$ci,$gender,$birthdate,$level,$section);
        
        $sql = rtrim($sql, ", ");
        
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
    }
        
    $out->id = $id;
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();  
    
    function insertVal($schoolid,$name,$surname,$ci,$gender,$birthdate,$level,$section){
        $arrname = explode('~',$name);
        $arrsurname = explode('~',$surname);
        $arrci = explode('~',$ci);
        $arrgender = explode('~',$gender);
        $arrbirthdate = explode(',',$birthdate);
        $arrlevel = explode('~',$level);
        $arrsection = explode('~',$section);
        $len = sizeof($arrci);
        $str = "";
        for($i = 0; $i < $len; $i ++){
            $str = $str."( ".$schoolid.", '".determinateApos($arrname[$i])."', '".determinateApos($arrsurname[$i])."', '".$arrci[$i]."','".$arrgender[$i]."', '".$arrbirthdate[$i]."',".$arrlevel[$i].",'".$arrsection[$i]."'),";
        }
        
        return $str;
    }
    
    function determinateApos($names){
        
        return str_replace("'","\'",$names);
    }
    
?>
