<?php
/**
  @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.0.9
  @date  09/07/10, 20:43
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class customer_and_coupon
  Recup liaison entre customer et coupon.

  TODO
    Purge des coupon deja consommé par le client
*/

class customer_and_coupon {

  /**
   LA liste des coupon dspo pour le customer
  */
  var $list_coupon;




  function customer_and_coupon($customer_id){
    global $page;
    $this->customer_id=(int)$customer_id;
    $this->list_coupon=array();
  }


  /**
  Construit objet list des customers associé à ce produits
  @param
  @a int id produit
  */
  function init(){
    global $page;

    //! ne fournis que les coupons non utilise et dont les dates corresponde, specifique au client en cours
//     $check_user_query = tep_db_query( $sql = 'SELECT dc.coupons_description, dc.coupons_discount_amount, dc2u.coupons_id  FROM '.TABLE_DISCOUNT_COUPONS.' dc, '.TABLE_DISCOUNT_COUPONS_TO_CUSTOMERS.' dc2u WHERE dc.coupons_id=dc2u.coupons_id and  dc2u.customers_id='.(int)$this->customer_id.' AND in_out=\'I\' AND ( coupons_date_start <= CURDATE() OR coupons_date_start IS NULL )  AND ( coupons_date_end >= CURDATE() OR coupons_date_end IS NULL ) AND  coupons_number_available < 1 ' );
    $check_user_query = tep_db_query( $sql = 'SELECT dc.coupons_description, dc.coupons_discount_amount, dc2u.coupons_id, dc.coupons_max_use   FROM '.TABLE_DISCOUNT_COUPONS.' dc, '.TABLE_DISCOUNT_COUPONS_TO_CUSTOMERS.' dc2u WHERE dc.coupons_id=dc2u.coupons_id and  dc2u.customers_id='.(int)$this->customer_id.' AND in_out=\'I\'  AND coupons_number_available >= 1 AND ( coupons_date_start <= NOW() OR ( coupons_date_start IS NULL OR  coupons_date_start = \'1000-01-01 00:00:00\' ) ) AND ( coupons_date_end >= NOW() OR ( coupons_date_end IS NULL OR  coupons_date_end = \'1000-01-01 00:00:00\' ) )' );

    if( tep_db_num_rows( $check_user_query ) > 0 )
      while($v = tep_db_fetch_array( $check_user_query ) ) {


       $check_use_query = tep_db_query($sql = "SELECT COUNT(*) AS cnt
                                              FROM ".TABLE_ORDERS." AS o
                                              INNER JOIN ".TABLE_DISCOUNT_COUPONS_TO_ORDERS." dc2o
                                                ON dc2o.orders_id=o.orders_id
                                                AND o.customers_id = '".(int)$this->customer_id."'
                                                AND dc2o.coupons_id='".tep_db_input( $v['coupons_id'] )."'");
      $use = tep_db_fetch_array( $check_use_query );
      //show error message if coupons_max_use is equal to the number of times this customer has used the code
      if( $v['coupons_max_use'] > $use['cnt'] )  $this->list_coupon[] = $v;
      }

    return $this->list_coupon;
  }



}

?>