<?php
// Configuration
require_once('config.php');

//Startup
require_once(DIR_SYSTEM . 'startup.php');

//error_reporting(E_ALL & ~E_NOTICE);
// Application Classes
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/tax.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/seo.php');
require_once(DIR_SYSTEM . 'library/cdn_loader.php');
require_once(DIR_SYSTEM . 'library/cache/cache_db.php');

if (defined('DEVELOPER') && DEVELOPER && defined('BENCHMARK')  && BENCHMARK) {
    Benchmark::initStats();

    $sqlCache = "On";

    if (defined('DISABLE_SQL_CACHE') && DISABLE_SQL_CACHE) {
        $sqlCache = "Off";
    }
}

if(!empty($_GET['noCacheDB']) && $_GET['noCacheDB']=='reset'){
    CacheDB::flush();
}

// Registry
$registry = new Registry();

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

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

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

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

// Store
if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
    $store_query = $db->queryCache("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
} else {
    $store_query = $db->queryCache("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
}

if ($store_query->num_rows) {
    $config->set('config_store_id', $store_query->row['store_id']);
} else {
    $config->set('config_store_id', 0);
}
        
// Settings
$query = $db->queryCache("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) {
    if (!$setting['serialized']) {
        $config->set($setting['key'], $setting['value']);
        if($setting['group'])
            $config->set($setting['group'].':'.$setting['key'], $setting['value']);
    } else {
        $config->set($setting['key'], unserialize($setting['value']));
        if($setting['group'])
            $config->set($setting['group'].':'.$setting['key'], unserialize($setting['value']));
    }
}

if (!$store_query->num_rows) {
    $config->set('config_url', HTTP_SERVER);
    $config->set('config_ssl', HTTPS_SERVER);   
}

// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') : $config->get('config_url'), $registry);    
$registry->set('url', $url);

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

// Seo 
$seo = new Seo($registry);
$registry->set('seo', $seo);

// remote CDN
$cdn = new Cdn();
$registry->set('cdn', $cdn); 

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); 
        
// Cache
$cache = new Cache();
$registry->set('cache', $cache); 

// Session
$session = new Session();

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

// Language Detection
$languages = array();

$query = $db->queryCache("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 ($config->get('auto_language_status') && !isset($session->data['language'])) {
    $ip_address = $request->server['REMOTE_ADDR'];
    // $ip_address = '188.69.224.62';
    
    $geo_url = 'http://www.geoplugin.net/php.gp?ip=' . $ip_address;

    $address_details = unserialize(file_get_contents($geo_url));
        
    $city = $address_details['geoplugin_city'];
        
    $country = $address_details['geoplugin_countryName'];
    $country_code = $address_details['geoplugin_countryCode'];

    if(!$city) {
        $city='Not Define';
    }

    if(!$country) {
        $country='Not Define';
    }
    
    if(!$country_code) {
        $country_code='Not Define';
    }
        
    // print_r('<strong>Country</strong>:- '.$country_code.'<br/>');

    $country_info = $db->queryCache("SELECT DISTINCT * FROM " . DB_PREFIX . "country WHERE iso_code_2 = '" . $country_code . "'"); 

    $detect_languages = $config->get('auto_language_value');
            
    foreach ($detect_languages as $result) {
        $currency_info = $db->queryCache("SELECT DISTINCT * FROM " . DB_PREFIX . "currency WHERE     currency_id = '" . $result['currency_id'] . "'");

        $language_info = $db->queryCache("SELECT DISTINCT * FROM " . DB_PREFIX . "language WHERE    language_id = '" . $result['language_id'] . "' AND status = 1"); 

        $auto_detect[ $result['country_id'] ] = [
            'language_code'      => $language_info->row['code'],
            'currency_code'      => $currency_info->row['code'],
        ];
    }

    if(isset( $auto_detect[ $country_info->row['country_id'] ]['language_code'] )) {
        $code = $auto_detect[ $country_info->row['country_id'] ]['language_code'];

        if (isset($auto_detect[ $country_info->row['country_id'] ]['currency_code'])) {
            $session->data['currency'] = $auto_detect[ $country_info->row['country_id'] ]['currency_code'];
        }
    } else {
        $code = $config->get('config_language');
    }
} else 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']);

$seo->multilingual_detect();

// Language 
// Gettext [test]
// $gettext = new Gettext($languages[$code], 'domain');

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

$loader->helper('html');    

// 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']) && !isset($request->cookie['tracking'])) {
    setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
        
// Currency
$registry->set('currency', new Currency($registry));

// Tax
$registry->set('tax', new Tax($registry));

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

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

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

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

// Mail
$registry->set('mail', new Mail($registry));
        
// Front Controller 
$controller = new Front($registry);

// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));

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

// Check images does it exist
// if ($_SERVER['REMOTE_ADDR'] == '188.69.224.62') {
//     $query = $db->query("SELECT product_id, image FROM " . DB_PREFIX . "product");

//     $counter = 0;
//     $counter_fixed = 0;

//     foreach ($query->rows as $product) {
//         $counter++;

//         if (!file_exists(DIR_IMAGE . $product['image'])) {
//             $counter_fixed++;

//             $db->query("UPDATE product SET image = '' WHERE product_id = '" . $product['product_id'] ."'");
//         }
//     }

//     dump('Patikrinta ' . $counter . ' prekės, iš kurių buvo dingusios ' . $counter_fixed . ' prekiu nuotraukos');

//     // Additional product images
//     $query = $db->query("SELECT product_id, image FROM " . DB_PREFIX . "product_image");

//     $counter = 0;
//     $counter_fixed = 0;

//     foreach ($query->rows as $product) {
//         $counter++;

//         if (!file_exists(DIR_IMAGE . $product['image'])) {
//             $counter_fixed++;

//             $db->query("DELETE FROM product_image WHERE product_id = '" . $product['product_id'] ."'");
//         }
//     }

//     dump('Patikrinta ' . $counter . ' prekės, iš kurių buvo dingusios ' . $counter_fixed . ' prekiu nuotraukos');
// }

// If develop tools enable, run debug class
if (defined('DEVELOPER') && DEVELOPER && defined('BENCHMARK')  && BENCHMARK) {
    $BenchmarkLogs = new Log('slowQuery');

    $route = isset($request->get['route']) ? $request->get['route'] : '';

    $BenchmarkLine = "[" . $route . "]" . Benchmark::getMainStatsString() . "[Cache:" . 'empty' . "]" . "[SQLCache:" . $sqlCache . "]"; //$cache->getExpire()

    $BenchmarkLogs->write($BenchmarkLine);

    Benchmark::previewMainStats();
  
    if (defined('DB_LOG_TIME') && DB_LOG_TIME >= 0) {

        $slowQueries = Benchmark::getStatByKey('slow_query');

        if (!empty($slowQueries)) {
            $slowLogs = new Log('slowQuery'.time());

            foreach ($slowQueries as $slowQuery) {
                if(is_array($slowQuery)){
                    foreach($slowQuery as $slowQuery1){
                        $slowLogs->write($slowQuery1);
                    }
                }
                else{
                    $slowLogs->write($slowQuery);
                }
                
            }
        }
    }
}