<?php

class Pampa_Log {

  /**
   * @var Model_Cms_Logs
   */
  private $modelProjectsLogs;

  /**
   * Singleton instance
   * @var Pampa_Log
   */
  protected static $_instance = null;

  protected function __construct() {

  }

  /**
   * Returns an instance of Frk_Auth_Site
   * Singleton pattern implementation
   * @return Pampa_Log Provides a fluent interface
   */
  public static function getInstance() {
    if (null === self::$_instance) {
      self::$_instance = new Pampa_Log();
      self::$_instance->modelProjectsLogs = new Model_Cms_Logs();
    }

    return self::$_instance;
  }

  public static function log($log = "", $user = NULL) {

    $self = self::getInstance();

    // check for user
    if(empty($user)) {
      // the cms auth
      $authCms = Pampa_Auth_Cms::getInstance();
      if(!$authCms->hasIdentity()) {
        if(!empty($log))
        {
          $ip = 'Desconhecido: '.$self->getRealIpAddr();
          $self->modelProjectsLogs->add($ip, $log);
        }
        return;
      }
      // get the logged user
      $user = $authCms->getIdentity();

      // join the text
      //$text = "User {$user->name} ({$user->id}): ".$log;

      // add to db
      $self->modelProjectsLogs->add($user->name, $log);
    }
  }

  public static function getRealIpAddr()
  {
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
  }
}