<?php
    header("Content-Type:application/json");
    include("../connection.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("email","pwd","contact","position","phone","hash");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
        
    //Inicializamos las variables
    $out = new stdClass();
    $email = $_GET["email"];
    $contact = $_GET["contact"];
    $position = $_GET["position"];
    $phone = $_GET["phone"];
    $hash = $_GET["hash"];
    $pwd = $_GET["pwd"];
    $phonesecundary = $_GET["phonesecundary"] == "null" ? null : $_GET["phonesecundary"];
    $contactalt = $_GET["contactalt"] == "null" ? null : $_GET["contactalt"];
    $positionalt = $_GET["positionalt"] == "null" ? null : $_GET["positionalt"];
    $emailalt = $_GET["emailalt"] == "null" ? null : $_GET["emailalt"];
    $phonealt = $_GET["phonealt"] == "null" ? null : $_GET["phonealt"];
    $sessid = randomString(32);
    $groups = '';
    
    if(isset($_GET['groups']) && $_GET['groups'] != ''){
        $groups = $_GET['groups'];
    }
    
    //Actualizamos los datos del colegio
    $sql =  "UPDATE schools " .
            "SET    email = '" . $email . "', ".
            "       contact = '". $contact ."', ".
            "       phone = '". $phone ."', ".
            "       position = '". $position . "', ".
            "       phonesecundary = '".$phonesecundary."', ".
            "       contactalt ='".$contactalt."', ".
            "       positionalt = '".$positionalt."', ".
            "       emailalt = '".$emailalt."', ".
            "       phonealt ='".$phonealt."', ".
            "       asociations = '".$groups."', ".
            "       hashregister = NULL ";
            
    //Si el hash es 1 significa que ya esta ingresado, si no debemos verificar por el hash
    if($hash == 1){
        $sql= $sql." WHERE hashregister is null AND email='".$email."'";
    }else{
        $sql = $sql." WHERE hashregister='".$hash."' AND email='".$email."'";
    }
            
    if (!$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Si es actualizacion de datos del colegio, actualizamos el nombre del usuario
    if($_GET["hash"] == 1){
        $sql = "UPDATE users SET name = '".$contact."'".
        "       WHERE email='".$email."'";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $sql =  "SELECT  name, private ".
            "FROM    schools ".
            "WHERE   email='".$email."' ";
            
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $row = $rs->fetch_assoc();
        $out->school = new stdClass();
        $out->school->id = $schoolid;
        $out->school->name = $row["name"];
        $out->school->private = ($row["private"] == 1 ? true : false);
    
        header("HTTP/1.1 200");
        echo (json_encode($out));
        die();
    }
    
    //Si el correo ya esta asociado a un colegio
    $sql =  "SELECT  *".
        "FROM    users ".
        "WHERE   UPPER(email)='".strtoupper($email)."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row= $rs->fetch_assoc();
    
    if($row["email"] != null){
        badEnd("409", array("msg"=>"Ya este correo se encuentra asociado a un colegio!"));
    }
    
    //Consultamos el id del colegio para colocarlo en el registro del usuario
    $sql =  "SELECT  id ".
        "FROM    schools ".
        "WHERE   UPPER(email)='".strtoupper($email)."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row= $rs->fetch_assoc();
    $schoolid=$row["id"];
    
    //Insertamos el nuevo usuario
    $sql =  "INSERT INTO users (email, name, pwd, sessionid, validthru, status, schoolid) ".
            "       VALUES ('".$email."', ".
            "       '".$contact."', ".
            "       '".$pwd."', ".
            "       '".$sessid."', ".
            "       DATE_ADD(NOW(), INTERVAL 1 DAY),".
            "       1,".
            "       '".$schoolid."')";
            
    if (!$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $sql =  "SELECT  id, sessionid, DATE_FORMAT(validthru, '%Y%m%d%H%i%s') vt, name, schoolid ".
            "FROM    users ".
            "WHERE   UPPER(email)='".strtoupper($email)."' ".
            "AND     pwd='".$pwd."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row= $rs->fetch_assoc();
    
    $out->id = (integer) $row["id"];
    $out->sessionid = $row["sessionid"];
    $out->validthru = $row["vt"];
    $out->name = $row["name"];
    
    $out->school = new stdClass();
    $schoolid = $row["schoolid"];
    
    $sql =  "SELECT  name, private ".
            "FROM    schools ".
            "WHERE   id=".$schoolid." ";
            
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $out->school->id = $schoolid;
    $out->school->name = $row["name"];
    $out->school->private = ($row["private"] == 1 ? true : false);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>