<?php

/**
 * Log selected action in database with ip, datetime and optional logged user.
 * @author valentin carruesco
 * @category Core
 * @license copyright
 */

class Log extends Entity
{
    public $id,$label,$category,$ip;
    protected $fields =
    array(
        'id' => 'key',
        'label' => 'longstring',
        'category' => 'string',
        'ip' => 'string',
        );

    public function label(){
        return preg_replace_callback('|^\[([^\]]*)\](.*)|i', function($matches){
            return '<span class="badge badge-info">'.$matches[1].'</span>'.$matches[2];
        }, $this->label);
    }

    public static function put($label,$category = 'Général') {
        global $myUser;
        $log = new self();
        $log->label = $label;
        $log->category = $category;
        $log->ip = ip();
        $log->save();
    }

    //Compare deux instances d'une même entité et log les differences entr eles deux dans un format json
    public static function compare($old,$new = null,$metafunction=null){
        global $myUser;

       
        $log = new self();
        $log->label = array();

        if(!isset($new) || !isset($old->id) || $old->id==0){
            $log->label['action'] = 'create';
            $log->label['fields'] = is_object($new) ? $new->toArray(): $old->toArray();
        }else if (!$new){
            $log->label['action'] = 'delete';
            $log->label['fields'] = $old->toArray();
        }elseif (is_object($new)){
            $log->label['action'] = 'update';
            $log->label['fields'] = Entity::compare($old,$new);
        }
    
        $log->label['entity'] = $old->tableName();
        
        
        $log->category = $log->label['entity'].'::compare';
        $log->ip = ip();

        if(isset($metafunction))
            $metafunction($log);
        

        $log->label = json_encode($log->label);
        $log->save();

    }

    public static function clear($delay = 1){
       $treshold = time() - ($delay * 86400);
       self::delete(array('created:<'=>$treshold));
    }
}
