<?php

require_once('php-ofc-library/open_flash_chart_object.php');
require_once('php-ofc-library/open-flash-chart.php');

class IndexController extends Zend_Controller_Action {
  ////////////////////////////////////////////////////////////////////////////
  //
  // SessionMessage
  //
  ////////////////////////////////////////////////////////////////////////////
  public function setSessionMessage($msg) {
    $s = new Zend_Session_Namespace('sessionMessage');
    $s->setExpirationHops(1);
    $s->msg = $msg;
  }

  public function getSessionMessage() {
    $s = new Zend_Session_Namespace('sessionMessage');
    return $s->msg;
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Form
  //
  ////////////////////////////////////////////////////////////////////////////
  public function getLpoForm() {
    $form = new Zend_Form;

    $form->setMethod('post');

    $name = $form->createElement(
      'text',
      'name',
      array('label' => 'LPO の名称')
    );
    $name->setRequired(true);

    $selector = $form->createElement(
      'text',
      'selector',
      array('label' => 'ランディングページで LPO コンテンツを表示する場所の指定')
    );
    $selector->setRequired(true);

    $landing_url = $form->createElement(
      'text',
      'landing_url',
      array('label' => 'ランディングページの URL')
    );
    $landing_url->setRequired(true);

    $conversion_url = $form->createElement(
      'text',
      'conversion_url',
      array('label' => 'コンバージョンページの URL')
    );
    $conversion_url->setRequired(true);

    $active = $form->createElement(
      'checkbox',
      'active',
      array('label' => '登録を有効にする')
    );

    $submit = $form->createElement(
      'submit',
      'submit',
      array('label' => '登録')
    );

    $form->addElement($name);
    $form->addElement($selector);
    $form->addElement($landing_url);
    $form->addElement($conversion_url);
    $form->addElement($active);
    $form->addElement($submit);

    return $form;
  }

  public function getConditionForm() {
    $form = new Zend_Form;

    $form->setMethod('post');

    $condition = $form->createElement(
      'select',
      'condition',
      array('label' => '表示条件')
    );
    $condition->setRequired(true);
    $condition->addMultiOption('all',      '必ず表示する');
    $condition->addMultiOption('keyword',  '検索キーワード');
    #$condition->addMultiOption('referrer', 'リファラー');
    #$condition->addMultiOption('query',    'パラメータ');

    $value = $form->createElement(
      'text',
      'value',
      array('label' => '内容')
    );

    $active = $form->createElement(
      'checkbox',
      'active',
      array('label' => '登録を有効にする')
    );

    $submit = $form->createElement(
      'submit',
      'submit',
      array('label' => '登録')
    );

    $form->addElement($condition);
    $form->addElement($value);
    $form->addElement($active);
    $form->addElement($submit);

    return $form;
  }

  public function getContentForm() {
    $form = new Zend_Form;

    $form->setMethod('post');

    $name = $form->createElement(
      'text',
      'name',
      array('label' => '名称')
    );
    $name->setRequired(true);

    $rate = $form->createElement(
      'text',
      'rate',
      array('label' => '表示割合')
    );
    $rate->setRequired(true);

    $content = $form->createElement(
      'textarea',
      'content',
      array('label' => 'LPO コンテンツ')
    );

    $active = $form->createElement(
      'checkbox',
      'active',
      array('label' => '登録を有効にする')
    );

    $submit = $form->createElement(
      'submit',
      'submit',
      array('label' => '登録')
    );

    $form->addElement($name);
    $form->addElement($rate);
    $form->addElement($content);
    $form->addElement($active);
    $form->addElement($submit);

    return $form;
  }

  public function getDeleteForm() {
    $form = new Zend_Form;

    $form->setMethod('post');
    $submit = $form->createElement(
      'submit',
      'submit',
      array('label' => '削除')
    );
    $form->addElement($submit);

    return $form;
  }

  public function getAccountForm() {
    $form = new Zend_Form;

    $name = $form->createElement(
      'text',
      'name',
      array('label' => 'お名前')
    );
    $name->setRequired(true);

    $email = $form->createElement(
      'text',
      'email',
      array('label' => 'メールアドレス')
    );
    $email->setRequired(true);
    $email->addValidator('EmailAddress');

    $password = $form->createElement(
      'password',
      'password',
      array('label' => 'パスワード (変更する場合は入力してください)')
    );

    $submit = $form->createElement(
      'submit',
      'submit',
      array('label' => '登録')
    );

    $form->addElement($name);
    $form->addElement($email);
    $form->addElement($password);
    $form->addElement($submit);

    return $form;
  }

  public function getLpoTagForm() {
    $config = Zend_Controller_Front::getInstance()->getParam('config');

    $this->view->base_url = $config->base_url;
    $this->view->hash     = $this->acct->hash;

    $form = new Zend_Form;
    $tag = $form->createElement(
      'textarea',
      'tag',
      array('wrap' => 'off')
    );
    $tag->setValue($this->view->render($config->lpo->tag->template));
    $form->addElement($tag);

    return $form;
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // getChartParam
  //
  ////////////////////////////////////////////////////////////////////////////
  public function getChartParam($default='hourly') {
    switch($chart = $this->getRequest()->getParam('chart', $default)) {
      case 'hourly':
      case 'daily':
      case 'monthly':
        break;
      default:
        $chart = $default;
    }

    return $chart;
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // getDateParam
  //
  ////////////////////////////////////////////////////////////////////////////
  public function getDateParam() {
    $date = $this->getRequest()->getParam('date', date('Y-m-d'));
    if(!Zend_Date::isDate($date, 'YYYY-MM-dd')) {
      $date = date('Y-m-d');
    }

    list($y, $m, $d) = explode('-', $date);

    return new Zend_Date(array('year' => $y, 'month' => $m, 'day' => $d));
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // getYesterday
  //
  ////////////////////////////////////////////////////////////////////////////
  public function getYesterday() {
    $date = new Zend_Date();
    $date->sub('01', Zend_Date::DAY);
    return $date->toString('YYYY-MM-dd');
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Dispatch
  //
  ////////////////////////////////////////////////////////////////////////////
  public function preDispatch() {
    if(!Zend_Auth::getInstance()->hasIdentity()) {
      return $this->_redirect('/account/login');
    }

    $acct_t = new Account();
    $this->acct = $acct_t->fetchRow(
      $acct_t->select()
        ->where('status = ?', 'active')
        ->where(
          'email = ?',
          Zend_Auth::getInstance()->getIdentity()
        )
    );

    if(!$this->acct) {
      Zend_Auth::getInstance()->clearIdentity();
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Menu
  //
  ////////////////////////////////////////////////////////////////////////////
  public function menuAction() {
    $this->view->action = $this->getRequest()->getParam('action');
    $this->view->list = $this->acct->findDependentRowset(
      'Lpo',
      null,
      $this->acct
        ->getTable()
        ->select()
        ->where('status != ?', 'deleted')
        ->order('name')
    );
    $this->render(null, 'menu');
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Msg
  //
  ////////////////////////////////////////////////////////////////////////////
  public function msgAction() {
    $this->view->msg = $this->getSessionMessage();
    $this->render(null, 'msg');
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Index
  //
  ////////////////////////////////////////////////////////////////////////////
  public function indexAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $this->view->chart     = $this->getChartParam();
    $this->view->date      = $this->getDateParam()->toString('YYYY-MM-dd');
    $this->view->yesterday = $this->getYesterday();
    $this->view->list      = $this->acct->findDependentRowset(
      'Lpo',
      null,
      $this->acct
        ->getTable()
        ->select()
        ->where('status != ?', 'deleted')
        ->order('name')
    );

    if(count($this->view->list) == 0) {
      $this->view->form = $this->getLpoTagForm();
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // LPO
  //
  ////////////////////////////////////////////////////////////////////////////
  public function lpoAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $lpo_t = new Lpo();
    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->chart     = $this->getChartParam();
    $this->view->date      = $this->getDateParam()->toString('YYYY-MM-dd');
    $this->view->yesterday = $this->getYesterday();
    $this->view->lpo       = $lpo;
    $this->view->list      = $lpo->findDependentRowset(
      'Condition',
      null,
      $lpo_t->select()->where('status != ?', 'deleted')->order('priority')
    );
  }

  public function lpoCreateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $form = $this->getLpoForm();
    $form->setAction('/index/lpo-create-submit');
    $form->getElement('name')->setValue('LPO登録名称 ' . date('Y-m-d'));
    $form->getElement('selector')->setValue('#LPO');
    $form->getElement('landing_url')->setValue('http://');
    $form->getElement('conversion_url')->setValue('http://');
    $form->getElement('active')->setValue(true);

    $this->view->form = $form;
  }

  public function lpoCreateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-create');
    }

    $form = $this->getLpoForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-create-submit');
      $this->view->form = $form;
      return $this->render('lpo-create');
    }

    $lpo_t = new Lpo();
    $lpo = $lpo_t->createRow();
    if($form->getElement('active')->getValue()) {
      $lpo->status = 'active';
    } else {
      $lpo->status = 'inactive';
    }
    $lpo->account_id     = $this->acct->id;
    $lpo->name           = $form->getElement('name')->getValue();
    $lpo->selector       = $form->getElement('selector')->getValue();
    $lpo->landing_url    = $form->getElement('landing_url')->getValue();
    $lpo->conversion_url = $form->getElement('conversion_url')->getValue();
    $lpo->save();

    $this->setSessionMessage('新しい LPO が登録されました。');

    $this->_redirect('/index/lpo/id/' . $lpo->id);
  }

  public function lpoUpdateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    $form = $this->getLpoForm();
    $form->setAction('/index/lpo-update-submit/id/' . $id);

    $form->getElement('active')->setValue($lpo->status == 'active');
    $form->getElement('name')->setValue($lpo->name);
    $form->getElement('selector')->setValue($lpo->selector);
    $form->getElement('landing_url')->setValue($lpo->landing_url);
    $form->getElement('conversion_url')->setValue($lpo->conversion_url);

    $this->view->action = $this->getRequest()->getParam('action');
    $this->view->form   = $form;
    $this->view->lpo    = $lpo;
  }

  public function lpoUpdateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-update');
    }

    $form = $this->getLpoForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-update-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-update');
    }

    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    if($form->getElement('active')->getValue()) {
      $lpo->status = 'active';
    } else {
      $lpo->status = 'inactive';
    }
    $lpo->name           = $form->getElement('name')->getValue();
    $lpo->selector       = $form->getElement('selector')->getValue();
    $lpo->landing_url    = $form->getElement('landing_url')->getValue();
    $lpo->conversion_url = $form->getElement('conversion_url')->getValue();
    $lpo->save();

    $this->setSessionMessage('登録内容が変更されました');

    $this->_redirect('/index/lpo-update/id/' . $id);
  }

  public function lpoDeleteAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    $form = $this->getDeleteForm();
    $form->setAction('/index/lpo-delete-submit/id/' . $id);

    $this->view->action = $this->getRequest()->getParam('action');
    $this->view->form   = $form;
    $this->view->lpo    = $lpo;
  }

  public function lpoDeleteSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-delete');
    }

    $form = $this->getDeleteForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-delete-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-delete');
    }

    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
    $db->beginTransaction();
    try {
      $lpo = $this->acct->getLpo($id);
      if(!$lpo) {
        $this->_redirect('/');
      }

      $lpo->del();
      $lpo->save();

      $log_t = new Log($this->acct->id);
      $log_t->update(
        array('status' => 'deleted'),
        $log_t->getAdapter()->quoteInto('lpo_id = ?', $lpo->id)
      );

      $db->commit();
    } catch(Exception $e) {
      $db->rollBack();
      throw $e;
    }

    $this->setSessionMessage('LPO が削除されました');
    $this->_redirect('/index');
  }

  public function getChartLabel($chart, $date) {
    $ret = array();

    switch($chart) {
    case 'hourly':
      for($i = 0; $i < 24; $i++) {
        $ret[] = sprintf('%02d:00', $i);
      }
      break;
    case 'daily':
      $from = new Zend_Date();
      $from->sub('01', Zend_Date::MONTH);
      $date->add('01', Zend_Date::DAY);
      for($i = $from; $i->compare($date) <= 0; $i->add('01', Zend_Date::DAY)) {
        $ret[]= $i->toString('YYYY-MM-dd');
      }
      break;
    case 'monthly':
      $from = new Zend_Date();
      $from->sub('02', Zend_Date::MONTH);
      $date->add('01', Zend_Date::DAY);
      for($i = $from; $i->compare($date) <= 0; $i->add('01', Zend_Date::MONTH)) {
        $ret[]= $i->toString('YYYY-MM');
      }
      break;
    }

    return $ret;
  }

  public function lpoChartAction() {
    $this->_helper->layout->disableLayout();

    $stats  = $this->getRequest()->getParam('stats', 'lpo');
    $id     = $this->getRequest()->getParam('id');
    $chart  = $this->getChartParam();
    $date   = $this->getDateParam();

    $log_t  = new Log($this->acct->id);

    $_landing    = $log_t->getStats('landing', $stats, $id, $chart, $date);
    $_conversion = $log_t->getStats('conversion', $stats, $id, $chart, $date);
    $_x_label    = $this->getChartLabel($chart, $date);

    $landing     = new line_hollow(3, 6, '#4da74d');
    $conversion  = new line_dot(3, 6, '#cb4b4b');
    $x_label     = array();
    $y_max       = 10;
    $y_right_max = 100;

    foreach($_x_label as $val) {
      switch($chart) {
      case 'hourly':
        $x_label[] = $val;
        $tip = $date->toString('YYYY年MM月dd日');
        break;
      case 'daily':
        list($y, $m, $d) = explode('-', $val);
        if($d) {
          if($d == '01') {
            $x_label[] = "{$m}/{$d}";
          } else {
            if(($d % 5 == 0) && $d != 30) {
              $x_label[] = $d;
            } else {
              $x_label[] = '';
            }
          }
        }
        $tip = "{$y}年{$m}月{$d}日";
        break;
      case 'monthly':
        list($y, $m) = explode('-', $val);
        if($m) {
          $x_label[] = "{$y}/{$m}";
        }
        $tip = "{$y}年{$m}月";
        break;
      }

      if(array_key_exists($val, $_landing)) {
        $v = $_landing[$val];
        $landing->add_data_tip($v, "{$tip}<br>アクセス数：{$v} 件");

        if($y_max < $_landing[$val]) {
          $y_max = $_landing[$val];
        }
      } else {
        $landing->add_data_tip(0, "{$tip}<br>アクセス数：0 件");
      }

      if(array_key_exists($val, $_conversion)) {
        $v = sprintf('%.2f', ($_conversion[$val] / $_landing[$val]) * 100);
        $conversion->add_data_tip(
          $v,
          "{$tip}<br>コンバージョン：{$v} ％ ({$_conversion[$val]} 件)"
        );
      } else {
        $conversion->add_data_tip(0, "{$tip}<br>コンバージョン：0 ％ (0 件)");
      }
    }

    if(($y_max % 5) != 0) {
      $y_max = ((int)($y_max / 5)) * 5 + 5;
    }

    $g = new graph();
    $g->title('　', '{}');
    if($this->getRequest()->getParam('mode', 'main') == 'main') {
      $g->bg_colour = '#c3d9ff';
      $g->x_axis_colour('#e0ecff', '#c3d9ff');
      $g->y_axis_colour('#e0ecff', '#e0ecff');
      $g->y_right_axis_colour('#ececff', '#c3d9ff');
    } else {
      $g->bg_colour = '#e0ecff';
      $g->x_axis_colour('#c3d9ff', '#e0ecff');
      $g->y_axis_colour('#c3d9ff', '#c3d9ff');
      $g->y_right_axis_colour('#c3d9ff', '#e0ecff');
    }

    $g->set_x_labels($x_label);
    $g->set_x_label_style(10, "#000000", 2, 1);
    $g->set_x_axis_steps(1);
    $g->set_tool_tip('#tip#');

    $g->data_sets[] = $conversion;
    $g->data_sets[] = $landing;
    $g->attach_to_y_right_axis(1);

    $g->set_y_min(0);
    $g->set_y_max($y_max);
    $g->set_y_legend('Access', 12, '#4da74d');

    $g->set_y_right_min(0);
    $g->set_y_right_max($y_right_max);
    $g->set_y_right_legend('Conversion', 12, '#cb4b4b');

    $this->view->graph = $g->render();
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // LPO Condition
  //
  ////////////////////////////////////////////////////////////////////////////
  public function lpoConditionAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $condition_t = new Condition();
    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    $this->view->chart     = $this->getChartParam();
    $this->view->date      = $this->getDateParam()->toString('YYYY-MM-dd');
    $this->view->yesterday = $this->getYesterday();
    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->list      = $condition->findDependentRowset(
      'Content',
      null,
      $condition_t->select()->where('status != ?', 'deleted')->order('name')
    );
    $this->view->lpo       = $condition->findParentRow('Lpo');
    $this->view->condition = $condition;
  }

  public function lpoConditionCreateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    $form = $this->getConditionForm();
    $form->setAction('/index/lpo-condition-create-submit/id/' . $id);
    $form->getElement('active')->setValue(true);

    $this->view->action = $this->getRequest()->getParam('action');
    $this->view->form   = $form;
    $this->view->lpo    = $lpo;
  }

  public function lpoConditionCreateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $lpo = $this->acct->getLpo($id);
    if(!$lpo) {
      $this->_redirect('/');
    }

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-condition-create');
    }

    $form = $this->getConditionForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-condition-create/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-condition-create');
    }

    $condition_t = new Condition();
    $condition   = $condition_t->createRow();
    if($form->getElement('active')->getValue()) {
      $condition->status = 'active';
    } else {
      $condition->status = 'inactive';
    }
    $condition->lpo_id    = $id;
    $condition->condition = $form->getElement('condition')->getValue();
    $condition->value     = $form->getElement('value')->getValue();
    $condition->save();

    $this->setSessionMessage('新しい表示条件が登録されました。');

    $this->_redirect('/index/lpo-condition/id/' . $condition->id);
  }

  public function lpoConditionUpdateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    switch($this->getRequest()->getParam('priority')) {
      case 'up':
        $condition->priorityUp();
        break;
      case 'down':
        $condition->priorityDown();
        break;
    }

    $form = $this->getConditionForm();
    $form->setAction('/index/lpo-condition-update-submit/id/' . $id);

    $form->getElement('active')->setValue($condition->status == 'active');
    $form->getElement('condition')->setValue($condition->condition);
    $form->getElement('value')->setValue($condition->value);

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->form      = $form;
    $this->view->lpo       = $condition->findParentRow('Lpo');
    $this->view->condition = $condition;
  }

  public function lpoConditionUpdateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-condition-update');
    }

    $id = $this->getRequest()->getParam('id');

    $form = $this->getConditionForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-condition-update-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-condition-update');
    }

    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    if($form->getElement('active')->getValue()) {
      $condition->status = 'active';
    } else {
      $condition->status = 'inactive';
    }
    $condition->condition = $form->getElement('condition')->getValue();
    $condition->value     = $form->getElement('value')->getValue();
    $condition->save();

    $this->setSessionMessage('表示条件が変更されました。');

    $this->_redirect('/index/lpo-condition-update/id/' . $id);
  }

  public function lpoConditionDeleteAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    $form = $this->getDeleteForm();
    $form->setAction('/index/lpo-condition-delete-submit/id/' . $id);

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->form      = $form;
    $this->view->lpo       = $condition->findParentRow('Lpo');
    $this->view->condition = $condition;
  }

  public function lpoConditionDeleteSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-condition-delete');
    }

    $form = $this->getDeleteForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-condition-delete-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-condition-delete');
    }

    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
    $db->beginTransaction();
    try {
      $condition = $this->acct->getCondition($id);
      if(!$condition) {
        $this->_redirect('/');
      }

      $condition->del();
      $condition->save();

      $log_t = new Log($this->acct->id);
      $log_t->update(
        array('status' => 'deleted'),
        $log_t->getAdapter()->quoteInto('condition_id = ?', $condition->id)
      );

      $db->commit();
    } catch(Exception $e) {
      $db->rollBack();
      throw $e;
    }

    $this->setSessionMessage('表示条件が削除されました。');
    $lpo = $condition->findParentRow('Lpo');
    $this->_redirect('/index/lpo/id/' . $lpo->id);
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // LPO Content
  //
  ////////////////////////////////////////////////////////////////////////////
  public function lpoContentAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $content = $this->acct->getContent($id);
    if(!$content) {
      $this->_redirect('/');
    }

    $condition = $content->findParentRow('Condition');
    $lpo       = $condition->findParentRow('Lpo');

    $this->view->chart     = $this->getChartParam();
    $this->view->date      = $this->getDateParam()->toString('YYYY-MM-dd');
    $this->view->yesterday = $this->getYesterday();
    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->lpo       = $lpo;
    $this->view->condition = $condition;
    $this->view->content   = $content;
  }

  public function lpoContentCreateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->lpo       = $condition->findParentRow('Lpo');
    $this->view->condition = $condition;

    $form = $this->getContentForm();
    $form->setAction('/index/lpo-content-create-submit/id/' . $id);
    $form->getElement('active')->setValue(true);
    $form->getElement('name')->setValue('表示コンテンツ名称');
    $form->getElement('rate')->setValue('1');

    $this->view->form = $form;
  }

  public function lpoContentCreateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $condition = $this->acct->getCondition($id);
    if(!$condition) {
      $this->_redirect('/');
    }

    $lpo = $condition->findParentRow('Lpo');

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->lpo       = $lpo;
    $this->view->condition = $condition;

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-content-create');
    }

    $form = $this->getContentForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-content-create-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-content-create');
    }

    $content_t = new Content();
    $content   = $content_t->createRow();
    if($form->getElement('active')->getValue()) {
      $content->status = 'active';
    } else {
      $content->status = 'inactive';
    }
    $content->condition_id = $id;
    $content->name         = $form->getElement('name')->getValue();
    $content->rate         = $form->getElement('rate')->getValue();
    $content->content      = $form->getElement('content')->getValue();
    $content->save();

    $this->setSessionMessage('表示コンテンツが登録されました。');

    $this->_redirect('/index/lpo-content/id/' . $content->id);
  }

  public function lpoContentUpdateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $content = $this->acct->getContent($id);
    if(!$content) {
      $this->_redirect('/');
    }
    $condition = $content->findParentRow('Condition');
    $lpo       = $condition->findParentRow('Lpo');

    $form = $this->getContentForm();
    $form->setAction('/index/lpo-content-update-submit/id/' . $id);

    $form->getElement('active')->setValue($content->status == 'active');
    $form->getElement('name')->setValue($content->name);
    $form->getElement('rate')->setValue($content->rate);
    $form->getElement('content')->setValue($content->content);

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->form      = $form;
    $this->view->lpo       = $lpo;
    $this->view->condition = $condition;
    $this->view->content   = $content;
  }

  public function lpoContentUpdateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-content-update');
    }

    $form = $this->getContentForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-content-update-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-content-update');
    }

    $content = $this->acct->getContent($id);
    if(!$content) {
      $this->_redirect('/');
    }

    if($form->getElement('active')->getValue()) {
      $content->status = 'active';
    } else {
      $content->status = 'inactive';
    }
    $content->name    = $form->getElement('name')->getValue();
    $content->rate    = $form->getElement('rate')->getValue();
    $content->content = $form->getElement('content')->getValue();
    $content->save();

    $this->setSessionMessage('表示コンテンツが変更されました。');

    $this->_redirect('/index/lpo-content-update/id/' . $id);
  }

  public function lpoContentDeleteAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    $content = $this->acct->getContent($id);
    if(!$content) {
      $this->_redirect('/');
    }
    $condition = $content->findParentRow('Condition');
    $lpo       = $condition->findParentRow('Lpo');

    $form = $this->getDeleteForm();
    $form->setAction('/index/lpo-content-delete-submit/id/' . $id);

    $this->view->action    = $this->getRequest()->getParam('action');
    $this->view->form      = $form;
    $this->view->lpo       = $lpo;
    $this->view->condition = $condition;
    $this->view->content   = $content;
  }

  public function lpoContentDeleteSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $id = $this->getRequest()->getParam('id');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('lpo-content-delete');
    }

    $form = $this->getDeleteForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/lpo-content-delete-submit/id/' . $id);
      $this->view->form = $form;
      return $this->render('lpo-content-delete');
    }

    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
    $db->beginTransaction();
    try {
      $content = $this->acct->getContent($id);
      if(!$content) {
        $this->_redirect('/');
      }
      $content->del();
      $content->save();

      $log_t = new Log($this->acct->id);
      $log_t->update(
        array('status' => 'deleted'),
        $log_t->getAdapter()->quoteInto('content_id = ?', $content->id)
      );

      $db->commit();
    } catch(Exception $e) {
      $db->rollBack();
      throw $e;
    }

    $condition = $content->findParentRow('Condition');
    $lpo       = $condition->findParentRow('Lpo');

    $this->view->lpo       = $lpo;
    $this->view->condition = $condition;

    $this->setSessionMessage('表示コンテンツが削除されました。');
    $this->_redirect('/index/lpo-condition/id/' . $condition->id);
  }

  public function lpoContentPreviewAction() {
    $this->_helper->layout->disableLayout();

    $id = $this->getRequest()->getParam('id');
    $content = $this->acct->getContent($id);
    if(!$content) {
      $this->_redirect('/');
    }

    $this->view->content = $content;
  }

  ////////////////////////////////////////////////////////////////////////////
  //
  // Account
  //
  ////////////////////////////////////////////////////////////////////////////
  public function accountAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $this->view->action = $this->getRequest()->getParam('action');
  }

  public function accountUpdateAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $form = $this->getAccountForm();
    $form->setAction('/index/account-update-submit');
    $form->getElement('name')->setValue($this->acct->name);
    $form->getElement('email')->setValue($this->acct->email);
    $form->getElement('password')->setValue($this->acct->password);
    $this->view->form = $form;

    $this->view->action = $this->getRequest()->getParam('action');
  }

  public function accountUpdateSubmitAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    if(!$this->getRequest()->isPost()) {
      return $this->_forward('account-update');
    }

    $form = $this->getAccountForm();

    if(!$form->isValid($_POST)) {
      $form->setAction('/index/account-update-submit');
      $this->view->form = $form;
      return $this->render('account-update');
    }

    $this->acct->name  = $form->getElement('name')->getValue();
    $this->acct->email = $form->getElement('email')->getValue();
    if($password = $form->getElement('password')->getValue()) {
      $this->acct->password = $password;
    }
    $this->acct->save();

    $this->setSessionMessage('登録情報が変更されました。');

    $this->_redirect('/index/account-update');
  }

  public function accountTagAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $this->view->form   = $this->getLpoTagForm();
    $this->view->action = $this->getRequest()->getParam('action');
  }

  public function accountCloseAction() {
    $this->_helper->actionStack('msg');
    $this->_helper->actionStack('menu');

    $this->view->action = $this->getRequest()->getParam('action');
  }

  public function accountUsageChartAction() {
    $this->_helper->layout->disableLayout();

    $limit = Zend_Controller_Front::getInstance()
      ->getParam('config')
      ->db
      ->table
      ->user
      ->log_limit;

    $log_t = new Log($this->acct->id);
    $usage = $log_t->getUsage();

    $free = $limit - $usage;
    if($free < 0) {
      $free = 0;
    }

    $g = new graph();
    $g->bg_colour = '#e0ecff';
    $g->title('　', '{}');
    $g->pie(100, '#c3d9ff', 'font-size: 13px;');
    $g->pie_slice_colours(array('#cc0000', '#00cc00'));
    $g->pie_values(array($usage, $free), array('受信したアクセス数', '利用可能なアクセス数'));

    $this->view->graph = $g->render();
  }
}
