<?
namespace admin\controls;

class Integrations {

  // apilo_create_product
  static public function apilo_create_product()
  {
    global $mdb, $settings;

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $product_id = \S::get( 'product_id' );
    $product = new \shop\Product( $product_id );

    $methodParams = [
      "sku" => $product -> sku,
      "ean" => $product -> ean,
      "name" => $product -> language['name'],
      "tax" => (int) $product -> vat,
      'status' => 1,
      "quantity" => (int) $product -> quantity,
      "priceWithTax" => $product -> price_brutto,
      'description' => $product -> language['description'] . '<br>' . $product -> language['short_description'],
      'shortDescription' => '',
      'images' => []
    ];

    foreach ($product->images as $image) {
      $methodParams["images"][] = "https://" . $_SERVER['HTTP_HOST'] . $image['src'];
    }

    $ch = curl_init( "https://projectpro.apilo.com/rest/api/warehouse/product/" );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( [ $methodParams ] ) );
    curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Content-Type: application/json",
      "Accept: application/json"
    ] );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    }
    else
    {
      if ( $responseData['products'] )
      {
        $mdb -> update( 'pp_shop_products', [ 'apilo_product_id' => reset( $responseData['products'] ), 'apilo_product_name' => $product->language['name'] ], [ 'id' => $product -> id ] );
      }

      \S::alert( 'Produkt został dodany do magazynu APILO.' );
    }
    header( 'Location: /admin/shop_product/view_list/' );
    exit;
  }

  // baselinker_create_product
  static public function baselinker_create_product()
  {
    global $mdb, $settings;

    $api_code = \admin\factory\Integrations::baselinker_settings( 'api_code' );

    $product_id = \S::get( 'product_id' );
    $product = \shop\Product::getFromCache( $product_id, 'pl' );

    $methodParams = [
      "storage_id" => \admin\factory\Integrations::baselinker_settings('storage_id'),
      "ean" => $product->ean,
      "sku" => $product->sku,
      "name" => $product->language['name'],
      "quantity" => "0",
      "price_brutto" => $product->price_brutto,
      "tax_rate" => $product->vat,
      "description" => $product->language['short_description'],
      "description_extra1" => $product->language['description'],
      "images" => []
    ];

    foreach ($product->images as $image) {
      $methodParams["images"][] = "url:https://" . $_SERVER['HTTP_HOST'] . $image['src'];
    }

    $methodParams = json_encode( $methodParams, JSON_UNESCAPED_SLASHES );

    $apiParams = [
      "token" => $api_code,
      "method" => "addProduct",
      "parameters" => $methodParams
    ];

    $curl = curl_init( "https://api.baselinker.com/connector.php" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $apiParams ) );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    $response = json_decode( curl_exec( $curl ), true );

    if ( $response['status'] == 'SUCCESS' )
    {
      if ( $response['product_id'] )
      {
        $mdb -> update( 'pp_shop_products', [ 'baselinker_product_id' => $response['product_id'], 'baselinker_product_name' => $product->language['name'] ], [ 'id' => $product -> id ] );
      }

      \S::alert( 'Produkt został dodany do magazynu Baselinker.' );
    }
    else
    {
      \S::alert( 'Podczas dodawania produktu wystąpił błąd.' );
    }
    header( 'Location: /admin/shop_product/view_list/' );
    exit;
  }

  // baselinker pobierz listę magazynów
  static public function baselinker_get_storages_list()
  {
    global $mdb, $settings;

    $api_code = \admin\factory\Integrations::baselinker_settings( 'api_code' );

    $methodParams = '{
      "storage_id": "bl_1"
    }';

    $apiParams = [
      "token" => $api_code,
      "method" => "getStoragesList",
      "parameters" => $methodParams
    ];

    $curl = curl_init( "https://api.baselinker.com/connector.php" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $apiParams ) );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    $response = json_decode( curl_exec( $curl ), true );

    if ( $response['status'] == 'SUCCESS' )
    {
      \admin\factory\Integrations::baselinker_settings_save( 'storages_list', $response['storages'] );
      \S::alert( 'Lista magazynów została pobrana.' );
    }
    else
    {
      \S::alert( 'Brak wyników.' );
    }
    header( 'Location: /admin/integrations/baselinker_settings/' );
    exit;
  }

  // baselinker_get_order_status_list
  static public function baselinker_get_order_status_list()
  {
    global $mdb, $settings;

    $api_code = \admin\factory\Integrations::baselinker_settings( 'api_code' );

    $apiParams = [
      "token" => $api_code,
      "method" => "getOrderStatusList",
      "parameters" => []
    ];

    $curl = curl_init( "https://api.baselinker.com/connector.php" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $apiParams ) );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    $response = json_decode( curl_exec( $curl ), true );

    if ( $response['status'] == 'SUCCESS' )
    {
      \admin\factory\Integrations::baselinker_settings_save( 'order_status_list', $response['statuses'] );
      \S::alert( 'Lista statusów została pobrana.' );
    }
    else
    {
      \S::alert( 'Brak wyników.' );
    }
    header( 'Location: /admin/integrations/baselinker_settings/' );
    exit;
  }

  // get_sellasist_carriers_list
  static public function get_sellasist_shipments_list()
  {
    $api_code = \admin\factory\Integrations::sellasist_settings( 'api_code' );

    $ch = curl_init( "https://projectpro.sellasist.pl/api/v1/shipments" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "apiKey: " . $api_code,
      "accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    else {
      if ( $responseData ) {
        \admin\factory\Integrations::sellasist_settings_save( 'shipments_methods', $responseData );
        \S::alert( 'Lista przewoźników została pobrana.' );
      } else
        \S::alert( 'Brak wyników.' );
    }
    header( 'Location: /admin/integrations/sellasist_settings/' );
    exit;
  }

  // get_sellasist_payment_types_list
  static public function get_sellasist_payment_types_list()
  {
    $api_code = \admin\factory\Integrations::sellasist_settings( 'api_code' );

    $ch = curl_init( "https://projectpro.sellasist.pl/api/v1/payments" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "apiKey: " . $api_code,
      "accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    else {
      if ( $responseData ) {
        \admin\factory\Integrations::sellasist_settings_save( 'payment_types_list', $responseData );
        \S::alert( 'Lista metod płatności została pobrana.' );
      } else
        \S::alert( 'Brak wyników.' );
    }
    header( 'Location: /admin/integrations/sellasist_settings/' );
    exit;
  }

  static public function get_sellasist_status_types_list()
  {
    $api_code = \admin\factory\Integrations::sellasist_settings( 'api_code' );

    $ch = curl_init( "https://projectpro.sellasist.pl/api/v1/statuses" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "apiKey: " . $api_code,
      "accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    else {
      if ( $responseData ) {
        \admin\factory\Integrations::sellasist_settings_save( 'status_types_list', $responseData );
        \S::alert( 'Lista statusów została pobrana.' );
      } else
        \S::alert( 'Brak wyników.' );
    }
    header( 'Location: /admin/integrations/sellasist_settings/' );
    exit;
  }

  // get_platform_list
  static public function get_platform_list()
  {
    global $mdb, $settings;

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $url = "https://projectpro.apilo.com/rest/api/orders/platform/map/";
    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    }
    else
    {
      if ( $responseData )
      {
        \admin\factory\Integrations::apilo_settings_save( 'platform-list', $responseData );
        \S::alert( 'Lista platform została pobrana.' );
      }
      else
      {
        \S::alert( 'Brak wyników.' );
      }
    }
    header( 'Location: /admin/integrations/apilo_settings/' );
    exit;
  }

  // get_status_types_list
  static public function get_status_types_list()
  {
    global $mdb, $settings;

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $url = "https://projectpro.apilo.com/rest/api/orders/status/map/";
    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    }
    else
    {
      if ( $responseData )
      {
        \admin\factory\Integrations::apilo_settings_save( 'status-types-list', $responseData );
        \S::alert( 'Lista statusów została pobrana.' );
      }
      else
      {
        \S::alert( 'Brak wyników.' );
      }
    }
    header( 'Location: /admin/integrations/apilo_settings/' );
    exit;
  }

  // get_carrier_account_list
  static public function get_carrier_account_list()
  {
    global $mdb, $settings;

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $url = "https://projectpro.apilo.com/rest/api/orders/carrier-account/map/";
    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    }
    else
    {
      if ( $responseData )
      {
        \admin\factory\Integrations::apilo_settings_save( 'carrier-account-list', $responseData );
        \S::alert( 'Lista kont przewoźników została pobrana.' );
      }
      else
      {
        \S::alert( 'Brak wyników.' );
      }
    }
    header( 'Location: /admin/integrations/apilo_settings/' );
    exit;
  }

  // get_payment_types_list
  static public function get_payment_types_list()
  {
    global $mdb, $settings;

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $url = "https://projectpro.apilo.com/rest/api/orders/payment/map/";
    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      \S::alert( 'Błąd cURL: ' . curl_error( $ch ) );
    }
    else
    {
      if ( $responseData )
      {
        \admin\factory\Integrations::apilo_settings_save( 'payment-types-list', $responseData );
        \S::alert( 'Lista metod płatności została pobrana.' );
      }
      else
      {
        \S::alert( 'Brak wyników.' );
      }
    }
    header( 'Location: /admin/integrations/apilo_settings/' );
    exit;
  }

  // settings for the sellasist integration
  static public function sellasist_settings()
  {
    return \Tpl::view( 'integrations/sellasist-settings', [
      'settings' => \admin\factory\Integrations::sellasist_settings(),
    ] );
  }

  // settings for the Baselinker integration
  static public function baselinker_settings()
  {
    return \Tpl::view( 'integrations/baselinker-settings', [
      'settings' => \admin\factory\Integrations::baselinker_settings(),
    ] );
  }

  // settings for shoppro
  static public function shoppro_settings()
  {
    return \Tpl::view( 'integrations/shoppro-settings', [
      'settings' => \admin\factory\Integrations::shoppro_settings(),
    ] );
  }

  // Settings for the APILO plugin
  static public function apilo_settings()
  {

    return \Tpl::view( 'integrations/apilo-settings', [
      'settings' => \admin\factory\Integrations::apilo_settings(),
    ] );
  }

  // save settings for the shoppro integration
  static public function shoppro_settings_save()
  {

    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawień wystąpił błąd. Proszę spróbować ponownie.' ];
    $field_id = \S::get( 'field_id' );
    $value = \S::get( 'value' );

    if ( \admin\factory\Integrations::shoppro_settings_save( $field_id, $value ) )
      $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostały zapisane.', 'value' => $value ];

    echo json_encode( $response );
    exit;
  }

  // save settings for the sellasist integration
  static public function sellasist_settings_save()
  {

    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawień wystąpił błąd. Proszę spróbować ponownie.' ];
    $field_id = \S::get( 'field_id' );
    $value = \S::get( 'value' );

    if ( \admin\factory\Integrations::sellasist_settings_save( $field_id, $value ) )
      $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostały zapisane.', 'value' => $value ];

    echo json_encode( $response );
    exit;
  }

  // save settings for the Baselinker integration
  static public function baselinker_settings_save()
  {

    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawień wystąpił błąd. Proszę spróbować ponownie.' ];
    $field_id = \S::get( 'field_id' );
    $value = \S::get( 'value' );

    if ( \admin\factory\Integrations::baselinker_settings_save( $field_id, $value ) )
      $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostały zapisane.', 'value' => $value ];

    echo json_encode( $response );
    exit;
  }

  // Save settings for the APILO plugin
  static public function apilo_settings_save() {

    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania ustawień wystąpił błąd. Proszę spróbować ponownie.' ];
    $field_id = \S::get( 'field_id' );
    $value = \S::get( 'value' );

    if ( \admin\factory\Integrations::apilo_settings_save( $field_id, $value ) )
      $response = [ 'status' => 'ok', 'msg' => 'Ustawienia zostały zapisane.', 'value' => $value ];

    echo json_encode( $response );
    exit;
  }

  // Authorization in apilo.com
  static public function apilo_authorization() {

    $response = [ 'status' => 'error', 'msg' => 'Podczas autoryzacji wystąpił błąd. Proszę spróbować ponownie.' ];
    $settings = \admin\factory\Integrations::apilo_settings();

    if ( \admin\factory\Integrations::apilo_authorization( $settings['client-id'], $settings['client-secret'], $settings['authorization-code'] ) )
      $response = [ 'status' => 'ok', 'msg' => 'Autoryzacja przebiegła pomyślnie.' ];

    echo json_encode( $response );
    exit;
  }

  // sellasist product search by sku
  static public function sellasist_product_search() {
    global $mdb, $settings;

    $sku = $mdb -> get( 'pp_shop_products', 'sku', [ 'id' => \S::get( 'product_id' ) ] );

    if ( !$sku ) {
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podany produkt nie posiada kodu SKU.' ] );
      exit;
    }

    $url = "https://projectpro.sellasist.pl/api/v1/products";
    $params['symbol '] = $sku;
    $url .= '?' . http_build_query( $params );

    $api_code = \admin\factory\Integrations::sellasist_settings( 'api_code' );

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "apiKey: " . $api_code,
      "accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) )
    {
      echo 'Błąd cURL: ' . curl_error( $ch );
    }
    else
    {
      if ( $responseData['error'] )
      {
        echo json_encode( [ 'status' => 'error', 'msg' => 'Brak wyników dla podanego SKU.' ] );
        exit;
      }
      else
      {
        $return_data = array();
        $return_data['status'] = 'SUCCESS';
        $return_data['products'] = $responseData;
        echo json_encode( $return_data );
        exit;
      }
    }
    echo json_encode( [ 'status' => 'error', 'msg' => 'Brak wyników dla podanego SKU.' ] );
    exit;
  }

  // apilo product search by sku
  static public function apilo_product_search() {
    global $mdb, $settings;

    $sku = $mdb -> get( 'pp_shop_products', 'sku', [ 'id' => \S::get( 'product_id' ) ] );

    if ( !$sku ) {
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podany produkt nie posiada kodu SKU.' ] );
      exit;
    }

    $access_token = \admin\factory\Integrations::apilo_get_access_token();

    $url = "https://projectpro.apilo.com/rest/api/warehouse/product/";
    $params['sku'] = $sku;
    $url .= '?' . http_build_query( $params );

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer " . $access_token,
      "Accept: application/json"
    ] );

    $response = curl_exec( $ch );
    $responseData = json_decode( $response, true );

    if ( curl_errno( $ch ) ) {
      echo 'Błąd cURL: ' . curl_error( $ch );
    } else {
      if ( $responseData && isset( $responseData['products'] ) ) {
        $responseData['status'] = 'SUCCESS';
        echo json_encode( $responseData );
        exit;
      } else {
        echo json_encode( [ 'status' => 'SUCCESS', 'msg' => 'Brak wyników dla podanego SKU.', 'products' => '' ] );
        exit;
      }
    }
    echo json_encode( [ 'status' => 'SUCCESS', 'msg' => 'Brak wyników dla podanego SKU.', 'products' => '' ] );
    exit;
  }

  // wyszukiwanie produktu w bazie baselinkera
  static public function baselinker_product_search()
  {
    global $mdb, $settings;

    $api_code = \admin\factory\Integrations::baselinker_settings( 'api_code' );

    $sku = $mdb -> get( 'pp_shop_products', 'sku', [ 'id' => \S::get( 'product_id' ) ] );

    if ( !$sku ) {
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podany produkt nie posiada kodu SKU.' ] );
      exit;
    }

    $methodParams = '{
      "storage_id": "bl_1",
      "filter_sku": "' . $sku . '"
    }';

    $apiParams = [
      "token" => $api_code,
      "method" => "getProductsList",
      "parameters" => $methodParams
    ];

    $curl = curl_init( "https://api.baselinker.com/connector.php" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, http_build_query( $apiParams ) );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    $response = json_decode( curl_exec( $curl ), true );

    echo json_encode( $response );
    exit;
  }

  // sellasist_product_select_delete
  static public function sellasist_product_select_delete()
  {
    global $mdb;

    if ( \admin\factory\Integrations::sellasist_product_select_delete( \S::get( 'product_id' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas usuwania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  // apilo product select delete
  static public function apilo_product_select_delete()
  {
    global $mdb;

    if ( \admin\factory\Integrations::apilo_product_select_delete( \S::get( 'product_id' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas usuwania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  // baselinker delete product linking
  static public function baselinker_product_select_delete()
  {
    global $mdb;

    if ( \admin\factory\Integrations::baselinker_product_select_delete( \S::get( 'product_id' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas usuwania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  // sellasist_product_select_save
  static public function sellasist_product_select_save()
  {
    global $mdb;

    if ( \admin\factory\Integrations::sellasist_product_select_save( \S::get( 'product_id' ), \S::get( 'sellasist_product_id' ), \S::get( 'sellasist_product_name' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas zapisywania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  // apilo product select save
  static public function apilo_product_select_save()
  {
    global $mdb;

    if ( \admin\factory\Integrations::apilo_product_select_save( \S::get( 'product_id' ), \S::get( 'apilo_product_id' ), \S::get( 'apilo_product_name' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas zapisywania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  static public function baselinker_product_select_save() {
    global $mdb;

    if ( \admin\factory\Integrations::baselinker_product_select_save( \S::get( 'product_id' ), \S::get( 'baselinker_product_id' ), \S::get( 'baselinker_product_name' ) ) )
      echo json_encode( [ 'status' => 'ok' ] );
    else
      echo json_encode( [ 'status' => 'error', 'msg' => 'Podczas zapisywania produktu wystąpił błąd. Proszę spróbować ponownie.' ] );
    exit;
  }

  // shoppro_product_import
  static public function shoppro_product_import()
  {
    global $mdb;

    $shoppro_settings = \admin\factory\Integrations::shoppro_settings();

    $mdb2 = new \medoo( [
      'database_type' => 'mysql',
      'database_name' => $shoppro_settings[ 'db_name' ],
      'server' => $shoppro_settings[ 'db_host' ],
      'username' => $shoppro_settings[ 'db_user' ],
      'password' => $shoppro_settings[ 'db_password' ],
      'charset' => 'utf8'
    ] );

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

    $product = $mdb2 -> get( 'pp_shop_products', '*', [ 'id' => $product_id ] );
    if ( $product )
    {
      $mdb -> insert( 'pp_shop_products', [
        'price_netto' => $product[ 'price_netto' ],
        'price_brutto' => $product[ 'price_brutto' ],
        'vat' => $product[ 'vat' ],
        'stock_0_buy' => $product[ 'stock_0_buy' ],
        'quantity' => $product[ 'quantity' ],
        'wp' => $product[ 'wp' ],
        'sku' => $product[ 'sku' ],
        'ean' => $product[ 'ean' ],
        'custom_label_0' => $product[ 'custom_label_0' ],
        'custom_label_1' => $product[ 'custom_label_1' ],
        'custom_label_2' => $product[ 'custom_label_2' ],
        'custom_label_3' => $product[ 'custom_label_3' ],
        'custom_label_4' => $product[ 'custom_label_4' ],
        'additional_message' => $product[ 'additional_message' ],
        'additional_message_text' => $product[ 'additional_message_text' ],
        'additional_message_required' => $product[ 'additional_message_required' ],
        'weight' => $product[ 'weight' ]
      ] );

      $new_product_id = $mdb -> id();
      if ( $new_product_id )
      {
        $languages = $mdb2 -> select( 'pp_shop_products_langs', '*', [ 'product_id' => $product_id ] );
        if ( is_array( $languages ) )
        {
          foreach ( $languages as $language )
          {
            $mdb -> insert( 'pp_shop_products_langs', [
              'product_id' => $new_product_id,
              'lang_id' => $language['lang_id'],
              'name' => $language['name'],
              'short_description' => $language['short_description'],
              'description' => $language['description'],
              'tab_name_1' => $language['tab_name_1'],
              'tab_description_1' => $language['tab_description_1'],
              'tab_name_2' => $language['tab_name_2'],
              'tab_description_2' => $language['tab_description_2'],
              'meta_title' => $language['meta_title'],
              'meta_description' => $language['meta_description'],
              'meta_keywords' => $language['meta_keywords'],
              'seo_link' => $language['seo_link'],
              'copy_from' => $language['copy_from'],
              'warehouse_message_zero' => $language['warehouse_message_zero'],
              'warehouse_message_nonzero' => $language['warehouse_message_nonzero'],
              'canonical' => $language['canonical'],
              'xml_name' => $language['xml_name']
            ] );
          }
        }

        $images = $mdb2 -> select( 'pp_shop_products_images', '*', [ 'product_id' => $product_id ] );
        if ( is_array( $images ) )
        {
          foreach ( $images as $image )
          {
            $image_url = 'https://' . $shoppro_settings['domain'] . $image['src'];

            // pobierz zdjęcie za pomocą curl
            $ch = curl_init( $image_url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
            $image_data = curl_exec( $ch );
            $image_data;
            curl_close( $ch );

            // ścieżdka do nowego zdjęcia to "/upload/product_images/product_[product_id]/[nazwa_zdjęcia]
            $image_name = basename( $image_url );
            $image_path = '../upload/product_images/product_' . $new_product_id . '/' . $image_name;

            // utwórz katalog dla zdjęć produktu jeśli nie istnieje
            if ( !file_exists( '../upload/product_images/product_' . $new_product_id ) )
              mkdir( '../upload/product_images/product_' . $new_product_id, 0777, true );

            // zapisz zdjęcie
            file_put_contents( $image_path, $image_data );

            // zapisz zdjęcie w bazie danych
            $mdb -> insert( 'pp_shop_products_images', [
              'product_id' => $new_product_id,
              'src' => '/upload/product_images/product_' . $new_product_id . '/' . $image_name,
              'o' => $image['o']
            ] );
          }
        }

        \S::alert( 'Produkt został zaimportowany.' );
        header( 'Location: /admin/shop_product/view_list/' );
        exit;
      }
    }

    \S::alert( 'Podczas importowania produktu wystąpił błąd.' );
    header( 'Location: /admin/shop_product/view_list/' );
    exit;
  }
}