<?php

/* 
 * Objeto para leer y escribir datos de log de intentos de asistencia realizadas por el usuario
 */
define("MAX_LINES", 200);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// timezone de Ciudad de México
date_default_timezone_set('America/Mexico_City');

require_once "vendor/autoload.php";

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

# die(json_encode($_ENV));

class LogAsistencias {
    //put your code here
    private $file, $month, $year;
    private $dir;
    
    function __construct(){
        $this->month = date("m");
        $this->year = date("Y");
        $this->dir = './log/';
        $this->updateFilename();
    }
    
    function setMes($mes){
        $this->month = $mes;
        $this->updateFilename();
    }
    function setAno($ano){
        $this->year = $ano;
        $this->updateFilename();
    }
    
    private function updateFilename(){
        $this->file = "asistencias_".$this->year."_".$this->month.".log";
    }
    private function cleanLog($text){//remueve || de los textos
        return trim(str_ireplace( "||" , "" , $text));
    }
    
    function appendLog($claveULSA, $nombre, $desc){
        $filename = $this->dir.$this->file;
        
        if (!file_exists($this->dir)){
            mkdir($this->dir, 0755, true);
        }
        if (file_exists($this->dir)){
            $data = date('Y-m-d H:i:s')."||".$this->cleanLog($claveULSA)."||".$this->cleanLog($desc)."||".$this->cleanLog($nombre)."\n";
            file_put_contents($filename, $data, FILE_APPEND);
        }
    }
    function getLog($mes ="", $ano = ""){
        if($mes != "") $this->setMes($mes);
        if($ano != "") $this->setAno($ano);
        $filename = $this->dir.$this->file;
        if (file_exists($filename)){
            //return array_slice(file ($filename , FILE_SKIP_EMPTY_LINES) , -10);
            $lines = file ($filename , FILE_SKIP_EMPTY_LINES);
            //echo "antes: ".count($lines);
            if(count($lines) > MAX_LINES){ $lines = array_slice($lines, MAX_LINES*(-1)); }
            //echo "despues: ".count($lines);
            return $lines;
        }else{
            return array();
        }
    }
}
