<?php

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

use function EesyPHP\vardump;

/*
 * Check values helpers
 */
function check_status($status) {
  global $status_list;
  return array_key_exists($status, $status_list);
}

/*
 * Handling item POST data
 */
function handle_item_post_data(&$info, $enabled_fields=null, $required_fields=null, &$item=null,
                               &$changes=null) {
  $field_errors=array();
  if (isset($_POST['submit'])) {
    Log :: debug('POST data : '.vardump($_POST));
    // Name
    if (!$enabled_fields || in_array('name', $enabled_fields)) {
      if (isset($_POST['name'])) {
        if (Check :: name($_POST['name'])) {
          $info['name'] = $_POST['name'];
        }
        else {
          $field_errors['name'] = "Ce nom est invalide.";
        }
      }
      else {
        $field_errors['name'] = "Cette information est obligatoire.";
      }
    }

    // status
    if (!$enabled_fields || in_array('status', $enabled_fields)) {
      if (isset($_POST['status']) && check_status($_POST['status'])) {
        $info['status'] = $_POST['status'];
      }
      else {
        $field_errors['status'] = "Cette information est obligatoire.";
      }
    }

    // description
    if (
      isset($_POST['description']) &&
      (!$enabled_fields || in_array('description', $enabled_fields))
    ) {
      if (Check :: is_empty(trim($_POST['description']))) {
        $info['description'] = null;
      }
      else if (Check :: description($_POST['description'])) {
        $info['description'] = $_POST['description'];
      }
      else {
        $field_errors['description'] = "Cette description est invalide.";
      }
    }
  }

  // Check custom required fields
  if (is_array($required_fields)) {
    foreach ($required_fields as $field) {
      if (array_key_exists($field, $field_errors))
        continue;
      if (array_key_exists($field, $info) && !is_null($info[$field]) && !Check :: is_empty($info))
        continue;
      $field_errors[$field] = "Cette information est obligatoire.";
    }
  }

  if (empty($field_errors) && is_array($item) && !is_null($changes)) {
    $changes = array();
    foreach ($info as $key => $value) {
      if ($value != $item[$key])
        $changes[$key] = $value;
    }
  }
  return $field_errors;
}

/*
 * Parser/formater values helpers
 */

function can_modify($item) {
  return can_do(
    $item,
    array('pending')
  );
}

function can_archive($item) {
  return can_do(
    $item,
    array('refused', 'validated')
  );
}

function can_delete($item) {
  return can_do(
    $item,
    array('archived')
  );
}

function can_do($item, $status=array()) {
  return in_array($item['status'], $status);
}

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