<?php
namespace App;

use GuzzleHttp\Client;
use \App;
//use \MyListing\Src\Endpoints\Term_List_Endpoint;

/**
 *
 */

class IquestaToMyListingJob  extends \App\ToMyListingJob {

    private $_iQuestaClient;
    private $_iQuestaApiKey; // YOUR SECRET KEY
    private $_iQuestaApiUrl;
    private $_iQuestaDebug;

    private $_mdErrors = array();

    protected static $_instance;

    private $_iQuestaUserAccount = false;
    private $_iQuestaNotFound = array();
    private $_iQuestaCorrespondance = array(
        'secteur_dactivit' => array(
            '1' => 'Achat',
            '2' => 'Transport/Logistique',
            '3' => 'Commerce/Distribution',
            '4' => 'Télévente / Hotline',
            '5' => 'Commerce/Distribution',
            '6' => 'Marketing',
            '7' => 'Marketing Digital / e-Commerce',
            '8' => 'Communication / Evénementiel',
            '9' => 'Journalisme / RP / Edition / Traduction',
            '10' => 'Documentation / Veille',
            '11' => 'RH / Recrutement',
            '13' => 'Services publics/Administration',
            '16' => 'Banque/Assurance/Finance',
            '17' => 'Banque/Assurance/Finance',
            '18' => 'Banque/Assurance/Finance',
            '19' => 'Banque/Assurance/Finance',
            '20' => 'Statistiques',
            '21' => 'Gestion de projets & Organisation',
            '22' => 'Econométrie',
            '23' => 'Droit des Affaires / Fiscalité',
            '24' => 'Droit',
            '25' => 'Graphisme / Multimédia',
            '26' => 'Informatique - Conseil',
            '27' => 'Informatique - Développement',
            '28' => 'Informatique de Gestion',
            '29' => 'Systèmes et Réseaux',
            '30' => 'Télécom/Internet/Média',
            '31' => 'Agroalimentaire',
            '32' => 'Industrie/Environnement',
            '33' => 'Qualité / Hygiène / Sécurité',
            '34' => 'Physique et Analyse',
            '35' => 'Chimie',
            '36' => 'Géologie / Géochimie',
            '37' => 'Biologie',
            '38' => 'Médecine/Santé',
            '39' => 'Ingénierie',
            '40' => 'Gestion de Production',
            '41' => 'Mécanique',
            '43' => 'Technique / Maintenance',
            '44' => 'Aéronautique',
            '47' => 'Energétique',
            '48' => 'Sciences des Matériaux',
            '51' => 'Immobilier',
            '52' => 'BTP/Construction',
            '53' => 'Architecture / Urbanisme / Paysage',
            '54' => 'Social',
            '75' => 'Conseil / Stratégie / Management',
            '56' => 'Tourisme',
            '57' => 'Artisanat',
            '58' => 'Stylisme',
            '72' => 'Entretien / Sécurité',
            '61' => 'Accueil / Hôte(sse)',
            '62' => 'Tourisme',
            '63' => 'Autres',
            '64' => 'Chauffeur / Livreur / Coursier',
            '65' => 'Commerce/Distribution',
            '66' => 'Cours à Domicile',
            '67' => 'Enquêteur',
            '68' => 'Manutention / Inventaire',
            '69' => 'Hôtellerie/Restauration',
            '70' => 'Télémarketing',
            '71' => 'Electricité / Electrotechnique',
            '74' => 'Data / Mathématiques Appliquées',
        ),
        'ville'            => array(),
        'job_tags'         => array(
            '1' => 'Stage',
            '2' => 'Alternance',
            '3' => 'VIE',
            '4' => 'CDD',
            '6' => 'CDI',
            '8' => 'Autre',
            '9' => 'Autre',
            '10' => 'Autre',
        ),
        'job_category'     => array(),
        'secteur_de_recherche' => array(
            '1' => array('Lorraine', 'Alsace', 'Champagne-Ardenne'),
            '2' => array('Poitou-Charentes', 'Aquitaine'),
            '3' => array('Rhône-Alpes', 'Auvergne'),
            '4' => array('Haute-Normandie', 'Basse-Normandie'),
            '5' => array('Franche-Comté', 'Bourgogne'),
            '6' => array('Bretagne'),
            '7' => array('Centre', 'Limousin'),
            '8' => array('Corse'),
            '9' => array('Guadeloupe', 'Martinique', 'Guyane', 'La Réunion', 'Mayotte'),
            '10' => array('Ile-de-France'),
            '11' => array('Midi-Pyrénées', 'Languedoc-Roussillon'),
            '12' => array('Nord-Pas-de-Calais', 'Picardie'),
            '13' => array('Pays de la Loire'),
            '14' => array('Provence-Alpes-Côte d\'Azur'),
            '24' => array('France'),
            '25' => array('Europe', 'Monde'),
        ),
        'niveau_requis_pour_postuler' => array(
            '100' => 'Indifférent',
            '12' => 'Sans niveau',
            //'' => 'Terminale',
            '10' => 'CAP',
            '11' => 'BEP',
            '0' => 'BAC',
            '1' => 'BAC +1',
            '2' => 'BAC +2',
            '3' => 'BAC +3',
            '4' => 'BAC +4',
            '5' => 'BAC +5',
            '6' => 'BAC +6',
        ),

    );

    function getMdErrors() {
        return $this->_mdErrors;
    }

    function __construct($debug = false)
    {
        $this->_iQuestaApiUrl = 'https://api2.iquesta.com';
        //$this->_iQuestaApiUrl = 'http://api2.iquesta.com';
        $this->_iQuestaApiKey = KEY_IQUESTA;
        $this->_iQuestaClient = new Client();
        $this->_iQuestaDebug = $debug;

        $newCorre = array();
        foreach($this->_iQuestaCorrespondance AS $k => $v) {
            $newCorre[$k] = array();
            foreach($v AS $k2 => $v2) {
                if(!in_array($k, array('secteur_dactivit', 'secteur_de_recherche', 'niveau_requis_pour_postuler'))) {
                    $newCorre[$k][$this->mdConvStr($k2)] = $this->mdConvStr($v2);
                } else {
                    $newCorre[$k][$this->mdConvStr($k2)] = $v2;
                }
            }

        }
        $this->_iQuestaCorrespondance = $newCorre;

        $this->_iQuestaUserAccount = get_user_by('login', 'iquesta');

        $this->mdInitCorrespondance();

        parent::__construct();
    }

    /** Enlever les accents */
    public static function replaceAccent( $string ) {
        $string = htmlentities( $string, ENT_NOQUOTES, 'utf-8' );
        $string = preg_replace( '#&([A-za-z])(?:uml|circ|tilde|acute|grave|cedil|ring);#', '\1', $string );
        $string = preg_replace( '#&([A-za-z]{2})(?:lig);#', '\1', $string );
        $string = preg_replace( '#&[^;]+;#', '', $string );

        return $string;
    }

    /** String to slug */
    public static function toSlug( $string = '' ) {
        if(is_object($string)) {
            if(isset($string->slug))return $string->slug;
        }
        $string = self::replaceAccent( strtolower( $string ) );
        $string = preg_replace( "/ /", "-", $string );
        $string = preg_replace( "/_/", "-", $string );
        $string = preg_replace( "/[^[:alnum:]-]/", "-", $string );
        $string = preg_replace( "/-+/", "-", $string );
        $string = preg_replace( "/^(-+)/", "", $string );
        $string = preg_replace( "/(-+)$/", "", $string );

        return $string;
    }

    public function mdConvStr($c) {
        return $this->toSlug($c);
    }

    public function mdInitCorrespondance() {
        // Ville
        $taxonomies = get_terms( array(
            'taxonomy' => 'region',
            'hide_empty' => false
        ));
        $tmp = array();
        foreach($taxonomies AS $k => $taxonomie) {
            $key = $this->mdConvStr($taxonomie->name);
            $tmp[$key] = $taxonomie->term_id;
            if(isset($this->_iQuestaCorrespondance['ville'][$key])) {
                $tmp[$key] = $this->_iQuestaCorrespondance['ville'][$key];
            }
        }
        foreach($this->_iQuestaCorrespondance['ville'] AS $k => $v) {
            $key = $this->mdConvStr($v);
            $val = (isset($tmp[$key])) ? $tmp[$key] : 0;
            $tmp[$k] = $val;
        }
        $this->_iQuestaCorrespondance['ville'] = $tmp;

        // Job_tags
        $taxonomies = get_terms(array(
            'taxonomy' => 'case27_job_listing_tags',
            'hide_empty' => false,
            'listing_type' => 2912,
        ));
        $tmp = array();
        foreach($taxonomies AS $k => $taxonomie) {
            //$tmp[$this->mdConvStr($taxonomie)] = $k;
            $tmp[$taxonomie->slug] = $taxonomie->term_id;
        }
        $this->_iQuestaNotFound['job_tags'] = (isset($tmp['autre'])) ? $tmp['autre'] : 0;
        foreach($this->_iQuestaCorrespondance['job_tags'] AS $k => $v) {
            $key = $this->mdConvStr($v);
            $val = (isset($tmp[$key])) ? $tmp[$key] : 0;
            $this->_iQuestaCorrespondance['job_tags'][$k] = $val;
        }

        // job_category
        $taxonomies = get_terms( array(
            'taxonomy' => 'job_listing_category',
            'hide_empty' => false
        ));
        $tmp = array();
        foreach($taxonomies AS $k => $taxonomie) {
            $this->_iQuestaCorrespondance['job_category'][$this->mdConvStr($taxonomie->name)] = $taxonomie->term_id;
        }
    }

    public static function getInstance() {
        if( self::$_instance === NULL ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __call($method,$arguments)
    {
        // Set Data
        if(preg_match('|^mdSetData|', $method)) {
            $return = '';
            $data = $arguments[0];
            $method = preg_replace('|^mdSetData|', '', $method);
            //echo('METHOD CALL :'.$method."\n");
            switch($method) {
                case 'niveau_requis_pour_postuler':
                    if(isset($data->levels)) {
                        $levelId = (isset($data->levels[0])) ? $data->levels[0]->id : '';
                        if($levelId === '')$return = $this->_iQuestaCorrespondance['niveau_requis_pour_postuler']['100'];
                        else {
                            $return = (isset($this->_iQuestaCorrespondance['niveau_requis_pour_postuler'][$levelId])) ? $this->_iQuestaCorrespondance['niveau_requis_pour_postuler'][$levelId] : $this->_iQuestaCorrespondance['niveau_requis_pour_postuler']['100'];
                        }
                    }
                    break;
                case 'nom_de_la_structure';
                    $return = $data->company_name;
                    break;
                case 'contact';
                    $return = $data->contact;
                    break;
                case 'job_title';
                    $return = $data->title;
                    break;
                case 'region';
                    $key = $this->mdConvStr($data->city);
                    $return = (isset($this->_iQuestaCorrespondance['ville'][$key])) ? $this->_iQuestaCorrespondance['ville'][$key] : $this->_iQuestaCorrespondance['ville']['autres'];
                    $return = array($return);
                    break;
                case 'job_description';
                    $return = $data->description;
                    break;
                case 'job_category';
                    $return = $this->_iQuestaCorrespondance['job_category']['offres']; // Offre
                    break;
                case 'secteur_dactivit';
                    $methodCorrespondance = 'mdCheckCorrespondance'.$method;
                    $id = $data->subject->id;
                    $return = $this->$methodCorrespondance($id, 'subject/id');
                    if (preg_match('|^@@@ERROR###|', $return)) {
                        $return = 'Autres';
                    }
                    break;
                case 'adresse_de_la_structure';
                    $address = trim($data->address);
                    $zipCode = trim($data->zip_code);
                    $ville = $data->city;
                    $return = '';
                    if(($address != '') && ($address != '.'))$return = $address." ";
                    if(($zipCode != '') && ($zipCode != '.'))$return .= $zipCode." ";
                    $return .= $ville;
                    $return = trim($return);
                    break;
                case 'publication':
                    $return = $data->created_at;
                    break;
                case 'mail_de_contact_de_formulaire':
                    $return = $this->_iQuestaUserAccount->data->user_email;
                    break;
                case 'job_tags';
                    $methodCorrespondance = 'mdCheckCorrespondance'.$method;
                    $id = $data->contract->id;
                    $return = $this->$methodCorrespondance($id, 'contract/id');
                    if (preg_match('|^@@@ERROR###|', $return)) {
                        $return = $this->_iQuestaNotFound['job_tags'];
                    }
                    $return = array($return);
                    break;
                case 'job_date':
                    if ($data->begin_min_at > $data->begin_max_at)
                        $return = $data->begin_max_at;
                    else
                        $return = $data->begin_min_at;
                    break;
                case 'dure':
                    if ($data->duration_min > $data->duration_max)
                        $tmpDuring = $data->duration_max;
                    else
                        $tmpDuring = $data->duration_min;
                    if($tmpDuring < 1)$return = 'Moins d\'un mois';
                    elseif(($tmpDuring >= 1) && ($tmpDuring < 2))$return = '1 mois - 2 mois';
                    elseif(($tmpDuring >= 2) && ($tmpDuring < 6))$return = '2 mois - 6 mois';
                    else $return = '6 mois - et plus';
                    break;
                case 'secteur_de_recherche':
                    $methodCorrespondance = 'mdCheckCorrespondance'.$method;
                    $id = $data->region->id;
                    $return = $this->$methodCorrespondance($id, 'contract/id');
                    break;
                case 'job_expires':
                    $return = preg_replace('| .*$|', '', $data->expire_at);
                    $return = '2020-06-06';
                    break;
                case 'nom-de-la-structure':
                    $return = 'MICKKK';
                    break;
                default:
                    $return = '';
                    break;
            }
            return $return;

        } elseif(preg_match('|^mdCheckCorrespondance|', $method)) {
            $data = $arguments[0];
            $fromInfo = $arguments[1];
            $method = preg_replace('|^mdCheckCorrespondance|', '', $method);
            /*switch($method) {
                case 'secteur_dactivit';
                    $list = array(
                        '63' => 'youpi'
                    );*/
                    if(isset($this->_iQuestaCorrespondance[$method][$data]))return $this->_iQuestaCorrespondance[$method][$data];
                    return '@@@ERROR###'.$fromInfo.'/'.$data;
                    /*break;
            }*/

        } else {
            trigger_error('Call to undefined method '.__CLASS__.'::'.$method.'()', E_USER_ERROR);
        }
    }

    public function mdSave($data) {

        // Listing Package ID
        $args = array(
            'name'           => 'forfait-partenaire-iquesta',
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => 1
        );
        $tmp = get_posts( $args );
        $listingPackageID = (count($tmp) > 0) ? $tmp[0]->ID : false;
        if(!$listingPackageID)exit('listingPackageID not found');

        $this->job_id = false;
        //$ Regarder si c'est un ajout ou une mise à jour
        $optionIQuestaId = '__iquesta_id_'. $data->id;
        $addIQuestaOption = true;
        $tmp = get_option($optionIQuestaId, false);
        if($tmp) {
            $tmp2 = get_post($tmp);
            if(!$tmp2) {
                delete_option($optionIQuestaId);
            }
            else {
                $this->job_id = $tmp;
                $addIQuestaOption = false;
            }
        }

        //exit('#'.$this->_iQuestaUserAccount->data->ID.'#');

        //echo('#'.$data->id.'#'.$this->job_id."#\n");

        $_GET['listing_type'] = 'job';

        $_POST = array(
            'submit_job' => 'submit--no-preview',
            'region' => $this->mdSetDataregion($data),
            'job_category' => $this->mdSetDatajob_category($data),
            //'current_job_cover' => '',
            'nom-de-la-structure' => $this->mdSetDatanom_de_la_structure($data),
            'secteur-dactivit' => $this->mdSetDatasecteur_dactivit($data),
            'adresse-de-la-structure' => $this->mdSetDataadresse_de_la_structure($data),
            'nom-du-responsable' => $this->mdSetDatacontact($data),
            'publication' => $this->mdSetDatapublication($data),
            'mail-de-contact-de-formulaire' => $this->mdSetDatamail_de_contact_de_formulaire($data),
            'email-du-contact-iquesta' => $this->mdSetDatamail_de_contact_de_formulaire($data),
            'contact-mail' => $this->mdSetDatamail_de_contact_de_formulaire($data),
            'job_title' => $this->mdSetDatajob_title($data),
            'job_description' => $this->mdSetDatajob_description($data),
            'job_tags' => $this->mdSetDatajob_tags($data),
            'job_date' => $this->mdSetDatajob_date($data),
            'dure' => $this->mdSetDatadure($data),
            'niveau-requis-pour-postuler' => $this->mdSetDataniveau_requis_pour_postuler($data),
            'secteur-de-recherche' => $this->mdSetDatasecteur_de_recherche($data),
            'listing-author' => '',
            'listing-expiry-date' => '',
            'job_manager_form' => '',
            //'job_id' => 0,
            'step' => 1,
            'listing_type' => 'job',
            //'listing_package' => '50384',
            'listing_package' => $listingPackageID,
        );
        //self::print_r($_POST);
        $jobCover = '';
        if($addIQuestaOption) {
            // Image aléatoire cover
            $path = get_template_directory().'-child'.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'partenaires';
            $scanned_directory_tmp = array_diff(scandir($path), array('..', '.'));
            $scanned_directory = array();
            foreach($scanned_directory_tmp AS $kScF => $vScF) {
                if(preg_match('|^[0-9]+\.|', $vScF)) {
                    $scanned_directory[] = $vScF;
                }
            }
            $file = $scanned_directory[array_rand($scanned_directory)];
            $urlFile = get_stylesheet_directory_uri() . '/assets/img/partenaires/' . $file;
            $jobCover = array($urlFile);


        } else {
            $jobCover = get_post_meta( $this->job_id, '_job_cover' );
            $jobCover = $jobCover[0];
        }

        /*echo('<pre>');
        print_r($_POST);
        exit();*/

        $this->md_submit_handler($data);
        $this->md_done();
        //exit('hhhh');

        if($addIQuestaOption) {
            add_option( $optionIQuestaId, $this->job_id);

            update_post_meta( $this->job_id, '_iquesta_id', $data->id );
            update_post_meta( $this->job_id, '_package_id', $data->idForfait );
            update_post_meta( $this->job_id, '_user_package_id', $data->idUserForfait );

            //update_post_meta( $this->job_id, '_job_expires', date( 'Y-m-d', strtotime( sanitize_text_field( $_POST['job_expires'] ) ) ) );
            wp_update_post( [
                'ID' => $this->job_id,
                'post_author' => $this->_iQuestaUserAccount->data->ID,
            ] );
        }

        update_post_meta( $this->job_id, '_job_cover', $jobCover );
    }

    public function md_submit_handler($data) {
        if ( empty( $_POST['submit_job'] ) ) {
            return;
        }

        // get the listing type
        if ( ! empty( $this->job_id ) ) {
            $listing = \MyListing\Src\Listing::get( $this->job_id );
            $type = $listing ? $listing->type : false;
        } elseif ( $type_slug = c27()->get_submission_listing_type() ) {
            $type = \MyListing\Src\Listing_Type::get_by_name( $type_slug );
        }

        $this->listing_type = $type;

        // if field validation throws any errors, cancel submission
        $this->md_validate_fields($data);
        if ( ! empty( $this->errors ) ) {
            print_r($this->errors);
            /*print_r($this->_mdErrors);
            print_r($data);
            print_r($_POST);*/
            return;
        }

        $description = isset( $this->fields['job_description'] ) ? $this->fields['job_description']['value'] : '';

        // validation passed successfully, update the listing
        $this->md_save_listing( $this->fields['job_title']['value'], $description, $this->job_id ? '' : 'preview' );
        $this->md_update_listing_data();

        // add custom listing data
        //do_action( 'mylisting/submission/save-listing-data', $this->job_id, $this->fields );

        // add custom listing data
        update_post_meta( $this->job_id, '_job_edited', time() );
        do_action( 'mylisting/submission/save-listing-data', $this->job_id, $this->fields );
        do_action( 'mylisting/submission/listing-updated', $this->job_id );

        // refresh listing
        $listing = \MyListing\Src\Listing::force_get( $this->job_id );

        // successful, show next step
        $this->step++;
    }

    protected function md_update_listing_data() {
        $listing = \MyListing\Src\Listing::get( $this->job_id );

        /**
         * Attach the listing type to the listing. Ensures it's the submission form,
         * before the listing with preview status has been created.
         *
         * @since 2.0
         */
        if ( empty( $_REQUEST['job_id'] ) && ( $listing_type = c27()->get_submission_listing_type() ) ) {
            if ( $type = \MyListing\Src\Listing_Type::get_by_name( $listing_type ) ) {
                update_post_meta( $this->job_id, '_case27_listing_type', $type->get_slug() );
            }
        }

        /**
         * Update listing meta data.
         *
         * @since 2.1
         */
        foreach ( $this->fields as $key => $field ) {
            // update
            $field->set_listing( $listing );
            $field->update();
        }

        if ( isset( $_POST['job_description'] ) ) {
            update_post_meta( $this->job_id, '_job_description', wp_kses_post( $_POST['job_description'] ) );
        }
    }

    protected function md_save_listing( $post_title, $post_content, $status = 'preview' ) {
        $data = [
            'post_title' => $post_title,
            'post_name' => sanitize_title( $post_title ), // update slug
            'post_content' => $post_content,
            'post_type' => 'job_listing',
            'comment_status' => 'open',
        ];

        if ( $status ) {
            $data['post_status'] = $status;
        }

        $data = apply_filters( 'mylisting/submission/save-listing-arr', $data, $this->job_id );

        if ( $this->job_id ) {
            $data['ID'] = $this->job_id;
            wp_update_post( $data );
        } else {
            $this->job_id = wp_insert_post( $data );
        }
    }

    public function md_validate_fields($data) {
        try {
            // check if it's a valid listing type
            if ( ! $this->listing_type ) {
                throw new \Exception( _x( 'Invalid listing type', 'Add listing form', 'my-listing' ) );
            }

            // make sure the user is logged in if submission requires an account
            /*if ( mylisting_get_setting( 'submission_requires_account' ) && ! is_user_logged_in() ) {
                throw new \Exception( _x( 'You must be signed in to post a new listing.', 'Add listing form', 'my-listing' ) );
            }*/
        } catch ( \Exception $e ) {
            $this->add_error( $e->getMessage() );
            $this->_mdErrors[] = 'ID Iquesta #'.$data->id. ' > ' . $e->getMessage();
            return;
        }

        // get form fields
        $this->init_fields();

        // field validation
        foreach ( $this->fields as $key => $field ) {
            // get posted value
            $value = $field->get_posted_value();

            // save posted value
            $this->fields[ $key ]['value'] = $value;

            // validate values
            try {
                $field->check_validity();
            } catch ( \Exception $e ) {
                $this->add_error( $e->getMessage() );
                $this->_mdErrors[] = 'ID Iquesta #'.$data->id. ' > ' . $key. ' : ' . $e->getMessage();
            }
        }

        // custom validation rules
        try {
            do_action( 'mylisting/submission/validate-fields', $this->fields );
        } catch( \Exception $e ) {
            $this->add_error( $e->getMessage() );
            $this->_mdErrors[] = 'ID Iquesta #'.$data->id. ' > ' . $key. ' : ' . $e->getMessage();
            return;
        }
    }

    public function md_done() {
        $this->md_payments_disabled_submission_handler( $this->job_id );

        // done, force get listing
        $listing = \MyListing\Src\Listing::force_get( $this->job_id );
        do_action( 'mylisting/submission/done', $this->job_id );
        do_action( 'job_manager_job_submitted', $this->job_id );
    }

    public function md_payments_disabled_submission_handler( $listing_id ) {
        $listing = \MyListing\Src\Listing::force_get( $listing_id );

        /**
         * If Paid Listings are enabled, then at this point the listing status must be either
         * `pending` or `publish`. If it's instead set to `preview`, then this is a submission
         * with paid listings disabled.
         */
        if ( ! ( $listing && in_array( $listing->get_status(), [ 'preview', 'expired' ], true ) ) ) {
            return;
        }

        //mlog()->note( '[ADD LISTING FORM] - Paid Listings are disabled, running free submission handler.' );

        $post_status = 'publish';
        wp_update_post( [
            'ID' => $listing->get_id(),
            'post_status' => $post_status,
            'post_date' => current_time( 'mysql' ),
            'post_date_gmt' => current_time( 'mysql', 1 ),
            'post_author' => get_current_user_id(),
        ] );

        if ( $post_status === 'publish' ) {
            $expires = \MyListing\Src\Listing::calculate_expiry( $listing->get_id() );
            update_post_meta( $listing->get_id(), '_job_expires', $expires );
        } else {
            delete_post_meta( $listing->get_id(), '_job_expires' );
        }
    }


    public function mdSaveaaa($data)
    {
        $title = $data->title;
        $content = '';
        $this->job_id = false;

        //$ Regarder si c'est un ajout ou une mise à jour
        $optionIQuestaId = '__iquesta_id_'. $data->id;
        $addIQuestaOption = true;
        $tmp = get_option($optionIQuestaId, false);
        if($tmp) {
            $tmp2 = get_post($tmp);
            if(!$tmp2) {
                delete_option($optionIQuestaId);
            }
            else {
                $this->job_id = $tmp;
                $addIQuestaOption = false;
            }
        }

        //$ Initialisation des données à enregistrer
        $_POST = array(
            'listing_package' => $data->idForfait,
            'job_expires' => $data->expire_at,
            'job_author'  => $this->_iQuestaUserAccount->data->ID,
        );
        $errors = false;
        foreach($this->mdFields AS $k => $v) {
            $method = 'mdSetData' . preg_replace('|-|', '_', $k);
            //echo($method."\n");
            $value  = $this->$method($data);
            if ((!is_array($value)) && (preg_match('|^@@@ERROR###|', $value))) {
                $msg = preg_replace('|^@@@ERROR###|', '', $value);
                $msg = 'Correspondance not found ' . $msg . ' from Iquesta data id ' . $data->id;
                echo($msg.PHP_EOL);
                echo($msg.PHP_EOL);
                $_POST[$k] = '';
                $errors = true;
                $this->_mdErrors[] = $msg;
            } else {
                $_POST[$k] = $value;
            }
        }
        if($errors) {
            //self::print_r($this->_mdErrors);
        }

        $this->init_fields();
        foreach($this->fields AS $k => $v) {
            if(isset($_POST[$k])) {
                $this->fields[$k]->props['value'] = $_POST[$k];
            }
        }

        // Création de la fiche
        $this->save_listing( $title, $content, 'publish' );
        $postId = $this->get_job_id();
        $postId = $this->job_id;
        update_post_meta( $postId, '_job_expires', date( 'Y-m-d', strtotime( sanitize_text_field( $_POST['job_expires'] ) ) ) );
        wp_update_post( [
            'ID' => $postId,
            'post_author' => $_POST['job_author'] > 0 ? absint( $_POST['job_author'] ) : 0,
        ] );

        // Indication du type
        $_REQUEST = array(
            //'listing_type' => 'job',
            'job_id' => $postId
        );
        //$this->listing_type = 'job';
        //self::print_r($this->fields);
        //$this->fields = $this->mdFields;


       /* foreach($_POST AS $k => $v) {
            if(!in_array($k, array('job_category'))) {
                unset($_POST[$k]);
            }
        }*/
        //self::print_r($_POST, 1);
        $this->update_listing_data();

        if($addIQuestaOption) {
            add_option($optionIQuestaId, $postId);

            // Image aléatoire cover
            $path = get_template_directory().'-child'.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'partenaires';
            $scanned_directory = array_diff(scandir($path), array('..', '.'));
            $file = $scanned_directory[array_rand($scanned_directory)];
            $urlFile = get_stylesheet_directory_uri() . '/assets/img/partenaires/' . $file;
            update_post_meta( $postId, '_job_cover',  array($urlFile) );
        }

        exit('coucou2');
    }

    public function mdSaveOld($data)
    {
        $title = $data->title;
        $content = '';
        $this->job_id = false;
        //$ Regarder si c'est un ajout ou une mise à jour
        $optionIQuestaId = '__iquesta_id_'. $data->id;
        $addIQuestaOption = true;
        $tmp = get_option($optionIQuestaId, false);
        if($tmp) {
            $tmp2 = get_post($tmp);
            if(!$tmp2) {
                delete_option($optionIQuestaId);
            }
            else {
                $this->job_id = $tmp;
                $addIQuestaOption = false;
            }
        }

        // Création de la fiche
        $this->save_listing( $title, $content, 'publish' );
        $this->update_listing_data();

        exit('coucou');

        //
        //self::print_r($this->mdFields);
        //$ Initialisation des données à enregistrer
        $_POST = array(
            'listing_package' => $data->idForfait,
            'job_expires' => $data->expire_at,
            'job_author'  => $this->_iQuestaUserAccount->data->ID,
        );


        $errors = false;
        foreach($this->mdFields AS $k => $v) {
            $method = 'mdSetData' . preg_replace('|-|', '_', $k);
            //echo($method."\n");
            $value  = $this->$method($data);
            if ((!is_array($value)) && (preg_match('|^@@@ERROR###|', $value))) {
                $msg = preg_replace('|^@@@ERROR###|', '', $value);
                $msg = 'Correspondance not found ' . $msg . ' from Iquesta data id ' . $data->id;
                echo($msg.PHP_EOL);
                echo($msg.PHP_EOL);
                $_POST[$k] = '';
                $errors = true;
                $this->_mdErrors[] = $msg;
            } else {
                $_POST[$k] = $value;
            }
        }
        if($errors) {
            //self::print_r($this->_mdErrors);
        }

        //self::print_r($_POST, 1);

        // Création de la fiche
        $this->save_listing( $title, $content, 'publish' );

        $postId = $this->get_job_id();
        $postId = $this->job_id;
        update_post_meta( $postId, '_job_expires', date( 'Y-m-d', strtotime( sanitize_text_field( $_POST['job_expires'] ) ) ) );
        wp_update_post( [
            'ID' => $postId,
            'post_author' => $_POST['job_author'] > 0 ? absint( $_POST['job_author'] ) : 0,
        ] );

        $postMetas = array(
            'claimed' => 0,
            'featured' => 0,
            'case27_listing_type' => 'job',
            'iquesta_id' => $data->id,
            'package_id' => $data->idForfait,
            'user_package_id' => $data->idUserForfait,
            'job_category' => $this->mdSetDatajob_category(''),
        );

        $fieldsAccepted = array(
            'informations-entreprise',
            'nom-de-la-structure',
            'numero-siren',
            'secteur-dactivit',
            'adresse-de-la-structure',
            'description-de-lentreprise',
            'job_logo',
            'information-candidat',
            'job_tagline',
            'tlphone',
            'information-du-poste',
            'publication',
            'mail-de-contact-de-formulaire',
            'job_title',
            'job_description',
            'job_date',
            'dure',
            'niveau-requis-pour-postuler',
            'price_range',
            'job_location',
            'secteur-de-recherche',
            'tlchargement-de-cv',
            'link-partenaire',
            'url-billet-externet',
            'inscription',
            'related_listing',
            'listing-author',
            'listing-expiry-date',
        );
        foreach($_POST AS $k => $v) {
            if(in_array($k, $fieldsAccepted)) {
                $postMetas[$k] = $v;
            }
        }

        if($addIQuestaOption) {
            add_option( $optionIQuestaId, $postId);
            $postMetas['case27_review_count'] = 0;
            $postMetas['wcfm_listing_views'] = 0;

            // Image aléatoire cover
            $path = get_template_directory().'-child'.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'partenaires';
            $scanned_directory = array_diff(scandir($path), array('..', '.'));
            $file = $scanned_directory[array_rand($scanned_directory)];
            $urlFile = get_stylesheet_directory_uri() . '/assets/img/partenaires/' . $file;
            $postMetas['job_cover'] = array($urlFile);
        }



        foreach($postMetas AS $k => $v) {
            update_post_meta( $postId, '_'.$k, $v );
        }

        exit('ok');
        self::print_r($postMetas);


        self::print_r($_POST, 1);
        exit('ok');

        // Indication du type
        $_REQUEST = array(
            'listing_type' => 'job',
        );
        $this->listing_type = 'job';
        $this->fields = $this->mdFields;
        $this->update_listing_data();
        exit('mmmm2');
        if($addIQuestaOption)add_option( $optionIQuestaId, $postId);
        update_post_meta( $postId, '_iquesta_id', $data->id );
        update_post_meta( $postId, '_package_id', $data->idForfait );
        update_post_meta( $postId, '_user_package_id', $data->idUserForfait );

        self::print_r($_POST, 1);

        // Image aléatoire cover
        $path = get_template_directory().'-child'.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'partenaires';
        $scanned_directory = array_diff(scandir($path), array('..', '.'));
        $file = $scanned_directory[array_rand($scanned_directory)];
        $urlFile = get_stylesheet_directory_uri() . '/assets/img/partenaires/' . $file;
        update_post_meta( $postId, '_job_cover', array($urlFile) );
        //self::print_r($_POST, 1);
    }

    /**
     * See https://api2.iquesta.com/documentation
     */
    public function iQuestaAddUser($data)
    {
        try {
            return $this->_iQuestaResponse($this->_iQuestaPost('/user', ['json' => $data]));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    /**
     * See https://api2.iquesta.com/documentation
     */
    public function iQuestaOffer($offerId)
    {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/offer/' . $offerId));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }

    }

    /**
     * See https://api2.iquesta.com/documentation
     */
    public function iQuestaOffers($data = [])
    {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/offers', $data));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }

    }

    public function iQuestaCountries() {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/countries'));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    public function iQuestaRegions() {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/regions'));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    public function iQuestaContracts() {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/contracts'));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    public function iQuestaSubjects() {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/subjects'));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    public function iQuestaLevels() {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/levels'));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    /**
     * Example :
     * $data = [
     *     'email'      => 'xavier@iquesta.com',
     *     'first_name' => 'xavier',
     *     'last_name'  => 'barbez',
     *     'offer_id'   => '298375',
     * ];
     *
     * $files = [
     *     'file_1' => fopen('/path/test.pdf', 'r'),
     *     'file_2' => fopen('/path/test-2.pdf', 'r')
     * ]
     */
    public function iQuestaSendApplication($data, $files)
    {
        try {
            $multipart = [];

            foreach ($data as $key => $value) {
                $multipart[] = [
                    'name'     => $key,
                    'contents' => $value
                ];
            }

            foreach ($files as $key => $value) {
                $multipart[] = [
                    'name'     => $key,
                    'contents' => $value
                ];
            }

            //print_r($multipart);
//exit('eeee');
            return $this->_iQuestaResponse($this->_iQuestaPost('/application', ['multipart' => $multipart]));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }


    /**
     * See https://api2.iquesta.com/documentation
     */
    public function iQuestaUser($email)
    {
        try {
            return $this->_iQuestaResponse($this->_iQuestaGet('/user', ['email' => $email]));
        } catch (\Exception $e) {
            return $this->_iQuestaError($e);
        }
    }

    private function _iQuestaError($e)
    {
        if ($e->getResponse()) {
            if ($this->_iQuestaDebug) {
                echo "Error<br />";
                echo "<pre>";
                echo json_encode(json_decode($e->getResponse()->getBody()->getContents()), JSON_PRETTY_PRINT);
                echo "</pre>";
            }

            return json_decode($e->getResponse()->getBody()->getContents());
        }
    }

    private function _iQuestaGet($url, $data = [], $files = [])
    {
        $res = $this->_iQuestaClient->get($this->_iQuestaApiUrl. $url, [
            'headers' => [
                'content-type'  => 'application/json',
                'Authorization' => 'Bearer ' . $this->_iQuestaApiKey,
            ],
            'json' => $data,
            //'debug' => true,
        ]);

        /*echo('#'.$this->_iQuestaApiUrl . $url.'#<br />');
        echo $res->getStatusCode();
        echo $res->getBody();
        self::print_r($res);

        echo('<br />');
        echo('<br />');
        echo('<br />');

        exit('ok');*/
        return $this->_iQuestaClient->get($this->_iQuestaApiUrl . $url, [
            'headers' => [
                'content-type'  => 'application/json',
                'Authorization' => 'Bearer ' . $this->_iQuestaApiKey,
            ],
            'json' => $data,
        ]);
    }

    private function _iQuestaPost($url, $data = [], $files = [])
    {
        return $this->_iQuestaClient->post($this->_iQuestaApiUrl . $url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->_iQuestaApiKey,
            ],
        ] + $data);
    }

    private function _iQuestaResponse($response)
    {
        $statusCode = $response->getStatusCode();
        $return     = \json_decode($response->getBody()->getContents());

        if ($this->_iQuestaDebug) {
            echo "Response<br />";
            echo "<pre>";
            echo json_encode($return , JSON_PRETTY_PRINT);
            echo "</pre>";
        }

        return $return;
    }
}
