<?php
// Version
define('VERSION', '1.5.6');

// Configuration
if (file_exists('config.php')) {
	require_once('config.php');
}

error_reporting(0);

require_once('../autoload.php');
$autoload = new Autoload();

require_once(DIR_SYSTEM . 'startup.php');

// Application Classes
require_once(DIR_SYSTEM . 'library/currency.php');
require_once(DIR_SYSTEM . 'library/user.php');
require_once(DIR_SYSTEM . 'library/weight.php');
require_once(DIR_SYSTEM . 'library/length.php');
require_once(DIR_SYSTEM . 'library/cielo_api.php');
require_once(DIR_SYSTEM . 'library/customer.php');
require_once(DIR_SYSTEM . 'library/cart.php');
require_once(DIR_SYSTEM . 'library/rede.php');
require_once(DIR_SYSTEM . 'library/getnet.php');
require_once(DIR_SYSTEM . 'library/pagarme.php');
require_once(DIR_SYSTEM . 'library/matera.php');
require_once(DIR_SYSTEM . 'library/pagseguro_api.php');
require_once(DIR_SYSTEM . 'library/frete/melhorenvio.php');
require_once(DIR_SYSTEM . 'library/frete/kangu.php');
require_once(DIR_SYSTEM . 'library/tracking/correios.php');
require_once(DIR_SYSTEM . 'library/template/template.php');
require_once(DIR_SYSTEM . 'helper/ftr_geral.php');
require_once(DIR_SYSTEM . 'library/ftr_geral_registry.php');
require_once(DIR_SYSTEM . 'library/ftr_proccess.php');
require_once(DIR_SYSTEM . 'library/paypal.php');
require_once(DIR_SYSTEM . 'library/pagseguro.php');
require_once(DIR_SYSTEM . 'library/yapay.php');

require '../vendor/autoload.php' ;//carregando devido ao composer, no momento utilizado pelo cielo API 3.0 e Rede

include_once(DIR_SYSTEM . 'helper/browserInfo.php');
require_once(DIR_SYSTEM . 'library/abstracking.php');
require_once(DIR_SYSTEM . 'library/wsceobase.php');
require_once(DIR_SYSTEM . 'library/wsceo.php');
require_once(DIR_SYSTEM . 'library/cache.php');
require_once(DIR_SYSTEM . 'library/cacheFile.php');
require_once(DIR_SYSTEM . 'library/cacheRam.php');

require_once(DIR_SYSTEM . 'library/ftr_validate.php');
require_once(DIR_SYSTEM . 'library/ie_validate.php');


// Registry
$registry = new Registry();

// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
$loader->type('tipocomum');

// Base Controllers
function loadController($controller) {
    global $loader;
    $loader->controller($controller);
}

// Config
$config = new Config();
$registry->set('config', $config);

// Cache
$cache = new Cache();
$registry->set('cache', $cache);

// Database
$db = new DB($registry, DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if($db->getConnectError()){
	echo "<span style='font-size: 22px;'>Erro ao conectar com o servidor.</span>";
	exit;
}
$registry->set('db', $db);

$cep = new Cep();
$registry->set('cep', $cep);

$loader->type('tipocomum');

// Settings
$query = $db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0'");

foreach ($query->rows as $setting) {

  switch ($setting['serialized']) {
    case Type_SettingValue::Tp_Serialized :
      $value = unserialize($setting['value']);
      break;
    case Type_SettingValue::Tp_Json :
      $value = json_decode($setting['value'], true);
      break;
    default:
      $value = $setting['value'];
  }

  $config->set($setting['key'], $value);

}

if ($config->get('config_time_zone')){
	//Seta os timezones padões na base e no php conforme configurado em configurações > localização
	date_default_timezone_set($config->get('config_time_zone'));

	$new_tz    = new DateTimeZone( $config->get('config_time_zone') );
	$date_tz   = new DateTime('now', $new_tz);
	$tz_offset = $date_tz->getOffset() / 3600;
	$timezone  = ($tz_offset >= 0) ? '+'.$tz_offset : '-'.$tz_offset*-1;

	$db->setTimezone($timezone.':00');
}

$cache->setPrefix(DB_USERNAME . $config->get('config_encryption'));

// Url
$urlTemporariaSSL = $config->get('config_linktemporario_ssl');
$urlProducaoSSL 	= $config->get('config_linkproducao_ssl');
$hab_producao   	= $config->get('config_habilita_linkproducao');

if((!empty($urlTemporariaSSL)) || (!empty($urlProducaoSSL))){
	$protocol 		 = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
	$urlAtualSSL   = $protocol. $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/.\\') . '/';

	if((!empty($urlProducaoSSL)) && (($urlAtualSSL == $urlProducaoSSL.'admin/')||($urlAtualSSL == 'https://www.'.str_replace('https://','',$urlProducaoSSL).'admin/'))){
		$config->set('config_ssl', $urlProducaoSSL);
		$config->set('config_adm_ssl', $urlProducaoSSL.'admin/');
	} elseif(!empty($urlTemporariaSSL) && ($urlTemporariaSSL.'admin/' == $urlAtualSSL)){
		$config->set('config_ssl', $urlTemporariaSSL);
		$config->set('config_adm_ssl', $urlTemporariaSSL.'admin/');
	}else{
	    $urlAtualSSLCatalog = str_replace('admin/' , '', $urlAtualSSL);
		$config->set('config_ssl'		 , $urlAtualSSLCatalog);
		$config->set('config_adm_ssl', $urlAtualSSL);
	}

}elseif (defined('HTTPS_SERVER')){
	$config->set('config_ssl', HTTPS_CATALOG);
	$config->set('config_adm_ssl', HTTPS_SERVER);
}

$url 		 = new Url($config->get('config_adm_ssl'));
$urlloja = new Url($config->get('config_ssl'));

$registry->set('url', $url);
$registry->set('urlloja', $urlloja);

// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);

function error_handler($errno, $errstr, $errfile, $errline) {
	global $log, $config;

	switch ($errno) {
		case E_NOTICE:
		case E_USER_NOTICE:
			$error = 'Notice';
			break;
		case E_WARNING:
		case E_USER_WARNING:
			$error = 'Warning';
			break;
		case E_ERROR:
		case E_USER_ERROR:
			$error = 'Fatal Error';
			break;
		default:
			$error = 'Unknown';
			break;
	}

	if ($config->get('config_error_display')) {
		echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
	}

	if ($config->get('config_error_log')) {
		$log->write('PHP ' . $error . ':  ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
	}

	return true;
}

// Error Handler
set_error_handler('error_handler');

// Request
$request = new Request();
$registry->set('request', $request);

// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$registry->set('response', $response);

// Session
$session = new Session();
$registry->set('session', $session);

// Language
$languages = array();

$query = $db->query("SELECT * FROM `" . DB_PREFIX . "language`");

foreach ($query->rows as $result) {
	$languages[$result['code']] = $result;
}

$config->set('config_language_id', $languages[$config->get('config_language')]['language_id']);


$language = new Language($languages[$config->get('config_language')]['directory']);
$language->load($languages[$config->get('config_language')]['filename']);
$registry->set('language', $language);

//Ftr_geral_registry
$ftrgeralregistry = new Ftr_geral_registry($registry);
$ftrgeralregistry->setIsAdmin(true);

$registry->set('ftrgeralregistry', $ftrgeralregistry);

//Ftr_validate
$ftrvalidate = new Ftr_validate($registry);

$registry->set('validate', $ftrvalidate);

// Document
$registry->set('document', new Document($registry));

// Customer
$registry->set('customer', new Customer($registry));

// Cart
$registry->set('cart', new Cart($registry));

// Currency
$registry->set('currency', new Currency($registry));

// Weight
$registry->set('weight', new Weight($registry));

// Length
$registry->set('length', new Length($registry));

// MercadoLivre ---removerrrrrrr
$registry->set('mercadolivre', new Mercadolivre($registry));
// Shopee
$registry->set('shopee', new Shopee($registry));
// Marketplace
$registry->set('marketplace', new MktPlace($registry));

// Ecommerce API
$registry->set('ecommerceapi', new EcommerceAPI($registry));

// APICielo 3.0
$registry->set('cieloapi', new Cielo_api($registry));

// Rede
$registry->set('rede', new Rede($registry));

// Getnet
$registry->set('getnet', new Getnet($registry));

// Pagarme
$registry->set('pagarme', new Pagarme($registry));

// Matera
$registry->set('matera', new Matera($registry));

// Pagseguro API
$registry->set('pagseguroapi', new PagseguroAPI($registry));

// Melhor Envio - Frete
$registry->set('melhorenvio', new Melhorenvio($registry));

// Kangu - Frete
$registry->set('kangu', new Kangu($registry));

// Correios - Frete
$registry->set('correios', new Correios($registry));

// User
$registry->set('user', new User($registry));

// Encryption
$registry->set('encryption', new Encryption($config->get('config_encryption')));

// CEO WEB SERVICE
$registry->set('wsceo', new Wsceo($registry));

$registry->set('feedback', new Feedback($registry));

$registry->set('sendwhat', new SendWhatsapp($registry));

// Template
//$registry->set('template', new Template($registry));


$configSistemaEcommerce   = $ftrgeralregistry->isSistema(Type_Sistema::Tp_Ecommerce);
$configSistemaMarketplace = $ftrgeralregistry->isSistema(Type_Sistema::Tp_Marketplace);

$config->set('config_sistema_ecommerce', $configSistemaEcommerce);
$config->set('config_sistema_marketplace', $configSistemaMarketplace);

// Language
/*Força a utilização da linguagem de orçamento quando utilizar o módulo reduzido*/
if ($configSistemaMarketplace && !$configSistemaEcommerce){
	$languages[$config->get('config_language')]['directory'] = 'portuguese-brOrc';
}
/*Força a utilização da linguagem de orçamento quando utilizar o módulo reduzido*/




// ftr_proccess
$ftrproccess = new ftr_proccess($registry);
$registry->set('ftrproccess', $ftrproccess);

// Front Controller
$controller = new Front($registry);

$registry->set('specific', new Specific($registry));

// Login
$controller->addPreAction(new Action('common/home/login'));

// Permission
$controller->addPreAction(new Action('common/home/permission'));

// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));

// Router
if (isset($request->get['route'])) {
	$action = new Action($request->get['route']);
} else {
	$action = new Action('common/home');
}

// Dispatch
$controller->dispatch($action, new Action('error/not_found'));

// Output
$response->output();
