<?php

class Log extends Zend_Db_Table_Abstract {
  protected $_referenceMap = array(
    'Lpo' => array(
      'columns'       => 'lpo_id',
      'refTableClass' => 'Lpo',
      'refColumns'    => 'id',
    ),
    'Condition' => array(
      'columns'       => 'condition_id',
      'refTableClass' => 'Condition',
      'refColumns'    => 'id',
    ),
    'Content' => array(
      'columns'       => 'content_id',
      'refTableClass' => 'Content',
      'refColumns'    => 'id',
    )
  );

  public function __construct($acct_id) {
    parent::__construct(array(
      'name' => sprintf(
        Zend_Controller_Front::getInstance()
          ->getParam('config')
          ->db
          ->table
          ->user
          ->log,
        $acct_id
      )
    ));

    $this->acct_id = $acct_id;
  }

  public function insert($data) {
    $data['date'] = new Zend_Db_Expr('now()');

    $config = Zend_Controller_Front::getInstance()->getParam('config');
    if($log_dir = $config->log->dir) {
      $log_dir = $log_dir . date('/Y/m');
      if(!is_dir($log_dir)) {
        mkdir($log_dir, 0777, true);
      }

      file_put_contents(
        $log_dir . '/lpo_' . date('Ymd') . '.log',
        implode(
          "\t",
          array(
            date('Y-m-d H:i:s'),
            'LPO',
            $data['log'],
            $this->acct_id,
            $data['lpo_id'],
            $data['condition_id'],
            $data['content_id']
          )
        ) . "\n",
        FILE_APPEND | LOCK_EX
      );
    }

    return parent::insert($data);
  }

  public function getHourlyStats($log, $stats, $id, $date) {
    $ret = array();

    foreach(
      $this->fetchAll(
        $s = $this->select()
          ->from(
            $this,
            'HOUR(`date`) AS `hour`, COUNT(*) AS count'
          )
          ->where('status != ?', 'deleted')
          ->where("DATE(`date`) = ?", $date->toString('YYYY-MM-dd'))
          ->where("{$stats}_id = ?", $id)
          ->where("log = ?", $log)
          ->group('hour')
          ->order('hour')
      ) as $val
    ) {
      $ret[sprintf('%02d:00', $val->hour)] = $val->count;
    }

    return $ret;
  }

  public function getDailyStats($log, $stats, $id, $date) {
    $ret = array();

    foreach(
      $this->fetchAll(
        $s = $this->select()
          ->from(
            $this,
            'DATE(`date`) AS dt, COUNT(*) AS count'
          )
          ->where('status != ?', 'deleted')
          ->where(
            "DATE(DATE_ADD(?, INTERVAL -1 MONTH)) <= DATE(`date`)",
            $date->toString('YYYY-MM-dd')
          )
          ->where("{$stats}_id = ?", $id)
          ->where("log = ?", $log)
          ->group('dt')
          ->order('dt')
      ) as $val
    ) {
      $ret[$val->dt] = $val->count;
    }

    return $ret;
  }

  public function getMonthlyStats($log, $stats, $id, $date) {
    $ret = array();

    foreach(
      $this->fetchAll(
        $s = $this->select()
          ->from(
            $this,
            'DATE_FORMAT(`date`, "%Y-%m") AS mth, COUNT(*) AS count'
          )
          ->where('status != ?', 'deleted')
          ->where(
            "DATE(DATE_ADD(?, INTERVAL -4 MONTH)) <= DATE(`date`)",
            $date->toString('YYYY-MM-dd')
          )
          ->where("{$stats}_id = ?", $id)
          ->where("log = ?", $log)
          ->group('mth')
          ->order('mth')
      ) as $val
    ) {
      $ret[$val->mth] = $val->count;
    }

    return $ret;
  }

  public function getStats($log, $status, $id, $chart, $date) {
    switch($chart) {
    case 'hourly':
      return $this->getHourlyStats($log, $status, $id, $date);
    case 'daily':
      return $this->getDailyStats($log, $status, $id, $date);
    case 'monthly':
      return $this->getMonthlyStats($log, $status, $id, $date);
    }

    return array();
  }

  public function getUsage() {
    $row = $this->fetchRow(
      $this->select()
        ->from($this, 'COUNT(*) AS count')
        ->where("date_format(`date`, '%Y%m') = date_format(now(), '%Y%m')")
    );
    return $row->count;
  }
}
