<?php

define('BASE_DIR', dirname(__FILE__).'/');
define('LIB_DIR', BASE_DIR.'../lib');
define('ZEND_DIR', BASE_DIR.'../lib/ZFlib');
define('MODEL_DIR', BASE_DIR.'../application/models');
define('CONFIG_INI', BASE_DIR.'../config.ini');

ini_set(
  'include_path',
  ini_get('include_path').
  PATH_SEPARATOR.
  LIB_DIR.
  PATH_SEPARATOR.
  ZEND_DIR.
  PATH_SEPARATOR.
  MODEL_DIR
);

require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

function main() {
  echo "***** necosuke lpo daily.php: " . date('Y-m-d H:i:s') . " *****\n";

  mb_internal_encoding('UTF-8');
  mb_language('Japanese');

  #Zend_Session::regenerateId();

  $config = new Zend_Config_Ini(CONFIG_INI, 'production');
  Zend_Controller_Front::getInstance()->setParam('config', $config);

  $db = Zend_Db::factory($config->db->adapter, $config->db->config->toArray());
  $db->query('SET NAMES UTF8');
  Zend_Db_Table_Abstract::setDefaultAdapter($db);

  echo "cleaning registration: ";
  $rgst_t = new Registration();
  $num = $rgst_t->delete(
    $rgst_t->getAdapter()->quoteInto(
      'DATE(`date`) < DATE(DATE_ADD(NOW(), INTERVAL -3 DAY))',
      null
    )
  );
  echo "num rows = {$num}\n";

  echo "cleaning reminder: ";
  $rmdr_t = new Reminder();
  $num = $rmdr_t->delete(
    $rmdr_t->getAdapter()->quoteInto(
      'DATE(`date`) < DATE(DATE_ADD(NOW(), INTERVAL -3 DAY))',
      null
    )
  );
  echo "num rows = {$num}\n";

  $acct_t = new Account();
  foreach(
    $acct_t->fetchAll(
      $acct_t->select()->where('status = ?', 'active')->order('id')
    ) as $acct
  ) {
    echo "cleaning log({$acct->id}): ";
    $log_t = new Log($acct->id);
    $num = $log_t->delete(
      $log_t->getAdapter()->quoteInto(
        'DATE(`date`) < DATE(DATE_ADD(NOW(), INTERVAL -4 MONTH))',
        null
      )
    );
    echo "num rows = {$num}\n";
  }

  echo "***** necosuke lpo daily.php: " . date('Y-m-d H:i:s') . " *****\n";
}

main();
