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

//Necessário para o atualizador ecommerce...
if (!defined('DIR_APPLICATION') && (defined('LINK_TEMP'))) {
	header('Location: ' . LINK_TEMP);
	exit;
}
require_once(DIR_SYSTEM . 'startup.php');

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

// Application
require_once(DIR_SYSTEM . 'library/product_visualized.php');
require_once(DIR_SYSTEM . 'library/presente.php');
require_once(DIR_SYSTEM . 'library/pagseguro.php');
require_once(DIR_SYSTEM . 'library/customer.php');
require_once(DIR_SYSTEM . 'library/affiliate.php');
require_once(DIR_SYSTEM . 'library/currency.php');
require_once(DIR_SYSTEM . 'library/weight.php');
require_once(DIR_SYSTEM . 'library/length.php');
require_once(DIR_SYSTEM . 'library/cart.php');
require_once(DIR_SYSTEM . 'library/buy_later.php');
require_once(DIR_SYSTEM . 'library/fidelitycart.php');
require_once(DIR_SYSTEM . 'library/breadcrumbs.php');
require_once(DIR_SYSTEM . 'library/product_list_title.php');
require_once(DIR_SYSTEM . 'library/user.php');
require_once(DIR_SYSTEM . 'library/cielo_api.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/pagseguro_api.php');
require_once(DIR_SYSTEM . 'library/analyze.php');
require_once(DIR_SYSTEM . 'library/ftr_geral_registry.php');
require_once(DIR_SYSTEM . 'helper/ftr_geral.php');
require_once(DIR_SYSTEM . 'library/ftr_proccess.php');
require_once(DIR_SYSTEM . 'library/wsceobase.php');
require_once(DIR_SYSTEM . 'library/wsceo.php');
require_once(DIR_SYSTEM . 'library/yapay.php');
require_once(DIR_SYSTEM . 'library/paypal.php');
require_once(DIR_SYSTEM . 'library/clearsale.php');
require_once(DIR_SYSTEM . 'library/ie_validate.php');
require_once(DIR_SYSTEM . 'library/email_validate.php');

//Módulos de frete
require_once(DIR_SYSTEM . 'library/frete/intelipost.php');
require_once(DIR_SYSTEM . 'library/frete/dlog.php');
require_once(DIR_SYSTEM . 'library/frete/melhorenvio.php');
require_once(DIR_SYSTEM . 'library/frete/kangu.php');
require_once(DIR_SYSTEM . 'library/frete/jadlog.php');
require_once(DIR_SYSTEM . 'library/cache.php');
require_once(DIR_SYSTEM . 'library/cacheFile.php');
require_once(DIR_SYSTEM . 'library/cacheRam.php');
//Módulos de frete

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


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


include_once(DIR_SYSTEM . 'helper/browserInfo.php');
require_once(DIR_SYSTEM . 'library/abstracking.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);
}

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

// Database
$db = new DB($registry, DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

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

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);

$config->set('config_store_id', 0);
// Settings
$query = $db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0' OR store_id = '" . (int)$config->get('config_store_id') . "' ORDER BY store_id ASC");

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'));

//Inicio - Validações para setar as URLs corretas de acordo com a loja em produção oud esenvolvimento
$urlTemporariaSSL = $config->get('config_linktemporario_ssl');
$urlProducaoSSL 	= $config->get('config_linkproducao_ssl');

$config->set('lojaEmProducao', $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 ($urlAtualSSL  == $urlTemporariaSSL){
	  $config->set('config_ssl', $urlTemporariaSSL);
	  $config->set('config_adm_ssl', $urlTemporariaSSL.'admin/');
	}elseif($urlAtualSSL == $urlProducaoSSL){
	  $config->set('config_ssl', $urlProducaoSSL);
	  $config->set('config_adm_ssl', $urlProducaoSSL.'admin/');
	}else{
		$config->set('config_ssl', $urlAtualSSL);
	    $config->set('config_adm_ssl', $urlAtualSSL.'admin/');
	}

} else if (defined('HTTPS_SERVER')) {
	//retrocompatibilidade com o formato de quando era incluido no ini...
	$config->set('config_ssl', HTTPS_SERVER);
    $config->set('config_adm_ssl', HTTPS_SERVER.'admin/');
	$config->set('lojaEmProducao', true);
}
//Fim - Validações para setar as URLs corretas de acordo com a loja em produção oud esenvolvimento
$url = new Url($config->get('config_ssl'));
$registry->set('url', $url);
$registry->set('urlloja', $url);

$urlAdmin = new Url($config->get('config_adm_ssl'));
$registry->set('urlAdmin', $urlAdmin);
// 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');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);

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

// Ftr_geral_registry
$ftrgeralregistry = new Ftr_geral_registry($registry);
$ftrgeralregistry->setIsAdmin(false);
$registry->set('ftrgeralregistry', $ftrgeralregistry);

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

//define o layout dependendo do lugar...
$config->set('config_template', $ftrgeralregistry->getConfigTemplate());

//inicio definicao do caminho do tema...
$config->set('config_folder_template',  DIR_TEMPLATE . $config->get('config_template') . '/template/');

// Language Detection
$languages = array();

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

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

$detect = '';

if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && $request->server['HTTP_ACCEPT_LANGUAGE']) {
	$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);

	foreach ($browser_languages as $browser_language) {
		foreach ($languages as $key => $value) {
			if ($value['status']) {
				$locale = explode(',', $value['locale']);

				if (in_array($browser_language, $locale)) {
					$detect = $key;
				}
			}
		}
	}
}

if (isset($session->data['language']) && array_key_exists($session->data['language'], $languages) && $languages[$session->data['language']]['status']) {
	$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages) && $languages[$request->cookie['language']]['status']) {
	$code = $request->cookie['language'];
} elseif ($detect) {
	$code = $detect;
} else {
	$code = $config->get('config_language');
}

if (!isset($session->data['language']) || $session->data['language'] != $code) {
	$session->data['language'] = $code;
}

if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
	setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}

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

// Language

$ftrgeralregistry = new Ftr_geral_registry($registry);
$configSistemaMarketplace = $ftrgeralregistry->isSistema(Type_Sistema::Tp_Marketplace);
$configSistemaEcommerce = $ftrgeralregistry->isSistema(Type_Sistema::Tp_Ecommerce);
$config->set('config_sistema_ecommerce', $configSistemaEcommerce);
$config->set('config_sistema_marketplace', $configSistemaMarketplace);

$language = new Language($languages[$code]['directory']);

$language->load($languages[$code]['filename']);
$registry->set('language', $language);

//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));
// Affiliate
$registry->set('affiliate', new Affiliate($registry));

if (isset($request->get['tracking'])) {
	setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// CEO WEB SERVICE
$registry->set('wsceo', new Wsceo($registry));
// Futuracalcularst
$registry->set('futuracalcularst', new Futuracalcularst($registry));
// Futuratipo
$registry->set('productvisualized', new Product_visualized($registry));
// Cart
$registry->set('cart', new Cart($registry));
// BuyLater
$registry->set('buylater', new Buy_later($registry));
// fidelitycart
$registry->set('fidelitycart', new Fidelitycart($registry));
// Listaprsente
$registry->set('presente', new Presente($registry));
// MercadoLivre -- removerrrrrrr
$registry->set('mercadolivre', new Mercadolivre($registry));
// Shopee
$registry->set('shopee', new Shopee($registry));

$registry->set('marketplace', new MktPlace($registry));

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

// breadcrumbs
$registry->set('breadcrumbs', new Breadcrumbs($registry));

//productListTitle
$registry->set('productlistitle', new ProductListTitle($registry));

// APICielo 3.0
$registry->set('cieloapi', new Cielo_api($registry));
// Rede
$registry->set('rede', new Rede($registry));
// Yapay
$registry->set('yapay', new Yapay($registry));
//Paypal
$registry->set('paypal', new Paypal($registry));
// Getnet
$registry->set('getnet', new Getnet($registry));
// Pagarme
$registry->set('pagarme', new Pagarme($registry));
// Pagseguro API
$registry->set('pagseguroapi', new PagseguroAPI($registry));

//Email Validate
$registry->set('emailvalidate', new EmailValidate($registry));

// Clearsale
$loader->type('tipoclearsale');
if ( $config->get('clearsale_status') && in_array($config->get('clearsale_tipo_integracao'), array(Type_ClearSaleIntegracao::Tp_Total, Type_ClearSaleIntegracao::Tp_TotalGarantido)) ) {
	$registry->set('clearsale', new Clearsale($registry));
}

// Intelipost - Cotação de frete
if ($config->get('intelipost_status')){
  $registry->set('intelipost', new Intelipost($registry));
}

// DLog - Cotação de frete
if ($config->get('dlog_status')){
  $registry->set('dlog', new DLog($registry));
}

// Melhor Envio - Cotação de frete
$registry->set('melhorenvio', new Melhorenvio($registry));

// kangu - Cotação de frete
$registry->set('kangu', new Kangu($registry));

// Jadlog - Cotação de frete
if ($config->get('jadlog_transport_status')){
	$registry->set('jadlog', new JadLog($registry));
}

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

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

$registry->set('pagseguro', new pagseguro($registry));

$registry->set('sendtask', new Sendtask($registry));

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

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

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

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

// Modo Incompatibilidade com Internet Explorer
$controller->addPreAction(new Action('common/incompatible'));

// bloquear IP
$controller->addPreAction(new Action('common/ban_ip'));
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// Produtos maior de 18
$controller->addPreAction(new Action('common/ofage'));

// Redirecionamento 301
if ($config->get('redirecionamento301_status') == Type_Status::Tp_Habilitado){
	$controller->addPreAction(new Action('common/redirecionamento301'));
}

//aqui vem a logica do redirect
$controller->addPreAction(new Action('common/ecommerce_only'));

// Modo desenvolvimento
$controller->addPreAction(new Action('common/desenvolvimento'));

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

// futuracalcularst
$registry->get('futuracalcularst')->loadInstances($registry);
// 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();
