<?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_drmaterac',
  'server' => 'dedyk8.cyber-folks.pl',
  'username' => 'admin_drmaterac',
  "password" => 'eRbZ]Ioh-0-2]fM+',
  'charset' => 'utf8'
] );

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

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

  if ( $mdb -> count( 'estella_products', [ 'sku' => $indeks_value ] ) == 0 )
  {
    $mdb -> insert( 'estella_products', [
      'sku' => $indeks_value,
      'name' => $nazwa_value,
      'ean' => $ean_value
    ] );
  }

  if ( $mdb -> count( 'estella_products_old', [ 'sku' => $indeks_value ] ) == 0 )
  {
    $mdb -> insert( 'estella_products_old', [
      'sku' => $indeks_value,
      'name' => $nazwa_value,
      'ean' => $ean_value
    ] );
  }
}

$products_to_delete = [];

$old_products = $mdb -> select( 'estella_products_old', [ 'sku' ] );
foreach ( $old_products as $product_tmp )
{
  if ( $mdb -> count( 'estella_products', [ 'sku' => $product_tmp['sku'] ] ) == 0 )
  {
    $products_to_delete[] = $product_tmp['sku'];
  }
}

foreach ( $products_to_delete as $product_to_delete )
{
  $product_id_tmp = $mdb_dr -> get( 'materac_product', 'id_product', [ 'reference' => $product_to_delete ] );
  if ( $product_id_tmp )
  {
    $mdb_dr -> update( 'materac_product', [ 'active' => 0 ], [ 'id_product' => $product_id_tmp ] );
    $mdb_dr -> update( 'materac_product_shop', [ 'active' => 0 ], [ 'id_product' => $product_id_tmp ] );
    echo '<p>Deaktywowano produkt: ' . $product_to_delete . '</p>';
  }
}