// Load WP Core require '../wp-load.php'; define( 'WPUSETHEMES', false );

// Endpoint //define( 'SERVERENDPOINT' , 'http://45.191.244.222:3000/update/' ); define( 'SERVERENDPOINT' , 'http://186.189.193.129:3000/update/' ); define( 'COMTARJCRED' , 1.075 ); define( 'DEBUG' , FALSE );

// Check if WP Rocket plugin es installed define( 'WPROCKETISON', false ); define( 'LSCACHEISON', false );

// BLACKFRIDAY OR CYBERMONDAY define( 'SALE_ON', false );

// Debug if( DEBUG ) { errorreporting(EALL); iniset('displayerrors', 1); }

// Functions function callEndpoint($url, $content){

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_ENCODING , "gzip");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($content));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200 && $status != 201){

    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

}

curl_close($curl);
return json_decode($json_response, true);

}

if (WPROCKETIS_ON) {

function rocket_preload_page ( $pages_to_preload, $args ){

    foreach( $pages_to_preload as $page_to_preload ) {
        wp_remote_get( esc_url_raw ( $page_to_preload ), $args );
    }

}

}

// Get all SKUs $args = array( 'poststatus' => 'publish', 'posttype' => 'product', 'postsperpage' => -1, 'order' => 'ASC' );

if( DEBUG ) echo '

';

$products = wcgetproducts( $args ); $skus = [];

foreach( $products as $product ) {

$skus[] = $product->get_sku();

}

// Cleaning memory $products = null;

$now = new DateTime();

$apidata = callEndpoint( SERVERENDPOINT, array( 'year' => $now->format('Y'), 'month' => $now->format('m'), 'skus' => $skus ));

// Cleaning memory $skus = null; $output = '';

/** * Aquí empezamos a Sincronizar * */

foreach( $apidata['cat'] as $apiprod ) {

$tc = $api_data['tc'];

if ( function_exists( 'wc_get_product' ) && !empty( wc_get_product_id_by_sku( $api_prod['sku'] )) && !empty($tc) && !empty($api_prod['pre']) && !empty($api_prod['inv'])) { 

    $ID = wc_get_product_id_by_sku( $api_prod['sku'] );
    $product = wc_get_product( $ID );
    $permalink = get_permalink( $ID );
    $output .= 'ID: ' . $ID . ' | SKU: ' . $api_prod['sku'];

    if(SALE_ON){

        if( $api_prod['esp'] < $api_prod['may'] ) {
            $saleprice = $api_prod['esp'];
        } else {
            $saleprice = $api_prod['may'];
        }

    } else {
        $saleprice = $api_prod['esp'];
    }

    $SyncType = get_post_meta( $ID, 'sincronizacion' , true);

    if($SyncType == 'sinprecio'){

        $output .= ' | Sincronización sin Precio';

    } else {
        // Sync Prince, Regular Prices & Sale Price
        if( !empty($api_prod['pre']) && ceil($api_prod['pre'] * number_format($tc, 2, '.', '') * COM_TARJ_CRED) < $product->get_price() || ceil($api_prod['pre'] * number_format($tc, 2, '.', '') * COM_TARJ_CRED) > $product->get_price() ) {

            $output .= ' | Old Price: ' . $product->get_price();
            $product->set_regular_price(ceil($api_prod['pre'] * number_format($tc, 2, '.', '') * COM_TARJ_CRED));
            $product->set_price( ceil($api_prod['pre'] * number_format($tc, 2, '.', '') * COM_TARJ_CRED) );
            $output .= ' | NEW Price: ' . ceil($api_prod['pre'] * number_format($tc, 2, '.', '') * COM_TARJ_CRED) ;
            $output .= ' | SALE Price: ' . ceil($saleprice * number_format($tc, 2, '.', '') * COM_TARJ_CRED) ;

            if(SALE_ON){ 

                $product->set_sale_price( ceil($saleprice * number_format($tc, 2, '.', '') * COM_TARJ_CRED) );

            } else {

                if( $api_prod['pre'] == $saleprice ) {

                    $product->set_sale_price( false );

                } else {

                    $product->set_sale_price( ceil($saleprice * number_format($tc, 2, '.', '') * COM_TARJ_CRED) );

                }

            }

            // Clean Cache and Preload
            $pages_to_clean_preload = [ $permalink ];

            if( WP_ROCKET_IS_ON ) {

                if ( function_exists( 'rocket_clean_post' ) ) {

                    foreach( $pages_to_clean_preload as $page_to_clean) {
                        rocket_clean_post( url_to_postid ( $page_to_clean ) );
                    }
                }

                if ( function_exists( 'get_rocket_option' ) ) {

                    if( 1 == get_rocket_option( 'manual_preload' ) ) {

                        $args = array();

                        if( 1 == get_rocket_option( 'cache_webp' ) ) {
                            $args[ 'headers' ][ 'Accept' ]          = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
                            $args[ 'headers' ][ 'HTTP_ACCEPT' ]     = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
                        }

                        // Preload desktop pages/posts.
                        rocket_preload_page( $pages_to_clean_preload, $args );

                        if( 1 == get_rocket_option( 'do_caching_mobile_files' ) ) {
                            $args[ 'headers' ][ 'user-agent' ]  = 'Mozilla/5.0 (Linux; Android 8.0.0;) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Mobile Safari/537.36';

                            // Preload mobile pages/posts.
                            rocket_preload_page(  $pages_to_clean_preload, $args );
                        }
                    }
                }

                $output .= ' | Flush Cache: Sí';

            }

            if( LS_CACHE_IS_ON ) {
                do_action( 'litespeed_purge_url', $permalink );
            }



        }

    }

    // Sync Stock
    $inventario = $api_prod['inv'];
    $total = 0;

    foreach( $inventario as $k => $inv ) {

        $total += $inv['stock'];

    }

    $product->set_manage_stock( 'yes' );
    $product->set_stock_quantity( $total );

    if( $total > 0 ) {

        $product->set_stock_status( 'instock' );

    } else {

        $product->set_stock_status( 'outstock' );

    }

    $output .= ' | Stock: ' . $total ;

    // Sync Mayoristas
    update_post_meta($ID, '_wwp_wholesale_amount', ceil( $api_prod['may'] * $tc * COM_TARJ_CRED) );
    update_post_meta($ID, '_wwp_wholesale_amount_cash', ceil( $api_prod['may'] * $tc ) );
    update_post_meta($ID, '_wwp_enable_wholesale_item', 'yes' );
    update_post_meta($ID, '_wwp_wholesale_type', 'fixed' );

    $output .= ' | Mayorista: ' . $api_prod['may'] ;
    $output .= ' | TC: ' . $tc ;
    $output .= ' | Precio Dols: ' . $api_prod['pre'] ;
    $output .= ' | Precio Esp: ' . $saleprice ;

    // Sync Cash 
    if( $api_prod['pre'] == $saleprice ) {

        $product->set_sale_price( false );

        update_post_meta($ID, 'en-efectivo', 'Q' . number_format(ceil($api_prod['pre'] * $tc ), 2, '.', ',') );
        $output .= ' | Efectivo: ' . 'Q' . number_format(ceil($api_prod['pre'] * $tc), 2, '.', ',') ;

    } else {

        $product->set_sale_price( ceil($saleprice * number_format($tc, 2, '.', '') * COM_TARJ_CRED) );

        update_post_meta($ID, 'en-efectivo', 'Q' . number_format(ceil($saleprice * $tc ), 2, '.', ',') );
        $output .= ' | Efectivo: ' . 'Q' . number_format(ceil($api_prod['pre'] * $tc), 2, '.', ',') ;

    }

    // Sync Bodegas
    $bodegas = json_encode($inventario);
    update_post_meta($ID, 'bodegas', $bodegas );


    // Sync Title
    $title = $product->get_name();

    $product->set_name( $api_prod['name'] . ' - ' . $api_prod['sku'] );

    // Saving 
    $product->save();

    $output .= "\n";

}

}

// Cleaning memory $api_data = null;

$sendmail = wp_mail("informatica@macrosistemas.gt","MACROSISTEMAS - Reporte Sincronizador", $output, '');

if( DEBUG ) echo $output; $output = '';

echo "\n\r" . 'Tiempo de Ejecución: ', microtime(TRUE) - $time . "\n\r";