<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED );
include '../_plugins/medoo.php';
include '../settings.php';

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

$mdb_dr = new medoo( [
  'database_type' => 'mysql',
  'database_name' => 'admin_lulandia',
  'server' => 'dedyk8.cyber-folks.pl',
  'username' => 'admin_lulandia',
  "password" => '6_atdQ-N#xlN-t#0',
  'charset' => 'utf8'
] );

$mdb -> query( 'TRUNCATE TABLE estella_products_lulandia' );

$file = file_get_contents( 'https://b2b.estella.eu/generator/22413dfa-be6d-473d-b301-282351168cf6/xml/aa6648e6-c4a8-4af6-b6ae-33954c47886f' );
$doc = new DOMDocument();
$doc -> loadXML( $file );
$xpath = new DOMXPath( $doc );

$products = $xpath->query('//Document/Produkt');

foreach ( $products as $product )
{
  $indeks = $xpath -> query( 'Indeks', $product );
  $indeks_value = $indeks -> item(0) -> nodeValue;

  $nazwa = $xpath -> query( 'Nazwa', $product );
  $nazwa_value = $nazwa -> item(0) -> nodeValue;

  $ean = $xpath -> query( 'Ean', $product );
  $ean_value = $ean -> item(0) -> nodeValue;

  $mdb -> insert( 'estella_products_lulandia', [
      'sku' => $indeks_value,
      'name' => $nazwa_value,
      'ean' => $ean_value
    ] );
}

$estella_products = $mdb_dr -> query( 'SELECT id_product FROM materac_product_lang WHERE name LIKE \'%Estella%\' AND id_product > 0' ) -> fetchAll( PDO::FETCH_COLUMN, 0 );
$estella_products = array_unique($estella_products);
foreach ( $estella_products as $estella_product_id )
{
  $product = $mdb_dr -> get( 'materac_product', '*', [ 'id_product' => $estella_product_id ] );
  $product_reference = $product['reference'];

  if ( !$mdb -> count( 'estella_products_lulandia', [ 'sku' => $product_reference ] ) )
  {
    $mdb_dr -> update( 'materac_product', [ 'active' => 0 ], [ 'id_product' => $estella_product_id ] );
    $mdb_dr -> update( 'materac_product_shop', [ 'active' => 0 ], [ 'id_product' => $estella_product_id ] );
    echo 'Nie ma produktu w bazie Estella: ' . $product_reference . ', id: ' . $estella_product_id . '<br>';
  }
}