<?php
error_reporting( E_ALL & ~E_NOTICE );
function __autoload_my_classes( $classname )
{
  $q = explode( '\\' , $classname );
  $c = array_pop( $q );
  $f = 'autoload/' . implode( '/' , $q ) . '/class.' . $c . '.php';

  if ( file_exists( $f ) )
    require_once( $f );
}
spl_autoload_register( '__autoload_my_classes' );
date_default_timezone_set( 'Europe/Warsaw' );

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';
require_once 'libraries/phpmailer/class.phpmailer.php';
require_once 'libraries/phpmailer/class.smtp.php';

session_start();

$mdb = new medoo( [
                    'database_type' => 'mysql',
                    'database_name' => $database['name'],
                    'server'        => $database['host'],
                    'username'      => $database['user'],
                    'password'      => $database['password'],
                    'charset'       => 'utf8'
                ] );

if ( !$lang_id = \S::get_session( 'current-lang' ) )
{
  $lang_id = \front\factory\Languages::default_language();
  \S::set_session( 'current-lang', $lang_id );
}

if ( !$lang = \S::get_session( 'lang' ) )
{
  $lang = \front\factory\Languages::lang_translations();
  \S::set_session( 'lang', $lang );
}

\front\controls\Site::check_url_params();

if ( !$settings = \S::get_session( 'settings' ) )
{
  $settings = \front\factory\Settings::settings_details();
  \S::set_session( 'settings', $settings );
}

$a = \S::get( 'a' );

if ( $a == 'basket_change_transport' )
{
    \S::set_session( 'transport_id', \S::get( 'transport_id' ) );

    $basket         = \S::get_session( 'basket' );
    $basket_summary = \front\factory\ShopBasket::summary_price( $basket, null );
    $transport_cost = \front\factory\ShopTransport::transport_cost( \S::get( 'transport_id' ) );

    echo json_encode( [ 'summary' => \S::decimal( $basket_summary + $transport_cost ) . ' zł' ] );
    exit;
}

if ( $a == 'change_payment' )
{
    \S::set_session( 'payment_method_id', \S::get( 'payment_method_id' ) );
    $transports = \front\factory\ShopTransport::transports_list( \S::get( 'payment_method_id' ) );
    echo json_encode( [ 'transports' => $transports ] );
    exit;
}

if ( $a == 'contact_form' )
{
  if ( ( !\S::get( 'email' ) and \S::get( 'phone' ) ) )
    $response = [ 'status' => 'error' ];
  else
  {
    if ( \S::send_email( $settings['contact_email'],  \S::get( 'subject' ), \S::get( 'text' ) . '<p>Nr telefonu: ' . \S::get( 'phone' ) . '</p><p>Email: ' . \S::get( 'email' ) . '</p>', \S::get( 'email' ) ) )
      $response = [ 'status' => 'ok' ];
  }

  echo json_encode( $response );
  exit;
}

if ( $a == 'cookie_close' )
{
  setcookie( "cookie_information", "true", mktime( 0, 0, 0, 12, 31, 2115 ) );
  exit;
}

if ( $a == 'banner_close' )
{
  \S::set_session( 'banner_close', true );
}
?>