<?php
//define( 'WP_USE_THEMES', true );

/** Loads the WordPress Environment and Template */
//require (dirname(dirname(dirname(__DIR__))) . '/wp-blog-header.php');
//require (dirname(dirname(dirname(__DIR__))) . '/wp-blog-header.php');
if(!function_exists('mdLog')) {
    function mdLog($message)
    {
        print($message);
        flush();
        ob_flush();
    }
}
/*
//if ( ! defined( 'ABSPATH' ) ) {
$inHttp = (isset($_GET['debug-iquesta'])) ? 1 : 0;

if(!$inHttp) {
    $_SERVER['REMOTE_ADDR'] = 'crontobeerasmus';
    require_once dirname(dirname(dirname(__DIR__))) . '/wp-load.php';
}
*/
// $_SERVER['REMOTE_ADDR'] = 'crontobeerasmus';


/** Set up WordPress environment */
//require_once dirname(dirname(dirname(__DIR__))) . '/wp-load.php';

require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php');

//use \App\IquestaToMyListingJob;
$iQuesta =  App\IquestaToMyListingJob::getInstance();

//$returnIQ = $iQuesta->iQuestaSubjects();
//$returnIQ = $iQuesta->iQuestaRegions();
//$returnIQ = $iQuesta->iQuestaLevels();
//$returnIQ = $iQuesta->iQuestaContracts();
//IquestaToMyListingJob::print_r($returnIQ);

    // Liste des annonces actuelles
    $annoncesOnLine = array();
    $lastAnnonces = get_option( '_iQuestaLastAnnonces', array());

    $modeTest = 0;


    // Rechercher les informations
    $iQuestaArgs = array('country_id' => 1, 'page' => 1, 'take' => (($modeTest == 1) ? 1 : 200));
    mdLog(PHP_EOL);
    mdLog("##########################################################".PHP_EOL);
    mdLog("## TOBEERASMUS - IMPORT IQUESTA  version 1.0 by MD 2020 ##".PHP_EOL);
    mdLog("##########################################################".PHP_EOL);

    $returnIQ = $iQuesta->iQuestaOffers($iQuestaArgs);

    global $wpdb;
    // Rechercher l'ID du forfait partenaire iquesta
    $forfaitId = get_post_id_by_slug('forfait-partenaire-iquesta', 'product');
    //echo("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_product_id' AND  meta_value = '".$forfaitId."' LIMIT 1");
    $metaInfo = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_product_id' AND  meta_value = '".$forfaitId."' LIMIT 1");
    /*echo('<pre>');
    print_r($metaInfo);
    exit('</pre>');*/
    $metaInfo = $metaInfo[0];
    $forfaitUserId = $metaInfo->post_id;

    $maxPage = $returnIQ->last_page;
    $datas = $returnIQ->data;
    //print_r($datas);exit();

    $addUpdate = 0;
    $delete = 0;
    if($modeTest == 1)$maxPage = 1;
    // Traiter les données

    for($page=$maxPage; $page > 0; $page--) {
        $iQuestaArgs['page'] = $page;

        $returnIQ = $iQuesta->iQuestaOffers($iQuestaArgs);
        $datas = $returnIQ->data;
        mdLog("- Processing page " . $page . "/".$maxPage." : ");
        for($i=0; $i < count($datas); $i++) {
            $data = $datas[$i];
            //print_r($data);
            //exit();
            $data->idForfait = $forfaitId;
            $data->idUserForfait = $forfaitUserId;
            $iQuesta->mdSave($data);
            $addUpdate++;
            $annoncesOnLine[] = $data->id;
        }
        mdLog("ok".PHP_EOL);
    }

    $tmp = get_option( '_iQuestaLastAnnonces', false);
    if($tmp) {
        update_option( '_iQuestaLastAnnonces', $annoncesOnLine);
    } else {
        add_option( '_iQuestaLastAnnonces', $annoncesOnLine);
    }

    foreach ($lastAnnonces AS $k => $lastAnnonce) {
        if(!in_array($lastAnnonce, $annoncesOnLine)) {
            $optionIQuestaId = '__iquesta_id_'. $lastAnnonce;
            $tmp = get_option($optionIQuestaId, false);
            if($tmp) {
                $delete++;
                wp_delete_post( $tmp, true );
                delete_option($optionIQuestaId);
            }
        }
    }
//}
mdLog("- Added / Updated : " . $addUpdate.PHP_EOL);
mdLog("- Deleted : " . $delete.PHP_EOL);
mdLog("##########################################################".PHP_EOL);
mdLog(PHP_EOL);

if(count($iQuesta->getMdErrors()) > 0) {
    print_r($iQuesta->getMdErrors());
}
exit();

function get_post_id_by_slug( $slug, $post_type = "post" ) {
    $query = new WP_Query(
        array(
            'name'   => $slug,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields'      => 'ids',
        ) );
    $posts = $query->get_posts();
    return array_shift( $posts );
}