<?php
    header("Content-Type: application/csv;");
    header("Content-Disposition: attachment; filename=studentdata.csv");
    //header("Content-Type: application/json;");
    include("../connection.php");
    include("../utils.php");
    
    //Parametros obligatorios
    $parmsob = array("sessionid","schoolid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros invalidos " . implode(", ", $parmsob)));
        
    //Inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $schoolid = $_GET["schoolid"];
    
    //Validamos que la session sea valida para continuar
    isSessionValid($db, $sessionid);
    
    //Obtenemos los codigos de los estudiantes
    $sql = "SELECT CONCAT(LPAD(pupils.id,'7','0'),RIGHT(CRC32(pupils.id),2)) as code FROM pupils".
    "       WHERE pupils.schoolid = ".$schoolid.
    "       ORDER BY pupils.id ASC ";
     if (!$coders=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Obtenemos los datos de los estudiantes
    $sql = "SELECT pupils.id, pupils.birthdate, ".
    "       pupils.name, pupils.surname, ".
    "       pupils.ci, pupils.gender, ".
    "       pupils.section, pupils.level ".
    "       FROM pupils ".
    "       WHERE pupils.schoolid = ".$schoolid.
    "       ORDER BY pupils.id ASC ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Ordenamos los datos de los estudiantes
    while($student= $rs->fetch_assoc()){
        $code = $coders->fetch_assoc();
        $record = new stdClass();
        $record->code = $code["code"];
        $record->id = $student["id"];
        $record->ci = $student["ci"];
        $record->name = $student["name"];
        $record->surname = $student["surname"];
        $record->gender = new stdClass();
        $record->gender->id = $student["gender"];
        $record->gender->dsc = $student["gender"] == "M" ? "Masculino" : "Femenino";
        
        $dateFormat = strtotime($student["birthdate"]);
    
        $record->birthdate = new stdClass();
        $record->birthdate->date = date("Y",$dateFormat).date("m",$dateFormat).date("d",$dateFormat);
        $record->birthdate->formatted = $student["birthdate"];
        $record->level = $student["level"];
        $record->grade = $student["section"];
        
        $records [] = $record;
        
        $csvarray [] = array(
            'ID' => $record->code,
            'Grado' => $record->grade,
            'Sección' => $record->level,
            'Nombre' => $record->name,
            'Apellido' => $record->surname,
            'Cédula' => $record->ci,
            'Fechanacimiento' => $record->birthdate->formatted,
            'Género' => $record->gender->id
        );
    }
    
    $out->records = $records;
    
    $fp = fopen('php://output', 'wb');
    fwrite($fp, $BOM);
    
    $line = array('ID','Grado','Sección','Nombre','Apellido','Cédula','Fecha de nacimiento','Género');
    
    fputcsv($fp, $line, ';', '"');
    
    foreach($csvarray as $arr){
        fputcsv($fp,$arr,';');
    }
    
    fclose($fp);
    
    echo json_decode($csvarray);
    
    die();
?>