<?php

use EesyPHP\App;
use EesyPHP\Date;
use EesyPHP\Hook;
use EesyPHP\Log;
use EesyPHP\Tpl;
use EesyPHP\Url;

use EesyPHPExample\Db\Item;

use function EesyPHP\format_size;

if (php_sapi_name() == "cli")
  return true;

// Enable Smarty security
Tpl :: enable_security_mode(
  // Allow some functions in IF clauses
  array(
    'isset', 'empty', 'count', 'in_array', 'is_array', 'array_key_exists', 'is_null',
    'can_modify', 'can_archive', 'can_delete'
  ),
  // Allow some modifier functions
  array('range', 'implode', 'stripslashes')
);

function define_common_template_variables($event) {
  global $admin;
  Tpl :: assign('statuses', Item :: statuses());
  Tpl :: assign('admin', isset($admin) && $admin);
}
Hook :: register('before_displaying_template', 'define_common_template_variables');

// Templates functions
function smarty_item_status($params) {
  $statuses = Item :: statuses();
  $status2class = array (
    'pending' => 'info',
    'validated' => 'success',
    'refused' => 'danger',
    'archived' => 'secondary',
  );
  if (array_key_exists($params['item']->status, $status2class)) {
    $class = $status2class[$params['item']->status];
  }
  else
    $class='danger';
  echo "<span class='badge bg-$class'>";
  echo (
    array_key_exists($params['item']->status, $statuses)?
    $statuses[$params['item']->status]:
    "Inconnu (".$params['item']->status.")"
  );
  echo "</span>";
}
Tpl :: register_function('item_status','smarty_item_status');

function smarty_format_time($params) {
  echo Date :: format($params['time'], (!isset($params['with_time']) || (bool)$params['with_time']));
}
Tpl :: register_function('format_time','smarty_format_time');

function smarty_format_size($params, $smarty) {
  if(!isset($params['digit'])) $params['digit'] = 2;
  echo format_size($params['size'],$params['digit']);
}
Tpl :: register_function('format_size','smarty_format_size');

function smarty_table_ordered_th($params, $smarty) {
  if ($params['order'] && $params['url'] && $params['text'] && is_array($params['search'])) {
    $params['url'] = Url::add_url_parameter($params['url'], 'order', $params['order']);
    printf("<a href='%s'>%s</a>", $params['url'], $params['text']);
  }
  if ($params['order'] == $params['search']['order']) {
    printf(
      ' <i class="fa fa-sort-%s" aria-hidden="true"></i>',
      strtolower($params['search']['order_direction']) == 'asc'?
      'up':'down'
    );
  }
}
Tpl :: register_function('table_ordered_th','smarty_table_ordered_th');

function smarty_encodeJsonBase64($params, $smarty) {
  if (isset($params['data']))
    echo base64_encode(json_encode($params['data']));
}
Tpl :: register_function('encodeJsonBase64','smarty_encodeJsonBase64');

# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab