<?php
class Table_InventoryChangeLog {
  protected $_table = NULL;

  public function __construct() {
    $this->_table = new DbTable_InventoryChangeLog();
  }

  public function insert($data) {
    return $this->_table->insert($data);
  }

  public function update($data, $value, $key = 'icl_id') {
    $where = $this->_table->getAdapter()->quoteInto("{$key}=?", $value);

    return $this->_table->update($data, $where);
  }

  public function delete($value, $key = 'icl_id') {
    $where = $this->_table->getAdapter()->quoteInto("{$key}=?", $value);

    return $this->_table->delete($where);
  }

  public function getByCondition($condition, $column = '*', $size = 0, $page = 1, $order = '') {
    $select = $this->_table->getAdapter()->select();
    $table  = $this->_table->info('name');
    $select->from($table, $column);
    $select->joinLeft('product as p','p.product_id=' . $table .".product_id",array('customer_code', 'product_sku', 'product_barcode'));
    $select->where("1 =?", 1);
    //echo $sql = $select->__toString();exit();


    if (isset($condition['warehouse_id']) && '' !== trim($condition['warehouse_id'])) {
      $select->where($table . '.warehouse_id=?', (int) $condition['warehouse_id']);
    }

    if (isset($condition['customer_id']) && '' !== trim($condition['customer_id'])) {
      $select->where('p.customer_id=?', (int) $condition['customer_id']);
    }
	if (isset($condition['customer_code']) && '' !== trim($condition['customer_code'])) {
      $select->where('p.customer_code=?', $condition['customer_code']);
    }
    if (isset($condition['product_id']) && '' !== trim($condition['product_id'])) {
      $select->where($table .'.product_id=?', (int) $condition['product_id']);
    }
      if(isset($condition["dateFor"]) && $condition["dateFor"] != ""){
          $select->where($table . ".operation_time >=?",$condition["dateFor"].' 00:00:00');
      }

      if(isset($condition["dateTo"]) && $condition["dateTo"] != ""){
          $select->where($table . ".operation_time <=?",$condition["dateTo"].' 23:59:59');
      }


    if ('count(*)' === $column) {
      return $this->_table->getAdapter()->fetchOne($select);
    }
    else {
      if (is_string($order) && '' !== $order) {
        $select->order($order);
      }

      if ($size > 0 && $page > 0) {
        $offset = ($page - 1) * $size;
        $select->limit($size, $offset);
      }

      return $this->_table->getAdapter()->fetchAll($select);
    }
  }
}
