<?php

namespace HwapX\Admin\Library\Builder;

use HwapX\Core\Library\Template;

use \F3;
use \Prefab;

class TableBuilder extends Prefab {
  protected $f3     = null;
  protected $mapper = null;
  protected $rules  = array();
  protected $default_rules  = array('param' => 'page', 'name' => 'Item');

  public function __construct($mapper = null, $rules = array()) {
    $this->f3     = F3::instance();
    $this->mapper = $mapper;

    if($rules)
      $this->rules  = array_merge($this->default_rules, $rules);
    elseif(isset($mapper->rules) && is_array($mapper->rules))
      $this->rules  = array_merge($this->default_rules, $mapper->rules);
  }

  public function setMapper($mapper) {
    $this->mapper = $mapper;
  }

  public function setRules($rules) {
    $this->rules  = array_merge($this->default_rules, $rules);
  }

  public function render($page = null, $rowcount = null, $options = array()) {
    $this->f3->set('page.title', $this->rules['name']);

    if(!isset($this->rules['title']))
      $this->rules['title'] = 'Lista de '.$this->rules['name'];

    if(is_null($page))
      $page  = $this->f3->exists('PARAMS.page') ? $this->f3->get('PARAMS.'.$this->rules['param']) - 1 : 0;

    if(is_null($rowcount))
      $rowcount = isset($this->rules['rowcount']) ? $this->rules['rowcount'] : $this->f3->get('app.table.rowcount');

    if($rowcount === true) {
      if($this->f3->exists('COOKIE.table_rowcount_'.$this->rules['route']))
        $rowcount = (int)$this->f3->get('COOKIE.table_rowcount_'.$this->rules['route']);
      else
        $rowcount = $this->f3->get('app.table.rowcount');
      $rowcount = $rowcount ?: 9999;
    }

    $where = isset($this->rules['filter']) ? $this->rules['filter'] : array();

    foreach ($where as &$value) if(is_string($value)) {
      $value = Template::instance()->resolve((string)$value);
      if($value === '') $value = null;
    }

    $metadata = method_exists($this->mapper, 'getMetadata') ? $this->mapper->getMetadata(true) : array();

    foreach($this->rules['cols'] as $field => $col) {
      $cookie = 'COOKIE.table_filter_'.$this->rules['route'].'_'.$field;
      if($this->f3->exists($cookie) && ($val = $this->f3->get($cookie)) != '') {
        $fieldstr = "`$field`";
        if(isset($metadata[$field]['expr'])) {
          $fieldstr = $metadata[$field]['expr'];
        }
        
        if((isset($col['type']) && $col['type'] == 'date') || ($metadata[$field]['type'] == 'DATE')) {
          //$fieldstr = "strftime('".$this->f3->get('app.datetime.format3')."', $field)";
          $fieldstr = "DATE_FORMAT($fieldstr, '".$this->f3->get('app.datetime.format3')."')";
        }

        $token    = isset($where[1]) ? '?' : ':'.$field;

        $where[0] = (isset($where[0]) ? $where[0] . ' and ' : '').$fieldstr.' LIKE '.$token;

        if($token !== '?')
          $where[$token]  = "%$val%";
        else
          $where[]  = "%$val%";
      }
    }

    $order   = $this->f3->get('COOKIE.table_order_'.$this->rules['route']);
    $order   = in_array($order, array('asc', 'desc')) ? $order : '';
    $field   = $this->f3->get('COOKIE.table_sort_'.$this->rules['route']);
    $field   = in_array($field, array_keys($this->rules['cols'])) ? $field : null;

    //$options = array();
    if($field)
      $options['order'] = "$field $order";

    $this->f3->set('table', $this->rules + $this->mapper->paginate($page, $rowcount, $where, $options));

    return Template::instance()->render('hwapx/admin/admin/table.html');
  }
}