<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2010  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  15/12/10, 15:32
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class recover_cart_sales
*/

class recover_cart_sales
  implements ExtModPage, InterfacedTJsonS , InterfaceModule{

  const FILENAME = FILENAME_RECOVER_CART_SALES;

  public static $code;

  public static $action;

  public static $list=array();
  public static $basedays;
  public static $skipdays;


  public static $cID;


  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;

    self::init();
  }

  public function check_action($actions){
    global $messageStack;

    self::$action=$actions;
    $DB=Database::getInstance();
    switch (self::$action) {
      case 'delete_confirm':
	if(isset($_GET['cID'])){
	  $reset_query_raw = "delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id=" . (int)$_GET['cID'];
	  $DB->query($reset_query_raw);

	  $reset_query_raw2 = "delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id=" . (int)$_GET['cID'];
	  $DB->query($reset_query_raw2);
	}
	tep_redirect(tep_href_link(self::FILENAME, 'tdate=' . (int)$_GET['tdate']));
      break;
    }

    return self::$action;
  }

  public function get_header(){
  }


  public static function load_db_values($ID){
/*
    $DB=Database::getInstance();

    $currency_query_raw = "select recover_cart_sales_id, title, code, symbol_left, symbol_right, decimal_point, thousands_point, decimal_places, last_updated, value from " . TABLE_CURRENCIES . " WHERE recover_cart_sales_id='".$ID."' ";
    $currency_query = $DB->query($currency_query_raw);

    return new objectInfo($currency_query->fetchAssoc() );*/
  }

  public function display_view(){
    switch(self::$action){
      case 'delete':
	self::$cID = (isset($_GET['cID'])) ? $_GET['cID'] : '';
	return tep_get_include_contents(self::$code.'.delete');
      break;
      case 'execute':
	$custid = (isset($_POST['custid'])) ? $_POST['custid'] : '';
	$this->processEmail($custids);
	return tep_get_include_contents(self::$code.'.execute');
      break;
      default:
	self::tep_get_list();
	return tep_get_include_contents(self::$code.'.listing');
    }
  }


/** Private  Specific interne module */
  private static function init(){
    self::$basedays = (isset($_GET['tdate']))? (int)$_GET['tdate'] :(int)RCS_SKIP_DAYS;
    self::$skipdays = (isset($_GET['sdate']))? (int)$_GET['sdate']: (int)RCS_BASE_DAYS;

    //! active datatable in ajax, precise les GET necessaire
    if(!defined('JSONSTATMENT'))define('JSONSTATMENT', 'mod=page&type='.self::$code.'&tdate='.self::$basedays.'&sdate='.self::$skipdays.'');
  }

  private static function seadate($day) {
    return date("Ymd", strtotime("-".$day." days"));
  }

/** Public Specific interne module */


  /**
    This will return a list of customers with sessions. Handles either the mysql or file case
    Returns an empty array if the check sessions flag is not true (empty array means same SQL statement can be used)
  */
  public static function _GetCustomerSessions() {
    $cust_ses_ids = array();
    $DB=Database::getInstance();
    if(_cst_bool('RCS_CHECK_SESSIONS')) {
      if (STORE_SESSIONS == 'mysql') {
	// --- DB RECORDS ---
	$sesquery = $DB->query("select value from " . TABLE_SESSIONS . " where 1");
	while ($ses = $sesquery->fetchAssoc()) {
	  if ( preg_match( "#customer_id[^\"]*\"([0-9]*)\"#", $ses['value'], $custval ) )
		  $cust_ses_ids[] = $custval[1];
	}
      }
      else {
	if( $handle = opendir( tep_session_save_path() ) ) {
	  while (false !== ($file = readdir( $handle )) ) {
	    if ($file != "." && $file != "..") {
	      $file = tep_session_save_path() . '/' . $file;	// create full path to file!
	      if( $fp = fopen( $file, 'r' ) ) {
		$val = fread( $fp, filesize( $file ) );
		fclose( $fp );

		if ( preg_match( "#customer_id[^\"]*\"([0-9]*)\"#", $val, $custval ) ) $cust_ses_ids[] = $custval[1];
	      }
	    }
	  }
	  closedir( $handle );
	}
      }
    }
    return $cust_ses_ids;
  }

  /**
    Repost date search in get
  */
  public static function RepostDate(){
    return 'tdate='.self::$basedays.'&amp;sdate='.self::$skipdays;
  }
  /**
    *
    * \brief Sends an email for the incomplete sales for the given customer(id)s.
    *
    */
  private function processEmail($custids) {
    global $currencies, $languages_id;

    $DB=Database::getInstance();


      if (is_array($custids))
	foreach ($custids as $cid)  {
	  unset($email);
	  $customer = '';

	  $query1 = $DB->query("select cb.products_id pid, cb.customers_basket_quantity qty, cb.customers_basket_date_added bdate, cus.customers_firstname fname, cus.customers_lastname lname, cus.customers_email_address email
				  from      " . TABLE_CUSTOMERS_BASKET . " cb, " . TABLE_CUSTOMERS . " cus
				  where     cb.customers_id = cus.customers_id  and cus.customers_id = '".$cid."'
				  order by  cb.customers_basket_date_added desc ");

	  $knt = $query1->__get('numRows');
	  $lastcid = '';
	  $mline = '';
	    for ($i = 0; $i < $knt; $i++) {
	      $inrec = $query1->fetchAssoc();

	      // set new cline and curcus
	      if ($lastcid != $cid) {
		if ($lastcid != "") {
		  $this->infoBoxContents[] = array('text' => '<strong>' . TABLE_CART_TOTAL . '</strong>' . $currencies->format($tprice));
		  $this->infoBoxContents[] = array('text' => '<a class="button" href="' . tep_href_link(FILENAME_RECOVER_CART_SALES, "action=delete&amp;customer_id=" . $cid . "&amp;tdate=" . $this->basedays . "&amp;sdate=" . $this->skipdays) . '">' . tep_image_button('button_delete.gif', IMAGE_DELETE) . '</a>');
		}
		$this->infoBoxContents[] = array('text' => '<a class="button" href="' . tep_href_link(FILENAME_CUSTOMERS, 'search=' . $inrec['lname'], 'NONSSL') . '">' . $inrec['fname'] . '&nbsp;' . $inrec['lname'] . '</a>' . $customer);
		$tprice = 0;
	      }
	      $lastcid = $cid;

	      // get the shopping cart
	      $query2 = $DB->query("select   p.products_price price, p.products_tax_class_id taxclass, p.products_model model, pd.products_name name
				    from    " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_LANGUAGES . " l
				    where   p.products_id = '" . $inrec['pid'] . "' and pd.products_id = p.products_id and pd.language_id = " . (int)$languages_id );

	      $inrec2 = $query2->fetchAssoc();
	      $sprice = tep_get_products_special_price( $inrec['pid'] );
	      if( $sprice < 1 ) $sprice = $inrec2['price'];

	      // Some users may want to include taxes in the pricing, allow that. NOTE HOWEVER that we don't have a good way to get individual tax rates based on customer location yet!
	      if(_cst_bool('RCS_INCLUDE_TAX_IN_PRICES '))$sprice += ($sprice * tep_get_tax_rate( $inrec2['taxclass'] ) / 100);
	      elseif( _cst_bool('RCS_USE_FIXED_TAX_IN_PRICES') && RCS_FIXED_TAX_RATE > 0 ) $sprice += ($sprice * RCS_FIXED_TAX_RATE / 100);

	      $tprice = $tprice + ($inrec['qty'] * $sprice);
	      $pprice_formated  = $currencies->format($sprice);
	      $tpprice_formated = $currencies->format(($inrec['qty'] * $sprice));

	      $this->infoBoxContents[] = array('text' => TABLE_HEADING_MODEL . $inrec2['model']);
	      $this->infoBoxContents[] = array('text' => TABLE_HEADING_DESCRIPTION . '<a class="button" href="' . tep_href_link(FILENAME_CATEGORIES, 'action=new_product_preview&amp;read=only&amp;pID=' . $inrec['pid'] . '&amp;origin=' . FILENAME_RECOVER_CART_SALES) . '">' . $inrec2['name'] . '</a>');
	      $this->infoBoxContents[] = array('text' => TABLE_HEADING_QUANTY . $inrec['qty']);
	      $this->infoBoxContents[] = array('text' => TABLE_HEADING_PRICE . $pprice_formated);
	      $this->infoBoxContents[] = array('text' => TABLE_HEADING_TOTAL . $tpprice_formated);

	      if( _cst_bool('EMAIL_USE_HTML'))  $mline .= $inrec['qty'] . ' x <a class="button" href="' . tep_catalog_href_link(FILENAME_CATALOG_PRODUCT_INFO, 'products_id='. $inrec['pid']) . '">' . $inrec2['name'] . '</a>' . "\n";
	      else  $mline .= $inrec['qty'] . ' x ' . $inrec2['name'] . "\n";

	    }

	    $cquery = $DB->query("select * from " . TABLE_ORDERS . " where customers_id = '".$cid."'" );

	    $custname = $inrec['fname']." ".$inrec['lname'];
	    $outEmailAddr = '"' . $custname . '" <' . $inrec['email'] . '>';

	    $email_ovner=( tep_not_null(EMAIL_FEEDBACK) )? EMAIL_FEEDBACK : EMAIL_FROM ;
	    $myarray = array(
		      'mail_sent_to'=>$mail_sent_to,
		      'from'=>$from,
		      'subject'=>$subject,
		      'links_account'=>tep_catalog_href_link(FILENAME_LOGIN, '', 'SSL'),
		      'mline'=>$mline,
		      'message'=>$content
		      );

	    $message_final=tep_post_prepare_email('recover_cart_sales.tpl',$language,$myarray);
	    tep_mail('',$outEmailAddr, EMAIL_TEXT_SUBJECT, $message_final, STORE_OWNER, $email_ovner);

	    //Copy
	    if( tep_not_null(RCS_EMAIL_COPIES_TO) )
	    tep_mail(STORE_OWNER, RCS_EMAIL_COPIES_TO, EMAIL_TEXT_SUBJECT, $message_final, STORE_OWNER, $email_ovner);

	    $mline = "";

	    // See if a record for this customer already exists; if not create one and if so update it
	    $donequery = $DB->query("select * from ". TABLE_SCART ." where customers_id = '".$cid."'");
	    if (tep_db_num_rows($donequery) == 0) $DB->query("insert into " . TABLE_SCART . " (customers_id, dateadded, datemodified ) values ('" . $cid . "', '" . $this->seadate('0') . "', '" . $this->seadate('0') . "')");
	    else $DB->query("update " . TABLE_SCART . " set datemodified = '" . $this->seadate('0') . "' where customers_id = " . $cid );
	  }




  }

  /** public static InterfacedTJsonS */

  private static function get_item_action($item){
    return '<span class="view fils fleft">'.
            '<a class="buttonimg fancyView iframe " href="' . tep_href_link(self::FILENAME, 'cID=' . $item['customers_id'] .'&amp;'.recover_cart_sales::RepostDate(). '&amp;action=delete') . '">' .  tep_image(DIR_WS_ICONS . 'icon_delete.png',IMAGE_DELETE ). '</a>'.
            '</span>';
  }

  private static function get_item_cart($cart,$item){
    global $price;

    $s = '<table>';
      foreach($item as $k=>$i)
	$s .= '<tr>'.
		'<td>'.$i['qty'].' '.$i['modele'].'<br />'.'<a  href="' . tep_href_link(FILENAME_PRODUCTS, 'action=new_product_preview&amp;read=only&amp;pID=' . $i['pID'] . '&amp;origin=' . self::FILENAME) . '"><strong>' . $i['name'] . '</strong></a>' .'</td>'.
		'<td>'.$i['TOT_TTC'].'</td>'.
	      '</tr>';

    $s .= '<tr>'.
	    '<td>'.__('sous total').'</td>'.
	    '<td>'.$price->format($cart['total_cart']).'</td>'.
	  '</tr>';
    $s .= '</table>';
    return $s;
  }

  public static function tep_get_modele(){
    return array( 0=>false,
		  'customers_basket_date_added'=>true,
                  'customers_firstname'=>true,
                  'customers_email_address'=>true,
		  'total'=>false,
		  'status'=>false,
		  'action'=>false
                );
  }

  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows,$languages_id,$price;

    self::init();
    $skip=false;

    $DB=Database::getInstance();
    $cust_ses_ids = self::_GetCustomerSessions();


    $query_raw = "select cb.customers_id , cb.products_id , cb.customers_basket_quantity qty, cb.customers_basket_date_added, cus.customers_firstname , cus.customers_lastname , cus.customers_telephone , cus.customers_email_address  ".
		"from   " . TABLE_CUSTOMERS_BASKET . " cb, " . TABLE_CUSTOMERS . " cus ".
		"where  cb.customers_basket_date_added <= '" . self::seadate(self::$basedays) . "' and  cb.customers_basket_date_added >= '" . self::seadate(self::$skipdays) . "' ".(!empty($cust_ses_ids) ? " and cus.customers_id not in ('" . implode(", ", $cust_ses_ids) . "')" : "") ." and  cb.customers_id = cus.customers_id ".$sWhere." ".
		"ORDER BY ".((!empty($sOrder)) ? $sOrder : " cb.customers_basket_date_added desc, cb.customers_id ");

    $split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

    $query = $DB->query($query_raw);

    while ($in_cart = $query->fetchAssoc() ) {

      $sentdate='';
      $checked = 1;
      $tprice=0;
      $donequery = $DB->query("select * from ". TABLE_SCART ." where customers_id = '".$in_cart['customers_id']."'");
      $emailttl = self::seadate(RCS_EMAIL_TTL);

      if ($donequery->__get('numRows') > 0) {
	$ttl = $donequery->fetchAssoc();
	if( $ttl ){
	  if( tep_not_null($ttl['datemodified']) )$ttldate = $ttl['datemodified'];	// allow for older scarts that have no datemodified field data
	  else $ttldate = $ttl['dateadded'];

	  if ($emailttl <= $ttldate) {
	    $sentdate = $ttldate;
	    $fcolor = RCS_CONTACTED_COLOR;
	    $checked = 0;
	    $new = 0;
	  }
	}
      }

      /*
	See if the customer has purchased from us before
	Customers are identified by either their customer ID or name or email address
	If the customer has an order with items that match the current order, assume order completed, bail on this entry!
      */
      $ccquery = $DB->query('select orders_id, orders_status from ' . TABLE_ORDERS . ' where (customers_id = ' . $in_cart['customers_id']. ' OR customers_email_address like "' . $in_cart['customers_email_address'] .'" or customers_name like "' . $in_cart['customers_firstname'] . ' ' . $in_cart['customers_lastname'] . '") and orders_status NOT IN (' . implode(unserialize(RCS_PENDING_SALE_STATUS), ',') . ') and date_purchased >= "' . (RCS_CARTS_MATCH_ALL_DATES ? '0' : $in_cart['customers_basket_date_added']) . '"' );
      if (tep_db_num_rows($ccquery) > 0) {
	// We have a matching order; assume current customer but not for this order

	// Now, look to see if one of the orders matches this current order's items
	while( $orec =  $ccquery->fetchAssoc() ) {
	  $ccquery = $DB->query( 'select products_id from ' . TABLE_ORDERS_PRODUCTS . ' where orders_id = ' . (int)$orec['orders_id'] . ' AND products_id = ' . (int)$in_cart['products_id'] );
	  if( $ccquery->__get('numRows') > 0 )  {
	    // OK, we have a matching order; see if we should just skip this or show the status
	    if(_cst_bool('RCS_SKIP_MATCHED_CARTS')) {
	      $skip = true;	// reset flag & break us out of the while loop!
	      break;
	    }
	    else  {
	      // It's rare for the same customer to order the same item twice, so we probably have a matching order, show it
	      $fcolor = RCS_MATCHED_ORDER_COLOR;
	      $ccquery = $DB->query("select status_name as orders_status_name from " . TABLE_STATUS . " where status_type='orders' language_id = " . (int)$languages_id . " AND status_id = " . (int)$orec['orders_status'] );

	      if( $srec =  $ccquery->fetchAssoc() )  $status = ' [' . $srec['orders_status_name'] . ']';
	      else  $status = ' ['. __('text current customer') . ']';
	    }
	  }
	}

	if( $skip )
	continue;	// got a matched cart, skip to next one
      }
      $sentInfo = __('text not contacted');

      if ($sentdate != '') $sentInfo = tep_datetime_short($sentdate); // $this->cart_date_short($sentdate);



      $in_cart['customers_basket_date_added']=substr($in_cart['customers_basket_date_added'],6).'-'.substr($in_cart['customers_basket_date_added'],4,2).'-'.substr($in_cart['customers_basket_date_added'],0,4);
      $in_cart['customers_firstname']=tep_customers_row_action($in_cart['customers_id'], array('origin'=>self::FILENAME));
      $in_cart[0]=tep_draw_checkbox_field('custid[]','', $in_cart['customers_id'], RCS_AUTO_CHECK == 'true' ? $checked : 0);
      $in_cart['status']=$sentInfo;



	      // We only have something to do for the product if the quantity selected was not zero!
        if ($in_cart['qty'] != 0) {
	  // Get the product information (name, price, etc)
	  $query2 = $DB->query("select  p.products_price price,
				    p.products_tax_class_id taxclass,
				    p.products_model model,
				    pd.products_name name
				  from    " . TABLE_PRODUCTS . " p,
				    " . TABLE_PRODUCTS_DESCRIPTION . " pd,
				    " . TABLE_LANGUAGES . " l
				  where   p.products_id = '" . (int)$in_cart['products_id'] . "' and
				    pd.products_id = p.products_id and
				    pd.language_id = " . (int)$languages_id);
	  $inrec2 = $query2->fetchAssoc();

/**
  TODO: Exploiter la class price cf tep_get_products_special_price()
  @date  22/07/10, 23:55
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
*/
	  // Check to see if the product is on special, and if so use that pricing
	  $sprice = tep_get_products_special_price( $in_cart['products_id'] );
	  if( $sprice < 1 ) $sprice = $inrec2['price'];

	  // Some users may want to include taxes in the pricing, allow that. NOTE HOWEVER that we don't have a good way to get individual tax rates based on customer location yet!
	  if(_cst_bool('RCS_INCLUDE_TAX_IN_PRICES ')) $sprice += ($sprice * tep_get_tax_rate( $inrec2['taxclass'] ) / 100);
	  elseif(_cst_bool('RCS_USE_FIXED_TAX_IN_PRICES ') && RCS_FIXED_TAX_RATE > 0 )  $sprice += ($sprice * RCS_FIXED_TAX_RATE / 100);

	  // BEGIN OF ATTRIBUTE DB CODE
	  $prodAttribs = ''; // DO NOT DELETE

	  if (_cst_bool('RCS_SHOW_ATTRIBUTES')) {
	      $attribquery = $DB->query("select  cba.products_id pid,
				  po.products_options_name poname,
				  pov.products_options_values_name povname
				  from    " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " cba,
				  " . TABLE_PRODUCTS_OPTIONS . " po,
				  " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov,
				  " . TABLE_LANGUAGES . " l
				  where   cba.products_id ='" . $in_cart['products_id'] . "' and
				  cba.customers_id = " . $curcus . " and
				  po.products_options_id = cba.products_options_id and
				  pov.products_options_values_id = cba.products_options_value_id and
				  po.language_id = " . (int)$languages_id . " and
				  pov.language_id = " . (int)$languages_id
				  );
	      $hasAttributes = false;

	      if ($attribquery->__get('numRows')) {
		$hasAttributes = true;
		$prodAttribs = '<br />';

		while ($attribrecs = $attribquery->fetchAssoc())
		  $prodAttribs .= '<small><i> - ' . $attribrecs['poname'] . ' ' . $attribrecs['povname'] . '</i></small><br />';
	      }
	  }

	  // END OF ATTRIBUTE DB CODE
	  $detail['TOT_HT'] 	= $tprice + ($in_cart['qty'] * $sprice);
	  $detail['PUHT']  	= $price->format($sprice);
	  $detail['TOT_TTC']	= $price->format(($in_cart['qty'] * $sprice));
	  $detail['modele']	= __('model') . $inrec2['model'];
	  $detail['name']	= $inrec2['name'].$prodAttribs;
	  $detail['qty']	= $in_cart['qty'];
	  $detail['pID']	= $in_cart['products_id'];

	}
      if(isset(self::$list[$in_cart['customers_id']]['detail_cart'])) $in_cart['detail_cart']=self::$list[$in_cart['customers_id']]['detail_cart'];
      $in_cart['detail_cart'][]= $detail;
      if(isset(self::$list[$in_cart['customers_id']]['total_cart'])) $in_cart['total_cart'] = self::$list[$in_cart['customers_id']]['total_cart'] + (float)$detail['TOT_TTC'];
      else $in_cart['total_cart']=(float)$detail['TOT_TTC'];

      self::$list[$in_cart['customers_id']]=$in_cart;
      }

    $li=$res=array();
    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k=>$v) $li[$k]=(isset($item[$k]) && !empty($item[$k]))? $item[$k] : '&nbsp;';
      $li['total']=self::get_item_cart($item,$item['detail_cart']);
      $li['status']=$item['status'];
      $li['action']=self::get_item_action($item);
      $res[]=$li;
    }
// print_r($res);
    if(count($res)==0) return array(array('base'=>'&nbsp;','date'=>'&nbsp;','customer'=>'&nbsp;','email'=>'&nbsp;','total'=>'&nbsp;','status'=>'&nbsp;','action'=>'&nbsp;'));
    return $res;
  }


/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }
}

?>