<?php

class Lpo extends Zend_Db_Table_Abstract {
  protected $_name = 'necosuke_lpo_mast_lpo';
  protected $_rowClass = 'LpoRow';
  protected $_dependentTables = array('Condition', 'Log');
  protected $_referenceMap = array(
    'Account' => array(
      'columns'       => 'account_id',
      'refTableClass' => 'Account',
      'refColumns'    => 'id',
      #'onDelete'      => self::CASCADE,
    ),
  );

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

    if(
      array_key_exists('landing_url', $data) &&
      $data['landing_url'] != 'http://'
    ) {
      $_url = parse_url($data['landing_url']);
      if(!array_key_exists('path', $_url)) {
        $data['landing_url'] = $data['landing_url'] . '/';
      }
    }

    if(
      array_key_exists('conversion_url', $data) &&
      $data['conversion_url'] != 'http://'
    ) {
      $_url = parse_url($data['conversion_url']);
      if(!array_key_exists('path', $_url)) {
        $data['conversion_url'] = $data['conversion_url'] . '/';
      }
    }

    return parent::insert($data);
  }

  public function update($data, $where) {
    $data['updated'] = new Zend_Db_Expr('now()');

    if(
      array_key_exists('landing_url', $data) &&
      $data['landing_url'] != 'http://'
    ) {
      $_url = parse_url($data['landing_url']);
      if(!array_key_exists('path', $_url)) {
        $data['landing_url'] = $data['landing_url'] . '/';
      }
    }

    if(
      array_key_exists('conversion_url', $data) &&
      $data['conversion_url'] != 'http://'
    ) {
      $_url = parse_url($data['conversion_url']);
      if(!array_key_exists('path', $_url)) {
        $data['conversion_url'] = $data['conversion_url'] . '/';
      }
    }

    return parent::update($data, $where);
  }
}

class LpoRow extends Zend_Db_Table_Row_Abstract {
  public function getContent($url, $ref) {
    $condition_t = new Condition;

    foreach(
      $this->findDependentRowset(
        'Condition',
        null,
        $condition_t->select()->where('status = ?', 'active')->order('priority')
      ) as $condition
    ) {
      if($data = $condition->getContent($url, $ref)) {
        array_unshift($data, $this);
        return $data;
      }
    }

    return null;
  }

  public function del() {
    $this->status = 'deleted';

    $content_t = new Content();
    foreach($this->findDependentRowset('Condition', null) as $condition) {
      $condition->del();
      $condition->save();
    }
  }
}
