<?php
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  21/03/11, 18:38
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class relance_order
  @brief module cron de triatement des commandes ayant un status en attente
    Ce module assure l'envoi d'un mail de relance apres X jours d'attente, puis
    Bascule le status de la commande sur un nouveau status si aucune modifiction intervient apres X jours
    Pour chaque action , il est possible d'effectuer une notification au client, et un recapitulatif dans les notifications admin .

    Cette class intégres à la fois l'execution cron proprement dite, et la gestion de sa configuration specifique.
    Plusieurs occurence de ce module avec des  configuration specifique peuvent être actives

    Ce module depend de la configuration de contenu de mail specifique , stocké en db et configurer poru chaque langue
*/

class relance_order
  implements IntModCronJobConfig, IntModCronJob{

  /**
    @var string laert le jour J, or avant l'anniversaire (+2)
  */
  CONST ECART = ''; //'+2';


  /**
    @var boolean active config module
  */
  public $config=true;

  /**
    @fn __construct()
    @brief Init and Load fiel lang module
  */
  public function __construct(){
    global  $language,$oscss;

    $oscss=oscss_cstr::getInstance();
    $oscss->pile_file_lang(DIR_FS_ADMIN.DIR_WS_LANGUAGES.$language.'/modules/cronjob/'.__CLASS__.'.txt');
  }

  /**
    @fn insert($post)
    @brief method call by action insert in modules/page/cronjob , adjust extra for this module
    @param $post array POST vars
    @return $string serialise for extra db fields
  */
  public function insert($post){
//     $sql;
//     foreach($this->keys as $item)
//       $sql[$item]= array($item,addslashes($post[$item]));

    return serialize($post);
  }

  /**
    @fn update($post)
    @brief method call by action update in modules/page/cronjob , adjust extra for this module
    @param $post array POST vars
    @return $string serialise for extra db fields
  */
  public function update($post){
    return serialize($post); //$this->insert($post);
  }

  /**
    @brief help for this module
    @return string;
  */
  public function help(){
    return __('help this module');
  }

  /**
    @fn Config($value)
    @brief methode for complete config cronmodule, by use extra fields db
    @param $value string serialized, extract in extar fields db
    @return array for use lib.configuration.php functions
  */
  public function Config($value){

  $config=new objectInfo(unserialize($value));
  $list='';
  $r=explode(';',MODULE_PAYMENT_INSTALLED);
  foreach($r as $i)
    if(!empty($i))$list.="'".$i."',";


  $ArrayConfig=
  array(
    // tabs help
    array(
      'text'=>__('mod tabs help'),
      'string'=>__('help this module'),
    ),
    // tabs config
    array(
      'text'=>__('mod tabs configuration'),
      'array'=>
	  array(
	    'order_status'=>
	      array(
		'title'=>__('choose type orders'),
		'description'=>__('choose type orders for action cronjob'),
		'set_function'=>'tep_cfg_pull_down_order_statuses(',
		'use_function'=>'tep_get_order_status_name',
		'value'=>@$config->order_status,
	      ),
	    'order_paiement'=>
	      array(
		'title'=>__('choose type paiement'),
		'description'=>__('choose type orders for action cronjob'),
		'set_function'=>'tep_cfg_select_option(array('.$list.'),'.'',
  // 		'use_function'=>'tep_get_order_status_name',
		'value'=>@$config->order_paiement,
	      ),
      ),
    ),
    array(
      'text'=>__('mod tabs Action mail'),
      'array'=>
            array(
	      'order_delay'=>
		array(
		  'title'=>__('choose delay first actions, send mail'),
		  'description'=>__('choose delay for first action cronjob, value in days. the first action is send mail, if is null no exec'),
      // 	    'set_function'=>'tep_cfg_select_option(array(\'true\', \'false\'),'.'',
      //     	'use_function'=>'tep_get_order_status_name',MODULE_PAYMENT_INSTALLED
		  'value'=>(isset($config->order_delay)? $config->order_delay : '8'),
		),
	      'order_delay_log_orders_history'=>
		array(
		  'title'=>__('status after send mail'),
		  'description'=>__('status after send mail description'),
		  'set_function'=>'tep_cfg_pull_down_order_statuses(',
		  'use_function'=>'tep_get_order_status_name',
		  'value'=>(isset($config->order_delay_log_orders_history)? $config->order_delay_log_orders_history : '5'),
		),
	      'order_delay_log_notify'=>
		array(
		  'title'=>__('log action in history orders'),
		  'description'=>__('add log in current history order'),
		  'set_function'=>'tep_cfg_select_option(array(\'true\', \'false\'),',
		  'use_function'=>'tep_value_for_humain',
		  'value'=>(isset($config->order_delay_log_notify)? $config->order_delay_log_notify : 'true'),
		),
	  ),
    ),
    array(
      'text'=>__('mod tabs Action annulation'),
      'array'=>
	array(
	  'order_update'=>
	    array(
	      'title'=>__('choose delay second actions, annulate order'),
	      'description'=>__('choose delay for second action cronjob, value in days. the second action is update order for status annulate mail, if is null no exec'),
      // 	'set_function'=>'$Module->(',
      // 	'use_function'=>'tep_get_order_status_name',
	      'value'=>@$config->order_update,
	    ),
	  'order_update_status'=>
	    array(
	      'title'=>__('choose status orders for second action'),
	      'description'=>__('choose status orders for second action description'),
	      'set_function'=>'tep_cfg_pull_down_order_statuses(',
	      'use_function'=>'tep_get_order_status_name',
	      'value'=>@$config->order_update_status,
	    ),
	  'order_update_notify_customers'=>
	    array(
	      'title'=>__('order_update notification customers'),
	      'description'=>__('order_update notification customer description'),
	      'set_function'=>'tep_cfg_select_option(array(\'true\', \'false\'),',
	      'use_function'=>'tep_value_for_humain',
	      'value'=>(isset($config->order_update_notify_customers)? $config->order_update_notify_customers : 'true'),
	    ),
	  'order_update_log_notify'=>
	    array(
	      'title'=>__('order_update log notification'),
	      'description'=>__('order_update log notification description'),
	      'set_function'=>'tep_cfg_select_option(array(\'true\', \'false\'),',
	      'use_function'=>'tep_value_for_humain',
	      'value'=>(isset($config->order_update_log_notify)? $config->order_update_log_notify : 'true'),
	    ),
	),
      ),
//     ),
   );


    return $ArrayConfig;
  }


  public function ConfigDelay(){

  }

  /**
    @brief methode return key config module
  */
  public function keys(){
    return array('order_status', 'order_delay');
  }

  /**
    @fn ClassExec()
    @brief method call by cron file. this it THE METHODE CRON
  */
  public function ClassExec($value){
    global $language,$languages_id;

    $config=new objectInfo(unserialize($value));
    // array for not send mail action 2 if mail in action 1
    $BlockDb=array();
    $Where='';

  /// Gestion des alerts mails relance

var_dump(_test_bool($config->order_update_log_notify));
exit;
    if((int)$config->order_delay !=0){
      /**
	@remarks Add action for send mail in critere date (date_purchased)
      */
      $Where =" AND o.date_purchased < DATE_ADD(now(), INTERVAL ".$config->order_delay." DAY)  AND (o.last_modified <= o.date_purchased  OR o.last_modified IS NULL)  ";


echo      $query_raw = "select distinct o.orders_id,o.orders_prefix, o.customers_id, o.customers_name, o.payment_method, o.class_payment , o.date_purchased, o.last_modified, o.currency, o.currency_value, s.status_name as orders_status_name, s.status_color as orders_status_color, ot.text as order_total from " . TABLE_ORDERS . " o left join " . TABLE_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_STATUS . " s WHERE o.orders_status = s.status_id  and s.status_type='orders' AND s.language_id = '" . (int)$languages_id . "' AND ot.class = 'ot_total' AND  o.orders_status='".(int)$config->order_status."' AND o.class_payment='".(string)substr($config->order_paiement,0,-4)."' ".$Where." ;";

      $bdqry = tep_db_query($query_raw);

      if (tep_db_num_rows($bdqry) > 0) {
	//; text for admin notif repport
	$txt_notif='';
	while($bdarr = tep_db_fetch_array($bdqry)) {

	  $order = new order((int)$bdarr['orders_id']);
var_dump('email:: ',$order->customer['name']);

	  $bd_sub = sprintf(__('email subject relance'), $order->customer['name']);
	  $bd_msg = sprintf(__('email content relance'), $order->customer['name'],$order->info['payment_method'], $config->order_delay );

	  /**
	    TODO: use lang customers !!
	  */
	  $myarray = array(
		    'email_use_html'=>_cst_bool('EMAIL_USE_HTML'),
		    'subject'=>$bd_sub,
		    'message'=>$bd_msg
		    );


	  /**
	    TODO add modele in db for form satisfaction shop ??
	  */

	  $message_final=emailUtility::post_prepare_email("cron_update_order.tpl",$language,$myarray);
// 	  var_dump($message_final);

  	    tep_mail($order->customer['name'], $order->customer['email_address'], $bd_sub, $message_final, STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, '');
	    /**
	      @remarks up status after send mail customers
	    */
	    tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . (int)$bdarr['orders_id'] . "', '" .(int)$config->order_delay_log_orders_history . "', now(), '1', '" . tep_db_input( __('txt cron auto send mail') )  . "')");

	    tep_db_perform(TABLE_ORDERS, array('orders_status'=>(int)$config->order_delay_log_orders_history,'last_modified'=>'now()'), 'update', " orders_id='".(int)$bdarr['orders_id'] ."' ");

	    $txt_notif .=sprintf(__('cronjob orders %s send mail after %s days for this client %s '),
			/*link orders */ '<a href="'.tep_href_link(FILENAME_ORDERS, 'cID='.(int)$bdarr['orders_id']).'" >'.(int)$bdarr['orders_id'].'</a>',
			/* nbr jours  */$config->order_delay ,
			/* liens client  */ '<a href="'.tep_href_link(FILENAME_CUSTOMERS, 'cID='.(int)$order->customer['id']).'" >'.$order->customer['name'].'</a>')
			.'<br />';

	  }

	/**
	  Recap for notif admin
	*/
	if(_test_bool($config->order_delay_log_notify))
	  notification::notifInMess('cronjob',__('cronjob log repport exec'),$txt_notif,array());


      }


    }





  /// Gestion de maintenance des commandes non reglé

    if((int)$config->order_update !=0) {
      /**
	@remarks Add action for send mail in critere date (last modified) and no updated
      */
      $Where =" AND o.last_modified <= DATE_ADD(now(), INTERVAL ".$config->order_update." DAY) ";

echo      $query_raw = "select distinct o.orders_id,o.orders_prefix, o.customers_id, o.customers_name, o.payment_method, o.class_payment , o.date_purchased, o.last_modified, o.currency, o.currency_value, s.status_name as orders_status_name, s.status_color as orders_status_color, ot.text as order_total from " . TABLE_ORDERS . " o left join " . TABLE_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_STATUS . " s WHERE o.orders_status = s.status_id  and s.status_type='orders' AND s.language_id = '" . (int)$languages_id . "' AND ot.class = 'ot_total' AND  s.status_id IN('".(int)$config->order_status."', '".(int)$config->order_delay_log_orders_history."') AND o.class_payment='".(string)substr($config->order_paiement,0,-4)."' ".$Where." ORDER BY   o.orders_id DESC";

      $bdqry = tep_db_query($query_raw);

      if (tep_db_num_rows($bdqry) > 0) {
	//; text for admin notif repport
	$txt_notif='';
	while($bdarr = tep_db_fetch_array($bdqry)) {

	$order = new order((int)$bdarr['orders_id']);
var_dump('upadte:: ',$order->customer['name']);

	$bd_sub = sprintf(__('email subject update'), $order->customer['name']);
	$bd_msg = sprintf(__('email content update'), $order->customer['name'],$order->info['payment_method'], $config->order_update );

	/**
	  TODO: use lang customers !!
	*/
	$myarray = array(
		  'email_use_html'=>_cst_bool('EMAIL_USE_HTML'),
		  'subject'=>$bd_sub,
		  'message'=>$bd_msg
		  );


	$message_final=emailUtility::post_prepare_email("cron_relance_order.tpl",$language,$myarray);

	if(_test_bool($config->order_update_notify_customers))
	  tep_mail($order->customer['name'], $order->customer['email_address'], $bd_sub, $message_final, STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, '');

	/**
	  @remarks update status orders + logs history orders
	*/
	tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . (int)$bdarr['orders_id'] . "', '" .(int)$config->order_update_status . "', now(), '1', '" . tep_db_input( __('txt cron auto annulate orders') )  . "')");

	tep_db_perform(TABLE_ORDERS, array('orders_status'=>(int)$config->order_update_status,'last_modified'=>'now()'), 'update', " orders_id='".(int)$bdarr['orders_id'] ."' ");


	$txt_notif .=sprintf(__('cronjob update orders %s status for %s after %s days for this client %s '),
		    /*link orders */ '<a href="'.tep_href_link(FILENAME_ORDERS, 'cID='.(int)$bdarr['orders_id']).'" >'.(int)$bdarr['orders_id'].'</a>',
		    /* statune name */ $order->info['orders_status'],
		    /* nbr jours  */$config->order_update ,
		    /* liens client  */ '<a href="'.tep_href_link(FILENAME_CUSTOMERS, 'cID='.(int)$order->customer['id']).'" >'.$order->customer['name'].'</a>')
		    .'<br />';
      }

      /**
	Recap for notif admin
      */
      if(_test_bool($config->order_update_log_notify))
	notification::notifInMess('cronjob',__('cronjob log repport exec'),$txt_notif,array());
      }
    }
  }
}
?>