<?php
/**
 * Plugin Name: Direct Print Order
 * Plugin URI: http://www.pixelorigin/wpdirectprint
 * Description: Impression automatique des commandes.
 * Version: 1.0
 * Author: Pixelorigin
 * Author URI: http://www.pixelorigin.com
 */
 
register_activation_hook( __FILE__, 'dp_pluggin_activate' );
add_action('admin_menu', 'wnb_settings_page');


/**
 * Creates settings for the plugin
 */
add_action('admin_init', 'wnb_initialize_settings');

function dp_pluggin_activate(){
    //Activation method.
    activate_directprint();
}

add_action('admin_init', 'admin_js' );  
function admin_js()
{ 
   wp_enqueue_script( 'javascript_file',
   plugin_dir_url(__FILE__) . 'script.js',
   [],
   '1.0.0'
);


 }; 

/**
 * Displays the notification bar on the frontend of the site
 */
add_action('wp_footer', 'dp_display_hours');
function dp_display_hours() {
	//wp_localize_script( 'capitaine', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
   if (null !== get_option('wnb_settings')) {
      $options = get_option('wnb_settings');
      ?>
      <div class="wnb-notification-bar <?php echo $options['display_location']; ?>
            <?php echo $options['display_sticky']; ?>">
           <div class="wnb-notification-text">
              <?php 
			  
			  
			   $jour=date('w');
			   
			   //echo "jour : ".$jour;
	$h1 = $options['j'.$jour.'h1'];
	$h2 = $options['j'.$jour.'h2'];
	$h3 = $options['j'.$jour.'h3'];
	$h4 = $options['j'.$jour.'h4'];
	
	//echo $h1.$h2.$h3.$h4;
		//echo $options['j4h1'];;	  
			  
			  
             
             date_default_timezone_set('Europe/Paris');
              $heure = date("H:i");
			  	
	$hf = $options['j0h2'];
	$ho = $options['j0h1'];
	

	
	
	
	
	
	
if (($heure > $h2  || $heure < $h1) && ($heure > $h4  || $heure < $h3)  )
{
	$ouverture = "ferme";
	$message ="Les commandes sont fermé<br> Uniquement pendant les heures d'ouverture<br> ";
}
else 
$ouverture = "ouvert";
			  
			  
			  
              //echo $ouverture;
              //echo $options['largeur']; 
			  ?>

<div class="ouverture <?php echo $ouverture; ?>">
<?php echo $message; ?>



              <?php echo $h1; ?> - 
              <?php echo $h2; ?> puis 
			   <?php echo $h3; ?> - 
              <?php echo $h4; ?>
</div>
		  
		  
           </div>
       </div>
	   <script>
	   //alert("h"+ajaxurl);
	  //console.log(NeveProperties);
	jQuery(document).ready(function( $ ) {
	
	
	$('.checkout-button').on('click', function(e) {
		e.preventDefault();
		//alert("verif");
		
		hr=$("#heureretrait").val();
      //alert(hr);
 urlcommande= $(this).attr("href");
 //ajaxurl="http:\/\/localhost\/snacksalam\/wp-admin\/admin-ajax.php";
 $.ajax({
          url: ajaxurl,
          type: "POST",
          data: {
            'action': 'heureRetrait',
            'hr': hr
          }
        }).done(function(response) {
        // alert(response);
if (response==1){window.location= urlcommande;}
if (response==0){alert("Choisir une heure pendant les heures d'ouverture");}

		 // Afficher le HTML
         
        });
        
 
	//window.location= $(this).attr("href");	
		
		
		//window.location.href = location.protocol + '//' + location.host + '/' + $( 'a', this).prop('href');
		
	});
	

	
});
  
	
	
	
	   </script>
	   
	   
      <?php
   }
}


/**
 * Loads plugin scripts and styles
 */
add_action('wp_enqueue_scripts', 'wnb_scripts');
function wnb_scripts() {
   wp_enqueue_style(
      'wdp-frontstyle-css',
      plugin_dir_url(__FILE__) . 'wdp-frontstyle.css',
      [],
      '1.0.0'
   );
}




function wnb_initialize_settings() {
	
	
	  add_settings_section(
      'general_section',
      __('Réglages', 'arch-wdpo'),
      'general_settings_callback',
      'wnb_settings'
   );
add_settings_field(
      'notification_text',
      __('Largeur imprimante', 'arch-wdpo'),
      'text_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'notification_text',
         'option_group' => 'wnb_settings',
         'option_id' => 'largeur',
      ]
   );
 

    add_settings_field(
      'Fj1h1',
      __('Lundi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Lundi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j1h1',
      ]
   );
   add_settings_field(
      'Fj1h2',
      __('Lundi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Lundi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j1h2',
      ]
   );
      add_settings_field(
      'Fj1h3',
      __('Lundi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Lundi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j1h3',
      ]
   );
   add_settings_field(
      'Fj1h4',
      __('Lundi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Lundi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j1h4',
      ]
   );
   
   add_settings_field(
      'Fj2h1',
      __('Mardi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mardi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j2h1',
      ]
   );
   add_settings_field(
      'Fj2h2',
      __('Mardi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mardi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j2h2',
      ]
   );
      add_settings_field(
      'Fj2h3',
      __('Mardi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mardi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j2h3',
      ]
   );
   add_settings_field(
      'Fj2h4',
      __('Mardi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mardi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j2h4',
      ]
   );
   
   add_settings_field(
      'Fj3h1',
      __('Mercredi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mercredi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j3h1',
      ]
   );
   add_settings_field(
      'Fj3h2',
      __('Mercredi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mercredi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j3h2',
      ]
   );
      add_settings_field(
      'Fj3h3',
      __('Mercredi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mercredi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j3h3',
      ]
   );
   add_settings_field(
      'Fj3h4',
      __('Mercredi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Mercredi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j3h4',
      ]
   );
     add_settings_field(
      'Fj4h1',
      __('Jeudi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Jeudi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j4h1',
      ]
   );
   add_settings_field(
      'Fj4h2',
      __('Jeudi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Jeudi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j4h2',
      ]
   );
      add_settings_field(
      'Fj4h3',
      __('Jeudi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Jeudi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j4h3',
      ]
   );
   add_settings_field(
      'Fj4h4',
      __('Jeudi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Jeudi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j4h4',
      ]
   );
    add_settings_field(
      'Fj5h1',
      __('Vendredi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Vendredi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j5h1',
      ]
   );
   add_settings_field(
      'Fj5h2',
      __('Vendredi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Vendredi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j5h2',
      ]
   );
      add_settings_field(
      'Fj5h3',
      __('Vendredi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Vendredi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j5h3',
      ]
   );
   add_settings_field(
      'Fj5h4',
      __('Vendredi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Vendredi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j5h4',
      ]
   );
     add_settings_field(
      'Fj6h1',
      __('Samedi ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Samedi ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j6h1',
      ]
   );
   add_settings_field(
      'Fj6h2',
      __('Samedi fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Samedi fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j6h2',
      ]
   );
      add_settings_field(
      'Fj6h3',
      __('Samedi ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Samedi ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j6h3',
      ]
   );
   add_settings_field(
      'Fj6h4',
      __('Samedi fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Samedi fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j6h4',
      ]
   );
   
      add_settings_field(
      'Fj0h1',
      __('Dimanche ouverture matin', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Dimanche ouverture matin',
         'option_group' => 'wnb_settings',
         'option_id' => 'j0h1',
      ]
   );
   add_settings_field(
      'Fj0h2',
      __('Dimanche fermeture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Dimanche fermeture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j0h2',
      ]
   );
   
   add_settings_field(
      'Fj0h3',
      __('Dimanche ouverture mi-journée', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Dimanche ouverture mi-journée',
         'option_group' => 'wnb_settings',
         'option_id' => 'j0h3',
      ]
   );
  
   add_settings_field(
      'Fj0h4',
      __('Dimanche fermeture soir', 'arch-wdpo'),
      'time_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Dimanche fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j0h4',
      ]
   );
      add_settings_field(
      'Fdup',
      __('Dupliquer le lundi les autres jours', 'arch-wdpo'),
      'button_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Dimanche fermeture soir',
         'option_group' => 'wnb_settings',
         'option_id' => 'j0h4',
      ]
   );
   add_settings_field(
      'Secure',
      __('Clé de sécurité à renseigner dans le logiciel :', 'arch-wdpo'),
      'text_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Secure',
         'option_group' => 'wnb_settings',
         'option_id' => 'secure',
      ]
   );
                
      add_settings_field(
      'ouverturelundi',
      __('Ouverture le lundi :', 'arch-wdpo'),
      'box_input_callback',
      'wnb_settings',
      'general_section',
      [
         'label_for' => 'Ouverture',
         'option_group' => 'wnb_settings',
         'option_id' => 'ouverturelundi',
      ]
   );             
   
   
   register_setting(
      'wnb_settings',
      'wnb_settings'
   );
}

/**
 * Displays the header of the general settings
 */
function general_settings_callback() {
   esc_html_e('Paramètres', 'arch-wdpo');
}




function wnb_settings_page() {
   add_submenu_page(
      'options-general.php',
      __('Direct Print Orders', 'arch-wdpo'),
      __('Direct print', 'arch-wdpo'),
      'manage_options',
      'wdp_orders',
      'wnb_render_settings_page'
   );
}


function text_input_callback($text_input) {
   // Get arguments from setting
   $option_group = $text_input['option_group'];
   $option_id = $text_input['option_id'];
   $option_name = "{$option_group}[{$option_id}]";
   $options = get_option($option_group);
  // printf $options;
   $option_value = $options[$option_id];
   echo "<input type='text'  id='{$option_id}'
                name='{$option_name}' value='{$option_value}' />";
}

function box_input_callback($box_input) {
   // Get arguments from setting
   $option_group = $box_input['option_group'];
   $option_id = $box_input['option_id'];
   $option_name = "{$option_group}[{$option_id}]";
   $options = get_option($option_group);
  // printf $options;
   $option_value = $options[$option_id];
   if ($option_value=="")
   {
	   $option_value=0;
	   $box="";
	}
   if ($option_value==1)
   {
	   $box="checked";
	}
   echo "<input type='checkbox'  id='{$option_id}'
                name='{$option_name}' value='{$option_value}' {$box}/>";
}

function time_input_callback($text_input) {
   // Get arguments from setting
   $option_group = $text_input['option_group'];
   $option_id = $text_input['option_id'];
   $option_name = "{$option_group}[{$option_id}]";
   $options = get_option($option_group);
  // printf $options;
   $option_value = $options[$option_id];
   echo "<input type='time' size='50' id='{$option_id}'
                name='{$option_name}' value='{$option_value}' />";
   
}

/**
 * Radio Input Callbacks
 */
function button_callback($radio_input) {
  
   echo "<input onclick='myFunction()' id='btrecopier' type='button' value='Reproduire les horaires'>";
}





/**
 * page de configuration parametre
 */
function wnb_render_settings_page() {
	

//	$wpdb->query($sql_dporders);
	
	
//$options = get_option('wnb_settings');
	

	
	
	
   //echo "hello3";
   $urlprint = get_home_url()."/wp-content/plugins/directprint/print.php";
   ?>
    <!-- Create a header in the default WordPress 'wrap' container -->
    <div class="wrap">

        <h2><?php esc_html_e('Direct print orders configuration',
                             'arch-wdpo'); ?></h2>

        <form method="post" action="options.php">

           <?php
           // Get plugin  settings to display in the form
           settings_fields('wnb_settings');
           do_settings_sections('wnb_settings');
           // Form submit button
           echo "<b>Adresse pour le logiciel Direct Print : </b>".$urlprint;
           submit_button();
           ?>

        </form>

    </div><!-- /.wrap -->
   <?php

$options = get_option('wnb_settings');
$largeur = $options['largeur'];
//define('WPLANG', 'fr_FR');
echo $largeur;
  // $order = wc_get_order( 785 );
  // echo $order->get_formatted_order_total();
    $orders = wc_get_orders( array(
                'numberposts' => - 1,
                'meta_key'    => '_customer_user',
                'meta_value'  => get_current_user_id(),
                'post_status' => $order_states
            ) );
			
			
	
    foreach ( $orders as $order ) {
      //print_r( $order.shipping.first_name);
	  $bool = $order->is_paid();
	  
//echo $bool."<br>";
      $ticket="";
	  
	  $orderid=$order->get_id();
     
      $modepayement=$order->get_payment_method_title();
            $ville=$order->get_billing_city();
            $nomprenom=$order->get_billing_last_name()." ".$order->get_billing_first_name();
            $adresse=$order->get_billing_address_1()." ".$order->get_billing_address_2();
            $codepostal=$order->get_billing_postcode();
            $pays=$order->get_billing_country();
            $email=$order->get_billing_email();
            $telephone=$order->get_billing_phone();
            $total=number_format($order->get_total(), 2);





            //echo "<br>".$nomprenom."<br>".$telephone."<br>".$email."<br>".$adresse."<br>".$codepostal." ".$ville."<br>";
			$ticket.= "N°".$orderid.'<br>';
			$status=$order->get_status();
			if ($status != "completed"){
				$etat="Non payé";
			}
			else 
			{
				$etat="Payé";
			}
			
			
			$ticket.="status".$order->get_status().'<br>';
			$ticket.="status".$order->get_payment_method_title().'<br>';
			$ticket.=$order->get_total()."<br>";
			$ticket.=$etat."<br>";
            
            $ticket.= $nomprenom.'<br>';
            
            $ticket.= $telephone.'<br>';
            
            $ticket.= $email.'<br>';
            
            $ticket.= $adresse.'<br>';
            
            $ticket.= $codepostal." ".$ville.'<br>';
            

                if ( count( $order->get_items() ) > 0 ) {
                   
                    foreach ( $order->get_items() as $item_id => $item ) {
                  $product= $item->get_product();
                  $product = $item->get_product();

            // Get the product Id
            $product_id = $product->get_id();
			$product_name = $item->get_name();
           $price = number_format($product->get_price(), 2);
		   $quantity = $item->get_quantity();
            // Get the product name
            $subtotal = $item->get_subtotal();
           // $totalligne = number_format($item->get_total(), 2);
			$tax = $item->get_subtotal_tax();
			//$totalligne=$item->get_total();
			 
			  $item_taxes     = $item->get_taxes();
           //$taxeligne=$item_taxes[total][2];
           
           $taxeligne=array_values($item_taxes[total])[0]; 
			  
           $totalligne=$subtotal+$taxeligne;
           $totalligne = number_format($totalligne, 2);
			 
            //print_r(  $item_taxes );
			
//print_r ($item_taxes[total]);
//echo "<br>".$item->get_subtotal()."taxe".$taxeligne;

$tarifligne=$quantity."x".$price."=".$totalligne;
           // $ligne = $product_name."------".$quantity."x".$price."=".$totalligne."<br>";
           // $lignes=$lignes.$ligne;
$monnaie="€";

            $ticket .= Aespace($product_name,$tarifligne,$largeur, $monnaie,"l");
            

						//echo $item->get_name()."=".$item->get_quantity()." ".$item->get_subtotal()." ".$product->get_price()."<br>";
						
                        // Add order pay to available pay
                        $available_pay += $item->get_total();
                    }

                    $ticket.= Aespace("Total",$total,$largeur, $monnaie,"t");

                    echo $ticket;
                    

                }

                


            }
   
   
}

add_action('woocommerce_proceed_to_checkout', 'woocommerce_get_data', 10);
function woocommerce_get_data(){
	wp_localize_script( 'capitaine', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
	echo '<script>ajaxurl="'.admin_url('admin-ajax.php').'"</script>';
	$customer = WC()->session->get('customer');
	$options = get_option('wnb_settings');


	
	//WC()->session->set( 'heureretrait', current_time( 'mysql' ) );
	//WC()->session->set( 'heureretrait', 'hello'  );
//echo WC()->session->get( 'heureretrait', 'It can\'t be empty' );
	 //print_r ($customer);
	 date_default_timezone_set('Europe/Paris');
		   $jour=date('w');
			   
			   //echo "jour : ".$jour;
	$h1 = $options['j'.$jour.'h1'];
	$h2 = $options['j'.$jour.'h2'];
	$h3 = $options['j'.$jour.'h3'];
	$h4 = $options['j'.$jour.'h4'];
	
	//echo $h1.$h2.$h3.$h4;
      //echo $options['j4h1'];;
      $hm=date('H:i');
      

      if (($hm > $h1  && $hm < $h2) || ($hm > $h3  && $hm < $h4)  )	{

         if ($hm > $h1   && $hm < $h2)	{
            $hf = $h2;

         }
         if ($hm > $h3   && $hm < $h4)	{
            $hf = $h4;
           // echo "apresmidi".$h4;

         }

         //echo "boutique ouverte";

         $heure = date("H:i");
			  	
	
         $ho = $options['j5h1'];
         
          
         //echo 'hello'.strtotime($hf);
         //echo "fermeture.".$hf;
         $hr = WC()->session->get( 'hr' );
         //echo $hr;
         $difference=strtotime($hf)-strtotime($hm);
                      $nombredecrenaux=intval($difference/3600*4);
                      $options="<select id='heureretrait' name='heureretrait'>";
                      $options=$options."<option value='0'>Séléctionnez</option>";
                      for ($i=1; $i<=$nombredecrenaux; $i++) {
                          $pminute=$i*15;
                          $prochain=strtotime($hm)+900*$i;//15*60=900 seconds
                          $prochain=date("H:i",$prochain);
                          $prochainH = str_replace(":", "H",$prochain);
                     
                 
                     
                          $options=$options."<option value='".$prochain."'>Dans ".$pminute."min à ".$prochainH."</option>";
              
                       }
                       $options=$options."</select>";
                   echo "<div class='hr' >Sélectionnez l'heure de retrait avant : ".$hf."  <br><br>".$options."</div>";
                   //echo $options;
      }	  
			  
             
            

	
	
	
	
	
	//echo "<div class='hr' >Sélectionnez l'heure de retrait : <input type='time' id='heureretrait' name='heureretrait' value='".WC()->session->get( 'heureretrait')."'></div><br>";
	//echo "<input type='button' id='valid' name='valid'>";
}


add_action("wp_ajax_heureRetrait", "saveheureretrait");
add_action("wp_ajax_nopriv_heureRetrait", "saveheureretrait");

function saveheureretrait() {
	
	$options = get_option('wnb_settings');
	$hr = $_POST['hr'];
	$reponse=0;
	
	 $jour=date('w');
			   
			   //echo "jour : ".$jour;
	$h1 = $options['j'.$jour.'h1'];
	$h2 = $options['j'.$jour.'h2'];
	$h3 = $options['j'.$jour.'h3'];
	$h4 = $options['j'.$jour.'h4'];
	
	//echo $h1.$h2.$h3.$h4;
		//echo $options['j4h1'];;	  
		//echo $hr;	  
			  
             
             date_default_timezone_set('Europe/Paris');
              $heure = date("H:i");
			 // echo $heure;

if (($hr > $h1  && $hr < $h2) || ($hr > $h3  && $hr < $h4)  )
{
	

   $reponse=1;
   WC()->session->set( 'hr', $hr );
}





if ($hr < $heure) {
	
   $reponse = 0;
   WC()->session->set( 'hr', ''  );
}

	

echo $reponse;
	die( $reponse );
}
add_action("wp_ajax_ticketjour", "ticketjour");
add_action("wp_ajax_nopriv_ticketjour", "ticketjour");

function ticketjour(){
	echo ("mes tickets");
}




add_action('woocommerce_review_order_before_submit', 'woocommerce_get_data2', 10);
function woocommerce_get_data2(){
	$customer = WC()->session->get('customer');
	
	
   echo "<div  class='retrait'>Heure de retrait <span id='hr'>".WC()->session->get( 'hr' )."</span></div>";
   ?>
   <script>
   //alert("h"+ajaxurl);
  //console.log(NeveProperties);
jQuery(document).ready(function( $ ) {


$('#place_order').on('click', function(e) {
   hr=$('#hr').text();
  
   if (hr==''){
      e.preventDefault();
   alert("Vous devez choisir une heure de retrait");
   <?php
   echo 'carturl ="'.wc_get_cart_url().'";';
   ?>
   //alert(carturl);
   window.location= carturl;
   }
});
});
</script>
<?php


/*
	print_r ($customer);
	
	//WC()->session->set( 'heureretrait', current_time( 'mysql' ) );
	WC()->session->set( 'heureretrait', 'hello'  );
echo WC()->session->get( 'heureretrait', 'It can\'t be empty' );
	 //print_r ($customer);
	
	echo "<input type='time' id='heureretrait' name='heureretrait'>";
	echo "<input type='button' id='valid' name='valid'>";
	
	 
*/	
}




add_action('woocommerce_thankyou', 'sauvecommande', 10, 1);
function sauvecommande( $order_id ) {
	
	$largeur=40;
	global $wpdb;
	$ticket="";
	
	$hr = WC()->session->get( 'hr' );
	
    if ( ! $order_id )
        return;

    // Allow code execution only once 
    if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {

        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );

        // Get the order key
        $order_key = $order->get_order_key();

        // Get the order number
        $order_number = $order->get_order_number();
		
		
		$orderid=$order->get_id();
     
      $modepayement=$order->get_payment_method_title();
            $ville=$order->get_billing_city();
            $nomprenom=$order->get_billing_last_name()." ".$order->get_billing_first_name();
            $adresse=$order->get_billing_address_1()." ".$order->get_billing_address_2();
            $codepostal=$order->get_billing_postcode();
            $pays=$order->get_billing_country();
            $email=$order->get_billing_email();
            $telephone=$order->get_billing_phone();
            $total=number_format($order->get_total(), 2);
         $datecommande=$order->get_date_created();
         $status=$order->get_status();





            //echo "<br>".$nomprenom."<br>".$telephone."<br>".$email."<br>".$adresse."<br>".$codepostal." ".$ville."<br>";
		$ticket.= "N°".$orderid;
        $ticket.= "\\line ";		
        $ticket.= "Date : ".$datecommande;
        $ticket.= "\\line ";	
        
         $ticket.= "Heure de retrait : ".$hr;
         $ticket.= "\\line\\line ";		
        	
        	
			$ticket.= $nomprenom;
         $ticket.= "\\line ";		
        	
        
            $ticket.= $telephone;
            $ticket.= "\\line ";		
           	
           
            $ticket.= $email;
            $ticket.= "\\line ";		
           	
           
            $ticket.= $adresse;
            $ticket.= "\\line ";		
        	
        
            $ticket.= $codepostal." ".$ville;
            $ticket.= "\\line\\line ";		
        	
        
           
		
		

        if($order->is_paid())
            $paid = __('yes');
        else
            $paid = __('no');

        // Loop through order items
        foreach ( $order->get_items() as $item_id => $item ) {

         $product= $item->get_product();
         $product = $item->get_product();

   // Get the product Id
   $product_id = $product->get_id();
$product_name = $item->get_name();
  $price = number_format($product->get_price(), 2);
$quantity = $item->get_quantity();
   // Get the product name
   $subtotal = $item->get_subtotal();
  // $totalligne = number_format($item->get_total(), 2);
$tax = $item->get_subtotal_tax();
//$totalligne=$item->get_total();
 
  $item_taxes     = $item->get_taxes();
  //$taxeligne=$item_taxes[total][2];
  
  $taxeligne=array_values($item_taxes[total])[0]; 
  
  $totalligne=$subtotal+$taxeligne;
  $totalligne = number_format($totalligne, 2);
  
            


$tarifligne=$quantity."x".$price."=".$totalligne;
           // $ligne = $product_name."------".$quantity."x".$price."=".$totalligne."<br>";
           // $lignes=$lignes.$ligne;
$monnaie="€";

            $ticket .= Aespace($product_name,$tarifligne,$largeur, $monnaie,"l");
        }
		
       $ticket.= Aespace("Total",$total,$largeur, $monnaie,"t");
	   
	   $status=$order->get_status();
			if ($status != "completed"){
				$etat="Non payé";
			}
			else 
			{
				$etat="Payé";
			}
			
			$ticket.="Etat : ".$etat;
	   
       //$ticket.= $status." ".$order->is_paid();
      $ticket.= "\\line ";		
		
		

        // Output some data
        //echo '<p>    Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
//echo "<br>".$ticket."<br>";
		
		
		//$sql_insert = "INSERT INTO `wp_dporders`(`idorder`, `commande`, `printed`, `datecommande`, `heureretrait`) VALUES (\'780\',\'lignes\',\'0\',\'2020-10-10\',\'2020-10-10\')";

//$sql_insert = "INSERT INTO ".$wpdb->prefix."dporders ( idorder, commande ) VALUES (".$order_id.",".$commande.")";
//$ticket = $wpdb::_real_escape( $ticket );


$sql_insert = "INSERT INTO ".$wpdb->prefix."dporders ( idorder, commande, heureretrait, printed, datecommande ) VALUES (".$order_id.",'".$wpdb->esc_like( $ticket )."','".$hr."', 0,'".$datecommande."' )";
//echo "<br>".$sql_insert."<br>";

echo "<div class='retrait'>Venez retirer votre commande à ".$hr."</div>";


$wpdb->query($sql_insert);
WC()->session->set( 'hr', ''  );




        // Flag the action as done (to avoid repetitions on reload for example)
        $order->update_meta_data( '_thankyou_action_done', true );
        $order->save();
    }
}



function activate_directprint(){
	
	global $wpdb;
	
	 $sql_dporders  = "CREATE TABLE ".$wpdb->prefix."dporders (
            id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			idorder INT( 11 ) ,
            commande TEXT ,
            printed INT( 11 ) ,
            datecommande DATETIME ,
            heureretrait TEXT 

        )";
	$wpdb->query($sql_dporders);
	
	
	
	
}


function Aespace($produit,$tarifligne,$largeur,$m,$balise)

{

    //$produit="ÉÉÉÉ";

    if ($balise=="l"){

        $balise1="<ligne1>";

        $balise2="</ligne1>";



    }

    else

{

    $balise1="<total>";

    $balise2="</total>";

}



    $xml="";

    $Ltarifligne=strlen($tarifligne)+2;

    $librec1=$largeur-$Ltarifligne-3;

    $Lproduit=mb_strlen($produit, 'UTF-8');

    

    if ($Lproduit>$librec1){

        $nombredecoupes=floor($Lproduit/$librec1);

        $pligne="";

        $p="";

        for ($ncoupe = 1; $ncoupe <= $nombredecoupes; $ncoupe++) {

           

        $coupe=($ncoupe+1)*$librec1;

            $pligne =mb_substr($produit,($ncoupe*$librec1),$librec1)."\line ";
            

            $pligne = ltrim($pligne);

            $p.=$pligne;

        }

        $Eproduit=$librec1-$Lproduit;

        $p1=mb_substr($produit,0,$librec1);

        $p2=mb_substr($produit,$librec1,$Lproduit);

        $tarifligne=str_repeat("\x20", 3).$tarifligne;

        $xml = $p1.$tarifligne." ".$m;
        $xml  .= "\\line ";
        
       // $xml .= $balise1.$p1.$tarifligne." ".$m." <br> ".$balise2."\\r\\n";

       //$xml .= $p2." <br> "."\\r\\n";

        $xml .= $p;

        //$xml .= $produit." <br> \\r\\n";



    }

    if ($Lproduit<$librec1){

        $Eproduit=$librec1-$Lproduit;

        $p1=mb_substr($produit,0,$librec1);

        $tarifligne=str_repeat("\x20", 3).$tarifligne;

        $xml = $produit.str_repeat("\x20",$Eproduit).$tarifligne." ".$m;
        $xml  .= "\\line ";
     

    }

    //echo $Lproduit.":".$produit."<br>";

    



return $xml;

}