<?php
    header("Content-Type:application/json");
    include("../connection.php");
    include("../utils.php");
    
    //Parametros obligatorios
    $parmsob = array("ssid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros invalidos " . implode(", ", $parmsob)));
        
    //Inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = $_GET["ssid"];
    
    //Validamos que la session sea valida para continuar
    isSessionValid($db, $sessionid);
    
    //Consultamos los datos de la escuela
    $sql = "SELECT schools.id,schools.name, schools.code, ".
    "           schools.events AS events, ".
    "           schools.modality AS modality, ".
        "       schools.region,schools.private,".
        "       schools.email,schools.contact,".
        "       schools.phone,schools.position, schools.phonesecundary,".
        "       schools.contactalt, schools.positionalt,".
        "       schools.emailalt, schools.phonealt,".
        "       schools.asociations, ".
        "       schools.estimatedpupilsedit".
        "       FROM `schools`,`users` ".
        "       WHERE users.sessionid = '".$sessionid."'".
        "       AND schools.id = users.schoolid";
        
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row= $rs->fetch_assoc();
    
    //Ordenamos los datos
    $out->id = (int)$row["id"];
    $out->code = $row["code"];
    $out->name = $row["name"];
    $out->region = new stdClass();
    $out->region->name = $row["region"];
    $out->privat = ($row["private"] == 1 ? true : false);
    $out->email = $row["email"];
    $out->contact = $row["contact"];
    $out->phone = $row["phone"];
    $out->phonesecundary = $row["phonesecundary"];
    $out->contactalt = $row["contactalt"];
    $out->positionalt = $row["positionalt"];
    $out->emailalt = $row["emailalt"];
    $out->phonealt = $row["phonealt"];
    $out->position = $row["position"];
    $out->asociations = $row['asociations'];
    $out->editlocked = ($row["estimatedpupilsedit"] == 1 ? true : false);
    if ($row['modality'] == null) {
        $out->modality = null;
    } else {
        $out->modality = $row['modality'] == 1 ? 'Online' : 'Presencial';
    }
    
    $out->events = ($row['events'] == null ? null : explode('|', $row['events']));
    
    //Aqui se cambia el precio por alumno
    
    // Consultamos el precio por alumno
    $sql = "SELECT content FROM settings WHERE id = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $out->price = new stdClass();
    $out->price->amount = (float)$row['content'];
    
    //Obtenemos el estimado de alumnos
    $sql = "SELECT estimatedpupils.id, estimatedpupils.level, ".
    "       estimatedpupils.section, estimatedpupils.qty ".
    "       FROM `estimatedpupils`,`users` ".
    "       WHERE users.sessionid = '".$sessionid."' ".
    "       AND estimatedpupils.schoolid = users.schoolid";
        
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Ordenamos el estimado por cada grado
    $out->estimatedpupils = new stdClass();
    $out->estimatedpupils->grade1 = new stdClass();
    $out->estimatedpupils->grade2 = new stdClass();
    $out->estimatedpupils->grade3 = new stdClass();
    $out->estimatedpupils->grade4 = new stdClass();
    $out->estimatedpupils->grade5 = new stdClass();
    $out->estimatedpupils->grade6 = new stdClass();
        
    while($row = $rs->fetch_assoc()){
        if($row["level"] == 1){
            $grade = "grade1";
        }else if($row["level"] == 2){
            $grade = "grade2";
        }else if($row["level"] == 3){
            $grade = "grade3";
        }else if($row["level"] == 4){
            $grade = "grade4";
        }else if($row["level"] == 5){
            $grade = "grade5";
        }else if($row["level"] == 6){
            $grade = "grade6";
        }else if ($row["level"] == null){
            break;
        }
        
        if($row["section"] == "A"){
            $section = "sectionA";
        }else if($row["section"] == "B"){
            $section = "sectionB";
        }else if($row["section"] == "C"){
            $section = "sectionC";
        }else if($row["section"] == "D"){
            $section = "sectionD";
        }else if($row["section"] == "E"){
            $section = "sectionE";
        }else if($row["section"] == "F"){
            $section = "sectionF";
        }else if($row["section"] == "G"){
            $section = "sectionG";
        }else if($row["section"] == "H"){
            $section = "sectionH";
        }else if($row["section"] == "I"){
            $section = "sectionI";
        }else if($row["section"] == "J"){
            $section = "sectionJ";
        }
    
        $out->estimatedpupils->$grade->$section = $row["qty"];
    }
    
    // Validamos los pagos del usuario, que tenga alumnos en estos
    $sql = "SELECT MAX(pupilqty) AS qty ".
    "       FROM payments ".
    "       WHERE schoolid = ".$out->id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    /*
    // Si es 0, el formato es viejo
    if($row['qty'] == 0){
        $out->test = "formato viejo";
    }*/
        
    //Obtenemos los datos del pago
    $sql = "SELECT payments.id, payments.validated, ".
    "       payments.currency, ".
    "       payments.account, payments.date,".
    "       payments.ref, payments.rif, ".
    "       payments.type, payments.amount, ".
    "       payments.due AS due, ".
    "       payments.pupilqty AS pupilqty ".
    "       FROM `payments`,`users` ".
    "       WHERE users.sessionid = '".$sessionid."' ".
    "       AND payments.schoolid = users.schoolid";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Ordenamos los datos de pago
    $out->payment = [];
    $groupsqty = 0;
    $groups = [];
    
    while($row = $rs->fetch_assoc()){
        
        $payment = new stdClass();
        $payment->id = (int)$row["id"];
        $payment->validated = ($row["validated"] == 1 ? true : false);
        $payment->account = $row["account"];
    
        $payment->datepay = new stdClass();
        $dateFormat = strtotime($row["date"]);
        $payment->datepay->short = $row["date"];
        $payment->datepay->row = date("Y",$dateFormat).date("m",$dateFormat).date("d",$dateFormat);
        $payment->datepay->long = date("d",$dateFormat)." de ".getMonth(date("m",$dateFormat))." de ".date("Y",$dateFormat);
    
        $payment->ref = $row["ref"];
        $payment->rif = $row["rif"];
        $payment->type = new stdClass();
        $payment->type->id = $row["type"];
        $payment->type->dsc = determinateType($row['type']);
        $payment->amount = new stdClass();
        $payment->amount->number = $row["amount"]; 
        $payment->amount->formatted = number_format($row["amount"], 2, ",", ".");
        $payment->due = new stdClass();
        $payment->due->number = (float)$row['due'];
        $payment->due->formatted = number_format($row["due"], 2, ",", ".");
        $payment->currencyid = (int)$row['currency'];
        $payment->pupilqty = (int)$row['pupilqty'];
        
        if($groupsqty == 0 && sizeof($groups) == 0){
            $groups[$groupsqty] = new stdClass();
            
            $groups[$groupsqty]->due = $payment->due->number;
            $groups[$groupsqty]->date = $dateFormat;
            $groups[$groupsqty]->pupilqty = $payment->pupilqty;
            
            $payment->group = $groupsqty + 1;
        }
        
        
        if($groups[$groupsqty]->due == $payment->due->number && $groups[$groupsqty]->date == $dateFormat){
            $payment->group = $groupsqty + 1;
        }else{
            $groupsqty++;
            
            $groups[$groupsqty] = new stdClass();
            
            $groups[$groupsqty]->due = $payment->due->number;
            $groups[$groupsqty]->date = $dateFormat;
            $groups[$groupsqty]->pupilqty = $payment->pupilqty;
            
            $payment->group = $groupsqty + 1;
            
        }
        
        $payments [] = $payment;
    }
    
    $out->payment = $payments;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    
    function getMonth($mt){
        $month = "";
        
        switch ($mt) {
            case 1:
                $month = "Enero";
                break;
            case 2:
                $month = "Febrero";
                break;
            case 3:
                $month = "Marzo";
                break;
            case 4:
                $month = "Abril";
                break;
            case 5:
                $month = "Mayo";
                break;
            case 6:
                $month = "Junio";
                break;
            case 7:
                $month = "Julio";
                break;
            case 8:
                $month = "Agosto";
                break;
            case 9:
                $month = "Septiembre";
                break;
            case 10:
                $month = "Octubre";
                break;
            case 11:
                $month = "Noviembre";
                break;
            case 12:
                $month = "Diciembre";
                break;
        }
        return $month;
    }
    
    function determinateType($type){
        $str = '';
        
        switch($type){
            case 1:
                $str = 'Mismo banco';
                break;
            case 2:
                $str = "Otro banco";
                break;
        }
        
        return $str;
    }
?>