<?php

date_default_timezone_set('America/Sao_Paulo');

if(!isset($_SESSION)) {
  session_start();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  require_once 'inc/tabela_precos.php';
  $redirect = 'erpc_tabela_precos_list.php';
  $tabela_precos = ler_tabela_precos();
  if (isset($_POST['btn-add'])) {
    $ok = tabela_precos_insert($tabela_precos);
    if ($ok === false) {
      $redirect = 'erpc_tabela_precos_add.php';
    }
  } else if (isset($_POST['btn-edit'])) {
    $ok = tabela_precos_update($tabela_precos);
    if ($ok === false) {
      $redirect = 'erpc_tabela_precos_edit.php?id=' . urlencode(base64_encode($tabela_precos['id']));
    }
  } else if (isset($_POST['btn-remove'])) {
    $ok = tabela_precos_delete($tabela_precos);
    if ($ok === false) {
      $redirect = 'erpc_tabela_precos_remove.php?id=' . urlencode(base64_encode($tabela_precos['id']));
    }
  }
  header("Location:$redirect");
  exit;
}

function ler_tabela_precos() {
  date_default_timezone_get('America/Sao_Paulo');
  $tabela_precos = tabela_precos_create();
  if (isset($_POST['tabela_precos'])) {
    $tabela_precos = array_replace_recursive($tabela_precos, $_POST['tabela_precos']);
  }
  foreach($tabela_precos as $k => $v) {
    $tabela_precos[$k] = sgcws_sanitize_field($k, $v);
  }
  $itens = $tabela_precos['itens'];
  foreach($itens as $i => $item) {
    foreach($item as $k => $v) {
      $item[$k] = sgcws_sanitize_field($k, $v);
    }
    $itens[$i] = $item;
  }
  $tabela_precos['itens'] = $itens;
  return $tabela_precos;
}
