<?php

use EesyPHP\Check;
use EesyPHP\Log;
use EesyPHP\Tpl;
use EesyPHP\Url;

use function EesyPHP\vardump;

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

/**
 * Search page handler
 * @param EesyPHP\UrlRequest $request
 * @return void
 */
function handle_search($request) {
  global $status_list;

  // Manage params
  if(
    (isset($_REQUEST['clear']) && $_REQUEST['clear']=='true') ||
    !isset($_SESSION['search']) ||
    !is_array($_SESSION['search'])
  ) {
    $_SESSION['search']=array(
      'pattern' => false,
      'status' => 'all',
      'order' => 'name',
      'order_direction' => 'ASC',
    );
    if (isset($_REQUEST['clear']) && $_REQUEST['clear']=='true')
      Url :: redirect($request -> current_url);
  }
  Log :: debug('Request params : '.vardump($_REQUEST));

  $status_list['all'] = _('Any');
  if (isset($_REQUEST['status'])) {
    if (check_status($_REQUEST['status']) || $_REQUEST['status'] == 'all')
      $_SESSION['search']['status'] = $_REQUEST['status'];
    else
      Tpl :: assign('status_error', true);
  }

  if (isset($_REQUEST['pattern'])) {
    if (trim($_REQUEST['pattern']) == '')
      $_SESSION['search']['pattern'] = false;
    else if (Check :: search_pattern($_REQUEST['pattern']))
      $_SESSION['search']['pattern'] = $_REQUEST['pattern'];
    else
      Tpl :: assign('pattern_error', true);
  }

  // Order
  if(isset($_REQUEST['order'])) {
    if( $_SESSION['search']['order']==$_REQUEST['order']) {
      if ($_SESSION['search']['order_direction']=='ASC')
        $_SESSION['search']['order_direction']='DESC';
      else
        $_SESSION['search']['order_direction']='ASC';
    }
    else
      $_SESSION['search']['order_direction']='ASC';
    $_SESSION['search']['order']=$_REQUEST['order'];
  }
  else {
    if($_SESSION['search']['order']=='') {
      $_SESSION['search']['order']='date';
      $_SESSION['search']['order_direction']='DESC';
    }
  }

  // Page
  if (isset($_REQUEST['page'])) {
    $_SESSION['search']['page']=intval($_REQUEST['page']);
  }
  else {
    $_SESSION['search']['page']=1;
  }

  // Nb par page
  $nbs_by_page=array(10,25,50,100,500);
  if (isset($_REQUEST['nb_by_page']) && in_array(intval($_REQUEST['nb_by_page']),$nbs_by_page)) {
    $_SESSION['search']['nb_by_page']=intval($_REQUEST['nb_by_page']);
    $_SESSION['search']['page']=1;
  }
  elseif (!isset($_SESSION['search']['nb_by_page'])) {
    $_SESSION['search']['nb_by_page']=$nbs_by_page[0];
  }

  Log :: debug('Search params : '.vardump($_SESSION['search']));
  $result = search_items($_SESSION['search']);
  if (!is_array($result))
    Tpl :: fatal_error(
      _("An error occurred while listing the items. ".
      "If the problem persists, please contact support.")
    );

  Tpl :: assign('result', $result);
  Tpl :: assign('search', $_SESSION['search']);
  Tpl :: assign('nbs_by_page', $nbs_by_page);
  Tpl :: assign('status_list', $status_list);

  Tpl :: add_css_file(
    'lib/bootstrap5-dialog/css/bootstrap-dialog.min.css',
  );
  Tpl :: add_js_file(
    'lib/bootstrap5-dialog/js/bootstrap-dialog.min.js',
    'js/myconfirm.js',
    'js/search.js'
  );

  Tpl :: display("search.tpl", _("Search"));
}
Url :: add_url_handler('|^item/?$|', 'handle_search');

/**
 * Show one item page handler
 * @param EesyPHP\UrlRequest $request
 * @return void
 */
function handle_show($request) {
  $item = get_item_from_url($request -> id);
  if (!$item)
    Url :: error_404();

  Tpl :: assign('item', $item);

  // Dialog
  Tpl :: add_css_file(
    'lib/bootstrap5-dialog/css/bootstrap-dialog.min.css',
  );
  Tpl :: add_js_file(
    'lib/bootstrap5-dialog/js/bootstrap-dialog.min.js',
    'js/myconfirm.js',
  );

  Tpl :: display(
    "show.tpl", _("Element %s"),
    (is_array($item)?$item['name']:"#".$request -> id)
  );
}
Url :: add_url_handler('|^item/(?P<id>[0-9]+)$|', 'handle_show');

/**
 * Create one item page handler
 * @param EesyPHP\UrlRequest $request
 * @return void
 */
function handle_create($request) {
  global $status_list;

  $info = array();
  $field_errors = handle_item_post_data($info);
  if (isset($_POST['submit']) && empty($field_errors)) {
    $item = add_item($info);
    if (is_array($item)) {
      Tpl :: add_message(_("The element '% s' has been created."), $item['name']);
      Url :: redirect('item/'.$item['id']);
    }
    Tpl :: add_error(_("An error occurred while saving this item."));
  }
  Log :: debug('Validated data : '.vardump($info));
  Log :: debug('Fields errors : '.vardump($field_errors));
  if (isset($_POST['submit']) && !empty($field_errors))
    Tpl :: add_error(
      _("There are errors preventing this item from being saved. ".
      "Please correct them before attempting to add this item."));
  Tpl :: assign('submited', isset($_POST['submit']));
  Tpl :: assign('info', $info);
  Tpl :: assign('field_errors', $field_errors);
  Tpl :: assign('status_list', $status_list);

  Tpl :: display("form.tpl", _("New"));
}
Url :: add_url_handler('|^item/new$|', 'handle_create');

function handle_modify($request) {
  global $status_list;

  $item = get_item_from_url($request -> id);
  if(!is_array($item))
    Url :: error_404();
  if (!can_modify($item)) {
    Tpl :: add_error(_('You cannot edit this item.'));
    Url :: redirect('item/'.$item['id']);
  }
  $info = array();
  $field_errors = handle_item_post_data($info);
  if (isset($_POST['submit']) && empty($field_errors)) {
    $changes = array();
    foreach ($info as $key => $value) {
      if ($value != $item[$key])
        $changes[$key] = $value;
    }
    Log :: debug('Changes : '.vardump($changes));
    if (empty($changes)) {
      Tpl :: add_message(_("You have not made any changes to element '% s'."), $item['name']);
      Url :: redirect('item/'.$item['id']);
    }
    if (update_item($item['id'], $changes) === true) {
      Tpl :: add_message(_("The element '% s' has been updated successfully."), $item['name']);
      Url :: redirect('item/'.$item['id']);
    }
    Tpl :: add_error(_("An error occurred while updating this item."));
  }
  Log :: debug('Validated data : '.vardump($info));
  Log :: debug('Fields errors : '.vardump($field_errors));
  Tpl :: assign('submited', isset($_POST['submit']));
  if (isset($_POST['submit']) && !empty($field_errors))
    Tpl :: add_error(
      _("There are errors preventing this item from being saved. ".
      "Please correct them before attempting to save your changes."));
  Tpl :: assign('info', (!empty($info)?$info:$item));
  Tpl :: assign('item_id', $item['id']);
  Tpl :: assign('field_errors', $field_errors);
  Tpl :: assign('status_list', $status_list);

  Tpl :: display("form.tpl", _("Element %s: Modification"), $item['name']);
}
Url :: add_url_handler('|^item/(?P<id>[0-9]+)/modify$|', 'handle_modify');

/**
 * Archive one item page handler
 * @param EesyPHP\UrlRequest $request
 * @return never
 */
function handle_archive($request) {
  $item = get_item_from_url($request -> id);
  if(!is_array($item)) {
    Tpl :: add_error(_("Item #% s not found."), $request -> id);
    Url :: redirect('item');
  }
  if ($item['status'] == 'archived') {
    Tpl :: add_message(_("This item is already archived."));
  }
  else if (!can_archive($item)) {
    Tpl :: add_error(_('You cannot archive this item.'));
  }
  else if (archive_item($item['id']) === true) {
    Tpl :: add_message(_("The element '% s' has been archived successfully."), $item['name']);
  }
  else {
    Tpl :: add_error(_('An error occurred while archiving this item.'));
  }
  Url :: redirect('item/'.$item['id']);
}
Url :: add_url_handler('|^item/(?P<id>[0-9]+)/archive$|', 'handle_archive');

/**
 * Delete one item page handler
 * @param EesyPHP\UrlRequest $request
 * @return void
 */
function handle_delete($request) {
  $item = get_item_from_url($request -> id);
  if(!is_array($item)) {
    Tpl :: add_error(_("Item #% s not found."), $request -> id);
  }
  else if (!can_delete($item)) {
    Tpl :: add_error(_('You cannot delete this item.'));
  }
  else if (delete_item($item['id']) === true) {
    Tpl :: add_message(_("The element '% s' has been deleted successfully."), $item['name']);
  }
  else {
    Tpl :: add_error(_('An error occurred while deleting this item.'));
    Url :: redirect('item/'.$item['id']);
  }
  Url :: redirect('item');
}
Url :: add_url_handler('|^item/(?P<id>[0-9]+)/delete$|', 'handle_delete');

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