<?php

// Enqueue child theme style.css
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_style( 'child-style', get_stylesheet_uri() );

    if ( is_rtl() ) {
        wp_enqueue_style( 'mylisting-rtl', get_template_directory_uri() . '/rtl.css', [], wp_get_theme()->get('Version') );
    }
}, 500 );

// Happy Coding :)


add_filter( 'case27\listing\location\short_address', '__return_false' );



// gestion des produits perimés

add_filter( 'mylisting/explore/args', function ( $args ) {
    $listing_types = ['activity'];

    if ( empty( $args['meta_query'] ) || empty( $args['meta_query']['listing_type_query'] ) ) {
        return $args;
    }

    $meta_value = $args['meta_query']['listing_type_query']['value'];

    if ( ! isset( $meta_value ) ) {
        return $args;
    }

    if ( is_array( $meta_value ) && ! empty( $meta_value ) ) {
        $meta_value = $meta_value[0];
    }

    // Only apply to the listing types defined in $listing_types.
    if ( ! in_array( $meta_value, $listing_types ) ) {
        return $args;
    }

    $args['meta_query'][] = [
        'relation' => 'OR',
        [
            'key' => '_date-de-dbut',
            'value' => date('Y-m-d'),
            'compare' => '>=',
            'type' => 'DATE',
        ],
    ];

    return $args;
}, 99 );



/** MD Modification 2020-03-11 */

/** Champ dans le formulaire de paiement pour indiquer que l'internaute est membre ou pas */
add_action( 'woocommerce_checkout_billing', function () {
    $isMember = (checkIfUserIsMember()) ? 1 : 0;
    echo('<input type="hidden" name="user_is_an_valid_member" id="user_is_an_valid_member" value="'.$isMember.'"  />');
}, 10 );

/** Indiquer le nouveau champ à WooCommerce */
add_filter('woocommerce_checkout_posted_data', function ($data)
{
    $custom_keys = [
        'user_is_an_valid_member',
    ];
    foreach ($custom_keys as $key) {
        if (isset($_POST[$key])) {
            $data[$key] = sanitize_text_field($_POST[$key]);
        }
    }

    return $data;
}, 10, 2);

/** Enregistrement de l'information membre ou pas */
add_action('woocommerce_checkout_update_order_meta', function ($order_id, $data)
{
    $custom_keys = [
        'user_is_an_valid_member',
    ];
    $order = wc_get_order($order_id);
    foreach ($custom_keys as $key) {
        if (isset($data[$key])) {
            $order->add_meta_data('_' . $key, $data[$key]);
        }
    }
    $order->save();
}, 10, 2);

/** Afficher dans l'admin que l'internaute a bénéficié du tarif membre */
add_action( 'woocommerce_admin_order_data_after_order_details', function ( $order ){
    $isMember = 0;
    if($order->meta_exists('_user_is_an_valid_member')) {
        $isMember = $order->get_meta('_user_is_an_valid_member');
    }
    if($isMember == 1) {
        echo('<p style="display:block; margin-top: 200px; padding: 10px !important; border: 1px solid #46b450; border-left-width: 4px; border-left-color: #46b450;"><strong style="font-size: 16px">Le client été membre au moment de l\'achat.</strong></p>');
    }
});

/** DEBUG IsMember */
function MDGetIsPaidStatuses() {
    //return wc_get_order_statuses();
    return array('wc-processing', 'wc-completed');

}
if(isset($_GET['debugIsMember'])){
    $debugUser = (isset($_GET['user'])) ? $_GET['user'] : false;
    checkIfUserIsMember(true, $debugUser);
}

/** Vérifier si l'internaute est membre */
function checkIfUserIsMember($modeDebug = false, $user=false) {
    global $wpdb, $table_prefix;
  //  SELECT wp.ID FROM `wor4208_posts` wp LEFT JOIN `wor4208_postmeta` wpm ON wp.ID=wpm.post_id WHERE post_type='product' AND wpm.meta_key='_its_a_member_card';

    // L'internaute n'est pas connu
    if ( ! is_user_logged_in() && ($user == false) ) {
        if($modeDebug)exit('NOT LOGGED IN.');
        else return false;
    }

    // L'internaute est connu
    if($user == false)$current_user = wp_get_current_user();
    else {
        $current_user = get_user_by('login', $user);
        if(!$current_user) {
            if($modeDebug) {
                exit('Utilisateur "'.$_GET['user'].'" non trouvé');
            }
        }
    }
    if($modeDebug) {
        if(!$current_user) exit('CURRENT USER NOT FOUND.');
        echo('<h2>Informations utilisateurs:</h2>');
        echo('Utilisateur "'.$current_user->data->user_login.'" (id:'.$current_user->ID.').<br />');
    } else {
        if(!$current_user) return false;
    }

    // Rechercher les produits de type carte de membre
    $sql = "SELECT * FROM `".$table_prefix."posts` wp LEFT JOIN `".$table_prefix."postmeta` wpm ON wp.ID=wpm.post_id WHERE post_type='product' AND wpm.meta_key='_its_a_member_card';";
    $results = $wpdb->get_results($sql);
    if($modeDebug) {
        echo('<h2>Produits de type carte de membre:</h2>');
    }
    $idsMemberCard = [];
    foreach($results AS $result) {
        $idsMemberCard[] = $result->ID;
        if($modeDebug) echo('- ' . $result->post_title . ' (id:' . $result->ID . ")<br />");
    }

    // Rechercher les commandes de l'internaute
    $sql = "SELECT wp.* FROM `".$table_prefix."posts` wp LEFT JOIN `".$table_prefix."postmeta` wpm ON wp.ID=wpm.post_id WHERE (wp.post_date >= CURDATE() - INTERVAL 1 YEAR) AND wp.post_status IN ('".join("','", MDGetIsPaidStatuses())."') AND wpm.meta_key='_customer_user' AND wpm.meta_value=".$current_user->ID;
    $customer_orders = $wpdb->get_results($sql);
    //echo $sql;

    // Regarder le contenu des commandes
    $ordersId = array();
    foreach ($customer_orders as $customer_order) {
        $ordersId[] = $customer_order->ID;
    }

    if(count($ordersId) == 0) {
        if($modeDebug)exit('<br /><strong style="color: red">USER IS NOT MEMBER</strong>');
        return false;
    }

    $sql = "SELECT * FROM `".$table_prefix."woocommerce_order_items` wcoi LEFT JOIN `".$table_prefix."woocommerce_order_itemmeta` wcoim ON wcoi.order_item_id=wcoim.order_item_id WHERE order_id IN (".join(",", $ordersId).") AND wcoim.meta_key='_product_id' AND wcoim.meta_value IN (".join(',', $idsMemberCard).");";//" AND wpm.meta_key='_customer_user' AND wpm.meta_value=".$current_user->ID;
    $customer_orders = $wpdb->get_results($sql);
    if(count($customer_orders) > 0) {
        if($modeDebug)exit('<br /><strong style="color: green">USER IS MEMBER</strong>');
        return true;
    }

    if($modeDebug)exit('<br /><strong style="color: red">USER IS NOT MEMBER</strong>');
    return false;
}

/** Affichage des champs "Tarif membre" dans l'admin */
add_action('woocommerce_product_options_general_product_data', function ()
{
    global $post;
    echo '<div class="options_group pricing show_if_simple show_if_external show_if_job_package show_if_promotion_package">';
    woocommerce_wp_text_input(
        array(
            'id' => '_price_member',
            'placeholder' => '',
            'label' => __('Tarif membre (€)', 'woocommerce'),
            'type'  => 'text',
            'class' => 'short wc_input_price',
            'value' => get_post_meta( $post->ID, '_price_member', true ),
        )
    );
    echo '</div>';

    /*echo '<div class="options_group show_if_simple">';
    woocommerce_wp_checkbox( array(
        'id'      => '_its_a_member_card',
        'value'   => get_post_meta( $post->ID, '_its_a_member_card', true ),
        'label'   => 'Carte de membre',
        'description' => 'Ce produit est une carte de membre valable 1 an à partir de la date d\'achat.'
    ) );
    echo '</div>';*/
}, 1);

/** Affichage des champs "Carte de membre" dans l'admin */
/*add_action('woocommerce_variation_product_options_advanced', function ()
{
    global $post;

    echo '<div class="options_group show_if_simple">';
    woocommerce_wp_checkbox( array(
        'id'      => '_its_a_member_card',
        'value'   => get_post_meta( $post->ID, '_its_a_member_card', true ),
        'label'   => 'Carte de membre',
        'description' => 'Ce produit est une carte de membre valable 1 an à partir de la date d\'achat.'
    ) );
    echo '</div>';
}, 1);*/
add_action( 'add_meta_boxes_product', function() {
    add_meta_box('postfunctionprddiv78360', 'Carte de membre', 'show_metaboxes_prod_cartemembre_html', null, 'side', 'high');
} );
function show_metaboxes_prod_cartemembre_html()
{
    global $post;
    $custom = get_post_custom($post->ID);
    $stat = isset($custom["_its_a_member_card"][0])?$custom["_its_a_member_card"][0]:'';
    ?>
    Ce produit est une carte de membre valable 1 an à partir de la date d'achat.<br />
    <select name="its_a_member_card" id="its_a_member_card" style="width: 100%">
        <option value="">Non</option>
        <option value="1"<?php if($stat == 1){?> selected="selected"<?php } ?>>Oui</option>
    </select>
    <?php
}
function show_metaboxes_prod_cartemembre_save_post()
{
    if(empty($_POST)) return;
    if(!isset($_POST["its_a_member_card"]))$_POST["its_a_member_card"] = '';
    global $post;
    if(isset($post) && isset($post->ID)) {
        if($_POST["its_a_member_card"] == 1) {
            update_post_meta($post->ID, "_its_a_member_card", $_POST["its_a_member_card"]);
        } else {
            delete_post_meta($post->ID, '_its_a_member_card');
        }
    }
}
add_action( 'save_post_product', 'show_metaboxes_prod_cartemembre_save_post' );

/** Affichage des champs "Tarif membre" et "Description membre" dans l'admin partie "variation" */
add_action('woocommerce_variation_options_pricing', function ($loop, $variation_data, $variation)
{
    woocommerce_wp_text_input( array(
            'id'    => 'price_member[' . $loop.']',
            'class' => 'short wc_input_price',
            'label' => __('Tarif membre (€)', 'woocommerce'),
            'value' => get_post_meta( $variation->ID, 'price_member', true ),
            'wrapper_class' => 'form-row form-row-first',
        )
    );
    woocommerce_wp_textarea_input( array(
            'id'    => 'desc_member[' . $loop.']',
            'class' => 'short wc_input_price',
            'label' => __('Description membre', 'woocommerce'),
            'value' => get_post_meta( $variation->ID, 'desc_member', true ),
            'wrapper_class' => 'form-row form-row-full',
        )
    );
}, 10, 3);

/** Enregistrement des champs "Tarif membre" et "Carte de membre" dans l'admin */
add_action('woocommerce_process_product_meta', function ($post_id)
{
    $field = $_POST['_price_member'];
    if (isset($field))
        update_post_meta($post_id, '_price_member', esc_attr($field));

    /*$field = $_POST['_its_a_member_card'];
    if (isset($field))
        update_post_meta($post_id, '_its_a_member_card', esc_attr($field));
    else
        delete_post_meta($post_id, '_its_a_member_card');*/
});

/** Enregistrement des champs "Tarif membre" et "Description membre" dans l'admin partie "variation" */
add_action( 'woocommerce_save_product_variation', function ( $variation_id, $i ) {
    $custom_field = $_POST['price_member'][$i];
    if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'price_member', esc_attr( $custom_field ) );
    $custom_field = $_POST['desc_member'][$i];
    if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'desc_member', esc_attr( $custom_field ) );
}, 10, 2 );

/** Affichage dans la fiche du produit */
add_filter( 'woocommerce_available_variation', function ( $variations ) {
    // Description membre
    $memberDesc = get_post_meta( $variations['variation_id'], 'desc_member', true );
    $isMember = checkIfUserIsMember();
    if(($memberDesc)  && ($isMember)) {
        $variations['variation_description'] = '<p>' . nl2br($memberDesc) . '</p>' ;
    }
    $memberPrice = get_post_meta( $variations['variation_id'], 'price_member', true );
    if(($memberPrice)  && (checkIfUserIsMember())) {
        $variations['price_html'] = preg_replace('|</span>\s*$|', '<span>&nbsp;Prix membre</span></span>', $variations['price_html']);
    }
    return $variations;
} );

/** Prix dans la fiche partie détail variation */
add_filter('woocommerce_product_variation_get_regular_price', 'member_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'member_price' , 99, 2 );
function member_price( $price, $product ) {
    // Suppression du prix en cache
    wc_delete_product_transients($product->get_id());

    // Prix membre
    $memberPrice = get_post_meta( $product->get_id(), 'price_member', true );
    if(($memberPrice)  && (checkIfUserIsMember())) {
        $price = $memberPrice;
    }
    return $price;
}

/** Prix dans le titre d'une fiche de type variation et sur une card */
add_filter('woocommerce_variation_prices_price', 'member_variation_price', 99, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'member_variation_price', 99, 3 );
function member_variation_price( $price, $variation, $product ) {
    // Suppression du prix en cache
    wc_delete_product_transients($variation->get_id());

    // Prix membre
    $memberPrice = get_post_meta( $variation->get_id(), 'price_member', true );
    if(($memberPrice)  && (checkIfUserIsMember())) {
        $price = $memberPrice;
    }
    return $price;
}

/** Prix de vente */
add_filter( 'woocommerce_product_get_price', 'price_for_member', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'price_for_member', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'price_for_member', 10, 2 );
function price_for_member( $price, $product ) {
    $memberPrice = get_post_meta( $product->get_id(), '_price_member', true );
    return (($memberPrice) && (checkIfUserIsMember())) ? $memberPrice : $price;
}

/** Affichage du prix sur les fiches simple */
add_filter( 'woocommerce_get_price_html', function ( $price, $product ){
    $memberPrice = get_post_meta( $product->id, '_price_member', true );
    $isMember = checkIfUserIsMember();
    $return = $price;
    $useMemberPrice = false;
    if(($memberPrice)  && ($isMember)) {
        $memberPrice = ( is_numeric( $memberPrice ) ? wc_price( $memberPrice ) : $memberPrice );
        $return = $price;
        $useMemberPrice = true;
        $return = preg_replace('#<ins>(.*)</ins>#', '<ins><span class="woocommerce-Price-amount amount">' . $memberPrice . '</span></ins>', $return);
    } else {
        if($product->is_type('variable')) {
            $handle     = new WC_Product_Variable($product->id);
            $variations = $handle->get_children();
            foreach ($variations as $variationId) {
                $memberPriceV = get_post_meta( $variationId, 'price_member', true );
                if(($memberPriceV)  && (checkIfUserIsMember())) {
                    $useMemberPrice = true;
                }
            }
        }
    }

    if($useMemberPrice) {
        $return = $return . '&nbsp;Prix membre';
    }

    return $return;
}, 100, 2 );


/** /MD Modification 2020-03-11 */

/** MD Forfaits a ne pas afficher 2020-06-17 */
function showForfait($forfait) {
    //return true;

    if(in_array($forfait, array('forfait-partenaire', 'forfait-partenaire-iquesta')))return false;
    else return true;
}
/** MD Forfaits a ne pas afficher 2020-06-17 */

/** MD Show/hide link in form 2020-08-28 */
function showMsgLink($link) {
    if(is_user_logged_in()) {
        return 'Texte à définir.<br /><br /><a href="'.$link.'" target="_blank" class="moreInfo">Plus d\'informations</a>';
    } else {
        return 'Pour contacter cette personne, vous devez être loggué.<br /><br /><a href="#" data-toggle="modal" data-target="#sign-in-modal" class="moreInfo">Se connecter</a>';
    }
}
/** /MD Show/hide link in form 2020-08-28 */

/** MD Show/hide contact form 2020-06-16 */
function showMsgForm($type) {
    switch($type) {
        default:
            return 'Pour contacter cette personne, vous devez devenir membre.<br /><br /><a href="/product/devenir-membre-adhesion/" class="moreInfo">Plus d\'informations</a>';
            break;
    }
}
function showForm($type, $postId) {
    //return true;
    // Visible que pour les non-membres
    $defaultHidden = array(
        'job' => 1,
        'rent' => 1
    );

    $custom = get_post_custom($postId);
    $showForm = isset($custom["forceContactForm"][0])?$custom["forceContactForm"][0]:'';
    $isMember = checkIfUserIsMember();
    switch($showForm) {
        case 'members':
            $show = $isMember;
            break;
        case 'all':
            $show = true;
            break;
        default:
            $show = ((isset($defaultHidden[$type])) && (!$isMember)) ? false : true;
            break;
    }
    return $show;
}
add_action( 'add_meta_boxes_job_listing', function() {
    add_meta_box('postfunctiondiv78788', 'Afficher/cacher le formulaire', 'show_metaboxes_contact_form_html', null, 'side', 'high');
} );
function show_metaboxes_contact_form_html()
{
    global $post;
    $custom = get_post_custom($post->ID);
    $stat = isset($custom["forceContactForm"][0])?$custom["forceContactForm"][0]:'';
    ?>
    <select name="forceContactForm" id="forceContactForm">
        <option value=""></option>
        <option value="members"<?php if($stat == 'members') {?> selected="selected"<?php } ?>>Afficher que pour les membres</option>
        <option value="all"<?php if($stat == 'all') {?> selected="selected"<?php } ?>>Afficher pour tous</option>
    </select>
    <?php
}
function show_metaboxes_contact_form_save_post()
{
    if(empty($_POST)) return;
    if(!isset($_POST["forceContactForm"]))$_POST["forceContactForm"] = '';
    global $post;
    if(isset($post) && isset($post->ID)) {
        update_post_meta($post->ID, "forceContactForm", $_POST["forceContactForm"]);
    }
}
add_action( 'save_post_job_listing', 'show_metaboxes_contact_form_save_post' );
/** /MD Show/hide contact form 2020-06-16 */

/** MD Send to iquesta 2020-06-17 */
function iQuestaSendFormError() {
    $name = (isset($_POST['_wpcf7_unit_tag'])) ? $_POST['_wpcf7_unit_tag'] : '#form';
    exit('{"into":"#'.$name.'","status":"validation_failed","message":"Une erreur interne est survenue. Veuillez essayer \u00e0 nouveau.\n","posted_data_hash":"","invalid_fields":[]}');
}
add_action('wpcf7_mail_sent', function () {
    $submission = WPCF7_Submission::get_instance();

    if ($submission) {

        // On récupère les données du formulaire
        $posted_data = $submission->get_posted_data();


        if(isset($_POST['_case27_recipients']) && ($_POST['_case27_recipients'] == 'email-du-contact-iquesta')) {
            if(!isset($_POST['_case27_post_id']))iQuestaSendFormError();

            $postId = $_POST['_case27_post_id'];
            $idIQuesta = get_post_meta($postId, '_iquesta_id', true);
            if(!$idIQuesta)iQuestaSendFormError();
            $offerId = $idIQuesta;
            if(MODE_DEV_IQUESTA)$offerId = 292498;

            $data = array(
                'email'      => $posted_data['your-email'],
                'first_name' => $posted_data['your-firstname'],
                'last_name'  => $posted_data['your-name'],
                'offer_id'   => $offerId,
            );

            $uploadFiles = $submission->uploaded_files();
            $files = array();
            if(isset($uploadFiles['monFichierCV'])) {
                $files['file_1'] = fopen($uploadFiles['monFichierCV'], 'r');
            }

            require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php');
            $iQuesta =  App\IquestaToMyListingJob::getInstance();
            $iQuesta->iQuestaSendApplication($data, $files);

            /*print_r($_FILES);
            print_r($submission);
            exit('coucou');*/
        }


    }
});
// define the wpcf7_submit callback
/*function action_wpcf7_submit( $instance, $result ) {
    // make action magic happen here...
    //$posted_data = $instance->get_posted_data();

    $submission = WPCF7_Submission::get_instance();

    if ($submission) {

        // On récupère les données du formulaire
        $posted_data = $submission->get_posted_data();
        print_r($posted_data);

        $file = '/var/www/vhosts/md-dev.fr/tobeerasmus-v2.md-dev.fr/tobeerasmus/web/wp-content/uploads/job-manager-uploads/tlchargement-de-cv/2018/12/sample.pdf';

        $offerId = $posted_data['_wpcf7_container_post'];
        $offerId = 292498;

        $data = array(
            'email'      => $posted_data['your-email'],
            'first_name' => $posted_data['your-firstname'],
            'last_name'  => $posted_data['your-name'],
            'offer_id'   => $offerId,
        );

        $files = array();
        $files['file_1'] = fopen($file, 'r');


        require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php');
        $iQuesta =  App\IquestaToMyListingJob::getInstance();
        $iQuesta->iQuestaSendApplication($data, $files);

	}

    //print_r($instance);
    exit('#'.$file.'#');
};*/

// add the action
//add_action( 'wpcf7_submit', 'action_wpcf7_submit', 10, 2 );

/** /MD Send to iquesta 2020-06-17 */


/** MD Cron hook 2020-07-21 */
add_action( 'MDCronHook', 'MDCronHook' );
function MDCronHook() {
    require_once(dirname(__FILE__). DIRECTORY_SEPARATOR . 'md-cron.php');
    //wp_mail( 'hello@example.com', 'WP Crontrol', 'WP Crontrol rocks!' );
}

/** /MD Cron hook 2020-07-21 */
