public function processCancel($db, $message)
 {
     echo "processing cancel referral_order_bonus : " . PHP_EOL;
     //echo "processing cancel referral_order_bonus : " . PHP_EOL;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     if (Customer::getTotalDeliveredForCustomer($id_customer) == 0) {
         $customer = new Customer($id_customer);
         if (!$customer->id_referrer) {
             return;
         }
         $id_referrer = $customer->id_referrer;
         $reward = self::getReward($id_referrer, EVENT_ORDER_DELIVERED, self::$id_rule, $reference);
         if (!$reward) {
             return;
         }
         $points_removed = $reward['points_awarded'];
         if (self::rewardExistsForReference($id_referrer, $id_event, self::$id_rule, $reference)) {
             echo 'skipping processed reward' . PHP_EOL;
             return;
         }
         $order = new Order((int) $reference);
         $referred_customer = new Customer($order->id_customer);
         if ($points_removed) {
             VBRewards::removeRewardPoints($id_referrer, $id_event, self::$id_rule, $points_removed, "First order by a friend cancelled - " . $referred_customer->email, $reference, $date_add);
             VBRewards::removeRewardPoints($id_customer, $id_event, self::$id_rule, $points_removed, "First order points through referral cancelled - " . $referred_customer->email, $reference, $date_add);
         }
     }
 }
/**
 * @param unknown_type $message
 * @param Db $db
 * @return void|boolean
 */
function processMessage($message, $db)
{
    //$message = Tools::jsonDecode('{"id_event":5,"date_event":"2012-03-14 13:07:18","reference":"274","id_customer":"10687"}', true);
    //$message = Tools::jsonDecode($response->body->ReceiveMessageResult->Message->Body, true);
    $message = Tools::jsonDecode($message, true);
    $id_event = $message['id_event'];
    if ($id_event == ONLINE_ORDER) {
        VBRewards::addRewardPoints($message['id_customer'], $id_event, 0, 100, 'Online payment bonus - Order no ' . $message['reference'], $message['reference'], $message['date_event']);
        return;
    }
    if ($id_event == EVENT_REGISTRATION) {
        VBRewards::addRewardPoints($message['id_customer'], $id_event, 0, 50, 'Registration/Sign-up', $message['reference'], $message['date_event']);
        return;
    }
    if (isset($message['first_order']) && $message['first_order']) {
        VBRewards::addRewardPoints($message['id_customer'], $id_event, 7, 50, 'First Order Bonus - Order no ' . $message['reference'], $message['reference'], $message['date_event']);
        return;
    }
    if (isset($message['first_review']) && $message['first_review']) {
        VBRewards::addRewardPoints($message['id_customer'], $id_event, 9, 50, 'Product Review - First review bonus', $message['reference'], $message['date_event']);
        return;
    }
    $res = $db->ExecuteS("select le.id_event, le.name as 'event_name', r.id_rule, r.name as 'rule_name', re.execute_sequence\n\t\t\t\t\t\t\tfrom vb_rules r\n\t\t\t\t\t\t\tinner join vb_loyalty_rule_events re on (r.id_rule = re.id_rule)\n\t\t\t\t\t\t\tinner join vb_loyalty_events le on le.id_event = re.id_event\n\t\t\t\t\t\t\twhere le.id_event = " . $message['id_event'] . " order by le.id_event, re.execute_sequence");
    foreach ($res as $rule_row) {
        if ($rule_row['id_rule'] == 9 || $rule_row['id_rule'] == 7) {
            continue;
        }
        $rewards_rule = RewardRules::getRule($rule_row['rule_name']);
        $rewards_rule->init($db);
        $rewards_rule->processEvent($db, $message);
        echo PHP_EOL;
    }
    return false;
}
 public function processEvent($db, $message)
 {
     echo "processing order_feedback";
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = (int) $message['reference'];
     $order = new Order($reference);
     //this order feedback is not from the same customer who placed this order
     if ((int) $order->id_customer != (int) $id_customer) {
         return false;
     }
     $result = $db->getRow("select \n                                        count(*) as processed\n                                    from \n                                        vb_customer_rewards\n                                    where \n                                        reference = " . $reference . "\n                                        and id_customer = " . $id_customer . "\n                                        and id_event = " . EVENT_ORDER_FEEDBACK);
     //Feedback reward for this order is already processed
     if ((int) $result['processed'] === 1) {
         return false;
     }
     // only one entry per day ( for multiple order feedbacks also )
     $todayPoints = $this->getTodaysOrderFeedbackPoints($db, $id_customer);
     if ($todayPoints === 0) {
         VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$order_feedback_points, 'Order Feedback', $reference, $date_add);
         return true;
     }
     $todayRewardId = (int) $todayPoints['id_reward'];
     $todayTotalPoints = (int) $todayPoints['points_awarded'] + self::$order_feedback_points;
     $todayBalance = VBRewards::getCustomerPoints($id_customer) + self::$order_feedback_points;
     $db->Execute("  UPDATE\n                                vb_customer_rewards \n                            SET \n                                points_awarded = " . $todayTotalPoints . ", balance = " . $todayBalance . "\n                            WHERE \n                                id_reward = " . $todayRewardId);
     $db->Execute("  UPDATE \n                                vb_customer_reward_balance \n                            SET \n                                balance = " . $todayBalance . "\n                            WHERE \n                                id_customer = " . (int) $id_customer);
     return true;
 }
 public function processEvent($db, $message)
 {
     echo "processing facebook_page_unlike . " . self::$facebook_page_like_points . PHP_EOL;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     $result = $db->getRow(" select \n                                    count(*) as 'page_likes'\n                                from \n                                    vb_customer_rewards\n\t\t\t\twhere \n                                    id_customer = " . $id_customer . "\n                                    and id_event = " . EVENT_FACEBOOK_PAGE_LIKE);
     $page_likes = (int) $result['page_likes'];
     $result = $db->getRow(" select \n                                    count(*) as 'page_unlikes'\n                                from \n                                    vb_customer_rewards\n\t\t\t\twhere \n                                    id_customer = " . $id_customer . "\n                                    and id_event = " . EVENT_FACEBOOK_PAGE_UNLIKE);
     $page_unlikes = (int) $result['page_unlikes'];
     if ($page_likes - $page_unlikes === 1) {
         VBRewards::removeRewardPoints($id_customer, $id_event, self::$id_rule, self::$facebook_page_like_points, 'Facebook Unlike of Indusdiva Page', $reference, $date_add);
     }
     return true;
 }
 public function preProcess()
 {
     parent::preProcess();
     $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
     $res = $db->ExecuteS("SELECT \n\t\t\t\t\t\t\tdescription, \n\t\t\t\t\t\t\treference, \n\t\t\t\t\t\t\tdate_add, \n\t\t\t\t\t\t\tpoints_awarded, \n\t\t\t\t\t\t\tcoalesce(points_deducted, '-') as `points_deducted`, \n\t\t\t\t\t\t\tbalance FROM vb_customer_rewards WHERE id_customer = " . self::$cookie->id_customer . "\n\t\t\t\t\t\t\torder by id_reward desc");
     self::$smarty->assign('vbpoints', $res);
     self::$smarty->assign('balance_points', VBRewards::getCustomerPoints(self::$cookie->id_customer));
     self::$smarty->assign('redeemed_points', VBRewards::getCustomerPointsRedeemed(self::$cookie->id_customer));
     self::$smarty->assign('earned_points', VBRewards::getCustomerPointsEarned(self::$cookie->id_customer));
     self::$smarty->assign('reviews_approved', Customer::getTotalApprovedReviews(self::$cookie->id_customer));
     self::$smarty->assign('social_points', $this->getSocialPoints());
     $referrals = Customer::getCustomerReferrals(self::$cookie->id_customer);
     if ($referrals) {
         self::$smarty->assign('total_referred', count($referrals));
     }
 }
 public function processEvent($db, $message)
 {
     echo "processing wishlist_product_facebook_share";
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = (int) $message['reference'];
     $result = $db->getRow("select \n                                        count(*) as processed\n                                    from \n                                        vb_customer_rewards\n                                    where \n                                        reference = " . $reference . "\n                                        and id_customer = " . $id_customer . "\n                                        and id_event = " . EVENT_WISHLIST_PRODUCT_FACEBOOK_SHARE);
     //Feedback reward for this order is already processed
     if ((int) $result['processed'] === 1) {
         return false;
     }
     $result = $db->getRow("select \n                                        sum(points_awarded) points_awarded, sum(points_deducted) points_deducted\n                                    from \n                                        vb_customer_rewards\n                                    where \n                                        id_customer = " . $id_customer . "\n                                        and id_event = " . EVENT_WISHLIST_PRODUCT_FACEBOOK_SHARE);
     $points_awarded = (int) $result['points_awarded'];
     $points_deducted = (int) $result['points_deducted'];
     $total_points_awarded = $points_awarded - $points_deducted;
     //limit for points awarded is reached
     if ($total_points_awarded >= 25 * self::$wishlist_product_facebook_share_points) {
         return false;
     }
     /*$todayPoints = $this->getTodaysWLSharePoints($db, $id_customer);
     
             if (!$todayPoints) {
                 VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$wishlist_product_facebook_share_points, 'Wishlist Product Share', $reference, $date_add);
                 return true;
             }
     
             $todayRewardId = (int) $todayPoints['id_reward'];
             $todayTotalPoints = (int) $todayPoints['points_awarded'] + self::$wishlist_product_facebook_share_points;
             $todayBalance = VBRewards::getCustomerPoints($id_customer) + self::$wishlist_product_facebook_share_points;
     
             $db->Execute(
                     "UPDATE vb_customer_rewards 
     						SET points_awarded = " . $todayTotalPoints . ", 
     						balance = " . $todayBalance . "
     						WHERE id_reward = " . $todayRewardId);
     
             $db->Execute("UPDATE vb_customer_reward_balance 
     						SET balance = " . $todayBalance . "
     						WHERE id_customer = " . (int) $id_customer);
     
                                                    
              
              */
     VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$wishlist_product_facebook_share_points, 'Wishlist Product Share', $reference, $date_add);
     return true;
 }
 public function preProcess()
 {
     global $isVirtualCart, $orderTotal;
     parent::preProcess();
     /* If some products have disappear */
     if (!self::$cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your shopping bag is no longer available for this quantity, please remove it to proceed.');
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) self::$cart->id_currency);
     $orderTotal = self::$cart->getOrderTotal();
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if (self::$cart->getOrderTotal(false) < $minimalPurchase && $this->step != -1) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('A minimum purchase total of') . ' ' . Tools::displayPrice($minimalPurchase, $currency) . ' ' . Tools::displayError('is required in order to validate your order.');
     }
     if (!self::$cookie->isLogged(true) and in_array($this->step, array(1, 2, 3))) {
         Tools::redirect('authentication.php?back=' . urlencode('order.php?step=' . $this->step));
     }
     if ($this->nbProducts) {
         self::$smarty->assign('virtual_cart', $isVirtualCart);
     }
     $this->_addAddress($this->step);
     if (self::$cookie->isLogged(true)) {
         $reward_points = VBRewards::getCustomerPoints(self::$cookie->id_customer);
         $redemption_status = VBRewards::checkPointsValidity(self::$cookie->id_customer, 0, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS));
         self::$smarty->assign('can_redeem_points', 1);
         self::$smarty->assign("redemption_status", $redemption_status);
         if ($redemption_status === CANNOT_REDEEM_COINS) {
             self::$smarty->assign('can_redeem_points', 0);
         } else {
             if ($redemption_status === INSUFFICIENT_VALID_ORDERS) {
                 self::$smarty->assign('redemption_status_message', 'Coins can be redeemed from second purchase onwards.');
             } else {
                 if ($redemption_status === MIN_CRITERIA_NOT_MET) {
                     self::$smarty->assign('redemption_status_message', 'Order value should be more than 100 USD to redeem coins');
                 }
             }
         }
         self::$smarty->assign('redeem_points', (int) self::$cart->getPoints());
         self::$smarty->assign('balance_points', $reward_points);
         if ($reward_points - (int) self::$cart->getPoints() > 0) {
             self::$smarty->assign('balance_cash', (int) self::$cart->getPointsDiscounts($reward_points - (int) self::$cart->getPoints()));
         }
     }
 }
 public function processCancel($db, $message)
 {
     return true;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     $reward = self::getReward($id_customer, EVENT_ORDER_DELIVERED, self::$id_rule, $reference);
     if (!$reward) {
         return;
     }
     $points_removed = $reward['points_awarded'];
     VBRewards::removeRewardPoints($id_customer, $id_event, self::$id_rule, $points_removed, 'Order cancelled - Order no ' . $reference, $reference, $date_add);
 }
 public function processCancel($db, $message)
 {
     echo "processing cancel first_order_bonus : " . PHP_EOL;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     $reward = self::getReward($id_customer, EVENT_ORDER_DELIVERED, self::$id_rule, $reference);
     if (!$reward) {
         return;
     }
     $points_removed = $reward['points_awarded'];
     VBRewards::removeRewardPoints($id_customer, $id_event, self::$id_rule, $points_removed, 'First Order Cancellation - Bonus coins reverted', $reference, $date_add);
 }
 public function processEvent($db, $message)
 {
     echo "processing facebook_unlike : " . self::$facebook_like_points;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     $todayPoints = $this->getTodaysFacebookPoints($db, $id_customer);
     if (!$todayPoints) {
         VBRewards::removeRewardPoints($id_customer, $id_event, self::$id_rule, self::$facebook_like_points, 'Facebook Unlike', $reference, $date_add);
         return;
     }
     $todayRewardId = (int) $todayPoints['id_reward'];
     $todayTotalPoints = (int) $todayPoints['points_deducted'] + self::$facebook_like_points;
     $todayBalance = VBRewards::getCustomerPoints($id_customer) - self::$facebook_like_points;
     $db->Execute("UPDATE vb_customer_rewards \n\t\t\t\t\t\tSET points_deducted = " . $todayTotalPoints . ", \n\t\t\t\t\t\tbalance = " . $todayBalance . "\n\t\t\t\t\t\tWHERE id_reward = " . $todayRewardId);
     $db->Execute("UPDATE vb_customer_reward_balance \n\t\t\t\t\t\tSET balance = " . $todayBalance . "\n\t\t\t\t\t\tWHERE id_customer = " . $id_customer);
 }
 public function processEvent($db, $message)
 {
     return true;
     echo "processing first_approved_review_bonus : ";
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     //get the number of approved reviews
     $result = Db::getInstance()->getRow("select count(*) as 'total_approved' from ps_product_comment where validate = 1 and id_customer = " . $id_customer);
     if ($result['total_approved'] == 1) {
         $points_added = self::$first_review_bonus;
         VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, $points_added, 'Product Review - First review bonus', $reference, $date_add);
     }
 }
 public function processEvent($db, $message)
 {
     echo "processing product_review_approved : " . self::$product_review_points;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     /*
                     if($this->getTotalReviewPoints($db, $id_customer) > 2500)
         return;
     */
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     $points_added = self::$product_review_points;
     $product_name = $this->getProductName($db, (int) $reference);
     VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, $points_added, 'Product Review - ' . $product_name, $reference, $date_add);
 }
 public function processEvent($db, $message)
 {
     echo "processing write_testimonial";
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = (int) $message['reference'];
     // only one entry per day ( for multiple order feedbacks also )
     $todayPoints = $this->getTodaysTestimonialPoints($db, $id_customer);
     if (!$todayPoints) {
         VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$write_testimonial_points, 'For Writing Testimonial', $reference, $date_add);
         return true;
     }
     $todayRewardId = (int) $todayPoints['id_reward'];
     $todayTotalPoints = (int) $todayPoints['points_awarded'] + self::$write_testimonial_points;
     $todayBalance = VBRewards::getCustomerPoints($id_customer) + self::$write_testimonial_points;
     $db->Execute("  UPDATE\n                                vb_customer_rewards \n                            SET \n                                points_awarded = " . $todayTotalPoints . ", balance = " . $todayBalance . "\n                            WHERE \n                                id_reward = " . $todayRewardId);
     $db->Execute("  UPDATE \n                                vb_customer_reward_balance \n                            SET \n                                balance = " . $todayBalance . "\n                            WHERE \n                                id_customer = " . (int) $id_customer);
     return true;
 }
 public function processEvent($db, $message)
 {
     echo "processing order_facebook_share";
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = (int) $message['reference'];
     $order = new Order($reference);
     //this order facebook share is not from the same customer who placed this order
     if ((int) $order->id_customer != (int) $id_customer) {
         return false;
     }
     $result = $db->getRow("select \n                                        count(*) as processed\n                                    from \n                                        vb_customer_rewards\n                                    where \n                                        reference = " . $reference . "\n                                        and id_customer = " . $id_customer . "\n                                        and id_event = " . EVENT_ORDER_FACEBOOK_SHARE);
     //Feedback reward for this order is already processed
     if ((int) $result['processed'] === 1) {
         return false;
     }
     VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$order_facebook_share_points, "Share Order Products on Facebook (Order - {$reference})", $reference, $date_add);
     return true;
 }
 public function processEvent($db, $message)
 {
     echo "processing google_plus_click : " . self::$google_plus_click_points;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     $result = $db->getRow("select sum(points_awarded) as 'total_points'\n\t\t\t\t\t\t\t\tfrom vb_customer_rewards\n\t\t\t\t\t\t\t\twhere id_customer = " . $id_customer . "\n\t\t\t\t\t\t\t\tand id_event = " . EVENT_GOOGLE_LIKE);
     if (!$result || $result['total_points'] == 0) {
         VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$google_plus_click_points, 'Google Plus Share', $reference, $date_add);
         return true;
     } else {
         $points_awarded = (int) $result['total_points'];
     }
     $result = $db->getRow("select sum(points_deducted) as 'total_points'\n\t\t\t\t\t\t\t\tfrom vb_customer_rewards\n\t\t\t\t\t\t\t\twhere id_customer = " . $id_customer . "\n\t\t\t\t\t\t\t\tand id_event = " . EVENT_GOOGLE_UNLIKE);
     if (!$result['total_points'] || $result['total_points'] == 0) {
         $points_deducted = 0;
     } else {
         $points_deducted = (int) $result['total_points'];
     }
     if ($points_awarded - $points_deducted >= 25 * self::$google_plus_click_points) {
         echo 'total points limit reached';
         return;
     }
     $todayPoints = $this->getTodaysGPlusPoints($db, $id_customer);
     if (!$todayPoints) {
         VBRewards::addRewardPoints($id_customer, $id_event, self::$id_rule, self::$google_plus_click_points, 'Google Plus Share', $reference, $date_add);
         return true;
     }
     $todayRewardId = (int) $todayPoints['id_reward'];
     $todayTotalPoints = (int) $todayPoints['points_awarded'] + self::$google_plus_click_points;
     $todayBalance = VBRewards::getCustomerPoints($id_customer) + self::$google_plus_click_points;
     $db->Execute("UPDATE vb_customer_rewards \n\t\t\t\t\t\tSET points_awarded = " . $todayTotalPoints . ", \n\t\t\t\t\t\tbalance = " . $todayBalance . "\n\t\t\t\t\t\tWHERE id_reward = " . $todayRewardId);
     $db->Execute("UPDATE vb_customer_reward_balance \n\t\t\t\t\t\tSET balance = " . $todayBalance . "\n\t\t\t\t\t\tWHERE id_customer = " . (int) $id_customer);
     return true;
 }
    public function viewcustomer()
    {
        global $currentIndex, $cookie, $link;
        $irow = 0;
        $configurations = Configuration::getMultiple(array('PS_LANG_DEFAULT', 'PS_CURRENCY_DEFAULT'));
        $defaultLanguage = (int) $configurations['PS_LANG_DEFAULT'];
        $defaultCurrency = (int) $configurations['PS_CURRENCY_DEFAULT'];
        if (!($customer = $this->loadObject())) {
            return;
        }
        $customerStats = $customer->getStats();
        $addresses = $customer->getAddresses($defaultLanguage);
        $products = $customer->getBoughtProducts();
        $discounts = Discount::getCustomerDiscounts($defaultLanguage, (int) $customer->id, false, false);
        $orders = Order::getCustomerOrders((int) $customer->id, true);
        $carts = Cart::getCustomerCarts((int) $customer->id);
        $groups = $customer->getGroups();
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $referrers = Referrer::getReferrers((int) $customer->id);
        if ($totalCustomer = Db::getInstance()->getValue('SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . $customer->id . ' AND valid = 1')) {
            Db::getInstance()->getValue('SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 GROUP BY id_customer HAVING SUM(total_paid_real) > ' . $totalCustomer);
            $countBetterCustomers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $countBetterCustomers = '-';
        }
        echo '
		<fieldset style="width:400px;float: left"><div style="float: right"><a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a></div>
			<span style="font-weight: bold; font-size: 14px;">' . $customer->firstname . ' ' . $customer->lastname . '</span>
			<img src="../img/admin/' . ($customer->id_gender == 2 ? 'female' : ($customer->id_gender == 1 ? 'male' : 'unknown')) . '.gif" style="margin-bottom: 5px" /><br />
			<a href="mailto:' . $customer->email . '" style="text-decoration: underline; color: blue">' . $customer->email . '</a><br /><br />
			' . $this->l('ID:') . ' ' . sprintf('%06d', $customer->id) . '<br />
			' . $this->l('Registration date:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Last visit:') . ' ' . ($customerStats['last_visit'] ? Tools::displayDate($customerStats['last_visit'], (int) $cookie->id_lang, true) : $this->l('never')) . '<br />
			' . ($countBetterCustomers != '-' ? $this->l('Rank: #') . ' ' . (int) $countBetterCustomers . '<br />' : '') . '
		</fieldset>
		<fieldset style="width:300px;float:left;margin-left:50px">
			<div style="float: right">
				<a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a>
			</div>
			' . $this->l('Newsletter:') . ' ' . ($customer->newsletter ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Opt-in:') . ' ' . ($customer->optin ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Age:') . ' ' . $customerStats['age'] . ' ' . (!empty($customer->birthday['age']) ? '(' . Tools::displayDate($customer->birthday, (int) $cookie->id_lang) . ')' : $this->l('unknown')) . '<br /><br />
			' . $this->l('Last update:') . ' ' . Tools::displayDate($customer->date_upd, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Status:') . ' ' . ($customer->active ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />');
        if ($customer->isGuest()) {
            echo '
			<div>
			' . $this->l('This customer is registered as') . ' <b>' . $this->l('guest') . '</b>';
            if (!Customer::customerExists($customer->email)) {
                echo '
					<form method="POST" action="index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&token=' . Tools::getAdminTokenLite('AdminCustomers') . '">
						<input type="hidden" name="id_lang" value="' . (int) (sizeof($orders) ? $orders[0]['id_lang'] : Configuration::get('PS_LANG_DEFAULT')) . '" />
						<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="' . $this->l('Transform to customer') . '" /></p>
						' . $this->l('This feature generates a random password and sends an e-mail to the customer
					</form>');
            } else {
                echo '</div><div><b style="color:red;">' . $this->l('A registered customer account exists with the same email address') . '</b>';
            }
            echo '
			</div>
			';
        }
        echo '
		</fieldset>
		<div class="clear">&nbsp;</div>';
        echo '<fieldset style="height:190px"><legend><img src="../img/admin/cms.gif" /> ' . $this->l('Add a private note') . '</legend>
			<p>' . $this->l('This note will be displayed to all the employees but not to the customer.') . '</p>
			<form action="ajax.php" method="post" onsubmit="saveCustomerNote();return false;" id="customer_note">
				<textarea name="note" id="noteContent" style="width:600px;height:100px" onkeydown="$(\'#submitCustomerNote\').removeAttr(\'disabled\');">' . Tools::htmlentitiesUTF8($customer->note) . '</textarea><br />
				<input type="submit" id="submitCustomerNote" class="button" value="' . $this->l('   Save   ') . '" style="float:left;margin-top:5px" disabled="disabled" />
				<span id="note_feedback" style="float:left;margin:10px 0 0 10px"></span>
			</form>
		</fieldset>
		<div class="clear">&nbsp;</div>
		<script type="text/javascript">
			function saveCustomerNote()
			{
				$("#note_feedback").html("<img src=\\"../img/loader.gif\\" />").show();
				var noteContent = $("#noteContent").val();
				$.post("ajax.php", {submitCustomerNote:1,id_customer:' . (int) $customer->id . ',note:noteContent}, function (r) {
					$("#note_feedback").html("").hide();
					if (r == "ok")
					{
						$("#note_feedback").html("<b style=\\"color:green\\">' . addslashes($this->l('Your note has been saved')) . '</b>").fadeIn(400);
						$("#submitCustomerNote").attr("disabled", "disabled");
					}
					else if (r == "error:validation")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: your note is not valid')) . '</b>").fadeIn(400);
					else if (r == "error:update")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: cannot save your note')) . '</b>").fadeIn(400);
					$("#note_feedback").fadeOut(3000);
				});
			}
		</script>';
        echo '<h2>' . $this->l('Messages') . ' (' . sizeof($messages) . ')</h2>';
        if (sizeof($messages)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Status') . '</th>
					<th class="center">' . $this->l('Message') . '</th>
					<th class="center">' . $this->l('Sent on') . '</th>
				</tr>';
            foreach ($messages as $message) {
                echo '<tr>
					<td>' . $message['status'] . '</td>
					<td><a href="index.php?tab=AdminCustomerThreads&id_customer_thread=' . (int) $message['id_customer_thread'] . '&viewcustomer_thread&token=' . Tools::getAdminTokenLite('AdminCustomerThreads') . '">' . substr(strip_tags(html_entity_decode($message['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75) . '...</a></td>
					<td>' . Tools::displayDate($message['date_add'], (int) $cookie->id_lang, true) . '</td>
				</tr>';
            }
            echo '</table>
			<div class="clear">&nbsp;</div>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has never contacted you.');
        }
        // display hook specified to this page : AdminCustomers
        if (($hook = Module::hookExec('adminCustomers', array('id_customer' => $customer->id))) !== false) {
            echo '<div>' . $hook . '</div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Groups') . ' (' . sizeof($groups) . ')</h2>';
        if ($groups and sizeof($groups)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenGroups = Tools::getAdminToken('AdminGroups' . (int) Tab::getIdFromClassName('AdminGroups') . (int) $cookie->id_employee);
            foreach ($groups as $group) {
                $objGroup = new Group($group);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '\'">
					<td class="center">' . $objGroup->id . '</td>
					<td>' . $objGroup->name[$defaultLanguage] . '</td>
					<td align="center"><a href="?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Orders') . ' (' . sizeof($orders) . ')</h2>';
        if ($orders and sizeof($orders)) {
            $totalOK = 0;
            $ordersOK = array();
            $ordersKO = array();
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($orders as $order) {
                if ($order['valid']) {
                    $ordersOK[] = $order;
                    $totalOK += $order['total_paid_real'];
                } else {
                    $ordersKO[] = $order;
                }
            }
            $orderHead = '
			<table cellspacing="0" cellpadding="0" class="table float">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Products') . '</th>
					<th class="center">' . $this->l('Total paid') . '</th>
					<th class="center">' . $this->l('Payment') . '</th>
					<th class="center">' . $this->l('State') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $orderFoot = '</table>';
            if ($countOK = sizeof($ordersOK)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:green;font-weight:700">' . $this->l('Valid orders:') . ' ' . $countOK . ' ' . $this->l('for') . ' ' . Tools::displayPrice($totalOK, new Currency($defaultCurrency)) . '</h3>' . $orderHead;
                foreach ($ordersOK as $order) {
                    echo '<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
						<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div>';
            }
            if ($countKO = sizeof($ordersKO)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:red;font-weight:700">' . $this->l('Invalid orders:') . ' ' . $countKO . '</h3>' . $orderHead;
                foreach ($ordersKO as $order) {
                    echo '
						<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
							<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div><div class="clear">&nbsp;</div>';
            }
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not placed any orders yet');
        }
        if ($products and sizeof($products)) {
            echo '<div class="clear">&nbsp;</div>
			<h2>' . $this->l('Products') . ' (' . sizeof($products) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Quantity') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($products as $product) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
					<td>' . Tools::displayDate($product['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td>' . $product['product_name'] . '</td>
					<td align="right">' . $product['product_quantity'] . '</td>
					<td align="center"><a href="?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Addresses') . ' (' . sizeof($addresses) . ')</h2>';
        if (sizeof($addresses)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('Company') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Address') . '</th>
					<th>' . $this->l('Country') . '</th>
					<th>' . $this->l('Phone number(s)') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenAddresses = Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee);
            foreach ($addresses as $address) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td>' . ($address['company'] ? $address['company'] : '--') . '</td>
					<td>' . $address['firstname'] . ' ' . $address['lastname'] . '</td>
					<td>' . $address['address1'] . ($address['address2'] ? ' ' . $address['address2'] : '') . ' ' . $address['postcode'] . ' ' . $address['city'] . '</td>
					<td>' . $address['country'] . '</td>
					<td>' . ($address['phone'] ? $address['phone'] . ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '') : ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '--')) . '</td>
					<td align="center">
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&addaddress&token=' . $tokenAddresses . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&deleteaddress&token=' . $tokenAddresses . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not registered any addresses yet') . '.';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Discounts') . ' (' . sizeof($discounts) . ')</h2>';
        if (sizeof($discounts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('ID') . '</th>
					<th>' . $this->l('Code') . '</th>
					<th>' . $this->l('Type') . '</th>
					<th>' . $this->l('Value') . '</th>
					<th>' . $this->l('Qty available') . '</th>
					<th>' . $this->l('Status') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenDiscounts = Tools::getAdminToken('AdminDiscounts' . (int) Tab::getIdFromClassName('AdminDiscounts') . (int) $cookie->id_employee);
            foreach ($discounts as $discount) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td align="center">' . $discount['id_discount'] . '</td>
					<td>' . $discount['name'] . '</td>
					<td>' . $discount['type'] . '</td>
					<td align="right">' . $discount['value'] . '</td>
					<td align="center">' . $discount['quantity_for_user'] . '</td>
					<td align="center"><img src="../img/admin/' . ($discount['active'] ? 'enabled.gif' : 'disabled.gif') . '" alt="' . $this->l('Status') . '" title="' . $this->l('Status') . '" /></td>
					<td align="center">
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&adddiscount&token=' . $tokenDiscounts . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&deletediscount&token=' . $tokenDiscounts . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has no discount vouchers') . '.';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<div style="float:left">
		<h2>' . $this->l('Carts') . ' (' . sizeof($carts) . ')</h2>';
        if ($carts and sizeof($carts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Total') . '</th>
					<th class="center">' . $this->l('Carrier') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenCarts = Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $cookie->id_employee);
            foreach ($carts as $cart) {
                $cartI = new Cart((int) $cart['id_cart']);
                $summary = $cartI->getSummaryDetails();
                $currency = new Currency((int) $cart['id_currency']);
                $carrier = new Carrier((int) $cart['id_carrier']);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '\'">
					<td class="center">' . sprintf('%06d', $cart['id_cart']) . '</td>
					<td>' . Tools::displayDate($cart['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td align="right">' . Tools::displayPrice($summary['total_price'], $currency) . '</td>
					<td>' . $carrier->name . '</td>
					<td align="center"><a href="index.php?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $this->l('No cart available') . '.';
        }
        echo '</div>';
        $interested = Db::getInstance()->ExecuteS('SELECT DISTINCT id_product FROM ' . _DB_PREFIX_ . 'cart_product cp INNER JOIN ' . _DB_PREFIX_ . 'cart c on c.id_cart = cp.id_cart WHERE c.id_customer = ' . (int) $customer->id . ' AND cp.id_product NOT IN (
		SELECT product_id FROM ' . _DB_PREFIX_ . 'orders o inner join ' . _DB_PREFIX_ . 'order_detail od ON o.id_order = od.id_order WHERE o.valid = 1 AND o.id_customer = ' . (int) $customer->id . ')');
        if (count($interested)) {
            echo '<div style="float:left;margin-left:20px">
			<h2>' . $this->l('Products') . ' (' . count($interested) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">';
            foreach ($interested as $p) {
                $product = new Product((int) $p['id_product'], false, $cookie->id_lang);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '\'">
					<td>' . (int) $product->id . '</td>
					<td>' . Tools::htmlentitiesUTF8($product->name) . '</td>
					<td align="center"><a href="' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '</table></div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        /* Last connections */
        $connections = $customer->getLastConnections();
        if (sizeof($connections)) {
            echo '<h2>' . $this->l('Last connections') . '</h2>
            <table cellspacing="0" cellpadding="0" class="table">
                <tr>
                    <th style="width: 200px">' . $this->l('Date') . '</th>
                    <th style="width: 100px">' . $this->l('Pages viewed') . '</th>
                    <th style="width: 100px">' . $this->l('Total time') . '</th>
                    <th style="width: 100px">' . $this->l('Origin') . '</th>
                    <th style="width: 100px">' . $this->l('IP Address') . '</th>
                </tr>';
            foreach ($connections as $connection) {
                echo '<tr>
                        <td>' . Tools::displayDate($connection['date_add'], (int) $cookie->id_lang, true) . '</td>
                        <td>' . (int) $connection['pages'] . '</td>
                        <td>' . $connection['time'] . '</td>
                        <td>' . ($connection['http_referer'] ? preg_replace('/^www./', '', parse_url($connection['http_referer'], PHP_URL_HOST)) : $this->l('Direct link')) . '</td>
                        <td>' . $connection['ipaddress'] . '</td>
                    </tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        if (sizeof($referrers)) {
            echo '<h2>' . $this->l('Referrers') . '</h2>
            <table cellspacing="0" cellpadding="0" class="table">
                <tr>
                    <th style="width: 200px">' . $this->l('Date') . '</th>
                    <th style="width: 200px">' . $this->l('Name') . '</th>
                </tr>';
            foreach ($referrers as $referrer) {
                echo '<tr>
                        <td>' . Tools::displayDate($referrer['date_add'], (int) $cookie->id_lang, true) . '</td>
                        <td>' . $referrer['name'] . '</td>
                    </tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        echo '<a href="' . $currentIndex . '&token=' . $this->token . '"><img src="../img/admin/arrow2.gif" /> ' . $this->l('Back to customer list') . '</a><br />';
        global $smarty;
        $smarty->assign('balance_points', VBRewards::getCustomerPoints($customer->id));
        $smarty->assign('redeemed_points', VBRewards::getCustomerPointsRedeemed($customer->id));
        $referrals = Customer::getCustomerReferrals($customer->id);
        if ($referrals) {
            $smarty->assign('total_referred', count($referrals));
        } else {
            $smarty->assign('total_referred', 0);
        }
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $res = $db->ExecuteS("SELECT\n                description,\n                reference,\n                date_add,\n                points_awarded,\n                coalesce(points_deducted, '-') as `points_deducted`,\n                balance FROM vb_customer_rewards WHERE id_customer = " . $customer->id . "\n                order by id_reward desc");
        $smarty->assign('vbpoints', $res);
        $smarty->display(_PS_THEME_DIR_ . 'admin/customer_points.tpl');
        //Customer's wishlist
        $wishlist_items = $db->ExecuteS("select \n            ps.name,\n            w.id_product, \n            p.reference,\n            w.date_add \n            from \n            ps_wishlist w \n            join ps_product_lang ps \n                on ps.id_product = w.id_product\n            join ps_product p\n                on p.id_product = w.id_product\n            where w.id_customer = {$customer->id} and ps.id_lang=1\n            order by w.date_add desc");
        $link = new Link();
        foreach ($wishlist_items as &$item) {
            $item["link"] = $link->getProductLink($item["id_product"]);
        }
        $smarty->assign('wishlist_items', $wishlist_items);
        $smarty->display(_PS_THEME_DIR_ . 'admin/customer_wishlist.tpl');
    }
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
    {
        global $cart, $link, $cookie;
        $id_payment_state = _PS_PS_NOT_PAID_;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) {
            if ($secure_key !== false and $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->id_address_delivery);
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_customization = $cart->getCartCustomizationCost();
            $order->total_donation = round($cookie->donation_amount);
            unset($cookie->donation_amount);
            if (strpos($order->payment, 'COD') === false) {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true));
            } else {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false));
                $order->total_cod = COD_CHARGE;
            }
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            $shippingdate = $cart->getExpectedShippingDate();
            $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            // Amount paid by customer is not the right one -> Status = payment error
            // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
            // if ($order->total_paid != $order->total_paid_real)
            // We use number_format in order to compare two string
            if (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) {
                $id_order_state = _PS_OS_ERROR_;
                $id_payment_state = _PS_PS_NOT_PAID_;
            } else {
                if (strpos($order->payment, 'COD') === false) {
                    $id_payment_state = _PS_PS_PAID_;
                }
            }
            //update payment status
            // Creating order
            if ($cart->OrderExists() == false) {
                $cart_value = $cart->getOrderTotal();
                if ($cart_value >= 1000) {
                    //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL))
                    //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE);
                }
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        if ($product['stock_quantity'] < 1) {
                            SolrSearch::updateProduct((int) $product['id_product']);
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $specificPrice = 0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . (double) Group::getReduction((int) $order->id_customer) . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 8) {
                                        $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />';
                                    } else {
                                        if ($text['index'] == 1) {
                                            $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />';
                                        } else {
                                            if ($text['index'] == 2) {
                                                $customizationText .= 'Stitched to measure blouse.' . '<br />';
                                            } else {
                                                if ($text['index'] == 3) {
                                                    $customizationText .= 'Stitched to measure in-skirt.' . '<br />';
                                                } else {
                                                    if ($text['index'] == 4) {
                                                        $customizationText .= 'Stitched to measure kurta.' . '<br />';
                                                    } else {
                                                        if ($text['index'] == 5) {
                                                            $customizationText .= 'Stitched to measure salwar.' . '<br />';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    //if giftcard, create voucher and send the mails now.
                    $categories = Product::getProductCategories($product['id_product']);
                    if (in_array(CAT_GIFTCARD, $categories)) {
                        $friendsName = '';
                        $friendsEmail = '';
                        $giftMessage = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 21) {
                                        $friendsName = $text['value'];
                                    } else {
                                        if ($text['index'] == 22) {
                                            $friendsEmail = $text['value'];
                                        } else {
                                            if ($text['index'] == 23) {
                                                $giftMessage = $text['value'];
                                            } else {
                                                if ($text['index'] == 25) {
                                                    $couponCode = $text['value'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //$couponCode = "GC" . Tools::rand_string(8);
                        // create discount
                        $languages = Language::getLanguages($order);
                        $voucher = new Discount();
                        $voucher->id_discount_type = 2;
                        foreach ($languages as $language) {
                            $voucher->description[$language['id_lang']] = $product['name'];
                        }
                        $voucher->value = (double) $unitPrice;
                        $voucher->name = $couponCode;
                        $voucher->id_currency = 2;
                        //USD
                        $voucher->quantity = 1;
                        $voucher->quantity_per_user = 1;
                        $voucher->cumulable = 1;
                        $voucher->cumulable_reduction = 1;
                        $voucher->minimal = 0;
                        $voucher->active = 1;
                        $voucher->cart_display = 0;
                        $now = time();
                        $voucher->date_from = date('Y-m-d H:i:s', $now);
                        $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365);
                        /* 365 days */
                        $voucher->add();
                        $productObj = new Product($product['id_product'], true, 1);
                        $idImage = $productObj->getCoverWs();
                        if ($idImage) {
                            $idImage = $productObj->id . '-' . $idImage;
                        } else {
                            $idImage = Language::getIsoById(1) . '-default';
                        }
                        $params = array();
                        $params['{voucher_code}'] = $voucher->name;
                        $params['{freinds_name}'] = $friendsName;
                        $params['{gift_message}'] = $giftMessage;
                        $params['{product_name}'] = $product['name'];
                        $params['{voucher_value}'] = $voucher->value;
                        $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location;
                        $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname;
                        $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card';
                        @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                        @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang);
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) and $outOfStock) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                //Payment status
                $paymentHistory = new OrderPaymentHistory();
                $paymentHistory->id_order = (int) $order->id;
                $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id);
                $paymentHistory->addState();
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                //Update tracking code for quantium
                if ($order->id_carrier == QUANTIUM) {
                    if (strpos($order->payment, 'COD') === false) {
                        $order->shipping_number = 'VBN' . $order->id;
                    } else {
                        $order->shipping_number = 'VBC' . $order->id;
                    }
                    $order->update();
                } else {
                    if ($order->id_carrier == SABEXPRESS) {
                        $db = Db::getInstance();
                        $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                        $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0");
                        $awb = $res['awb'];
                        $id = $res['id'];
                        $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                        $db->Execute('UNLOCK TABLES');
                        $order->shipping_number = $awb;
                        $order->update();
                    } else {
                        if ($order->id_carrier == AFL) {
                            $db = Db::getInstance();
                            $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                            $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0");
                            $awb = $res['awb'];
                            $id = $res['id'];
                            $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                            $db->Execute('UNLOCK TABLES');
                            $order->shipping_number = $awb;
                            $order->update();
                        }
                    }
                }
                // Send an e-mail to customer
                if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) {
                    //deduct reward points
                    $points_redeemed = $cart->getPoints();
                    if ($points_redeemed) {
                        VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    /*
                    if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0)
                    {
                        VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    */
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $shippingdate = new DateTime($order->expected_shipping_date);
                    $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if (Validate::isEmail($customer->email)) {
                        if ($id_order_state == _PS_OS_BANKWIRE_) {
                            Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        } else {
                            $data['payment'] = 'Online Payment';
                            Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        }
                    }
                    //Send SMS
                    //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com';
                    //Tools::sendSMS($delivery->phone_mobile, $smsText);
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }
 public function initFacebook()
 {
     global $smarty, $cookie, $cart;
     //echo str_replace('//','/',dirname(__FILE__).'/') .'facebook.php'; exi
     require_once str_replace('//', '/', dirname(__FILE__) . '/') . 'facebook.php';
     // Create our Application instance
     $this->facebook = new Facebook(array('appId' => FB_API_KEY, 'secret' => FB_SECRET, 'cookie' => true));
     //check if the user has logged in
     $fb_user = $this->facebook->getUser();
     // echo "<script>console.log("+$fb_user+")</script>";
     $userInfo = null;
     if ($fb_user) {
         try {
             // Proceed knowing you have a logged in user who's authenticated.
             $customer = new Customer();
             $customer = $customer->getByFacebookID($fb_user);
             if ($customer) {
                 $this->loginCustomer($customer);
                 if (Tools::getValue('fblogin') == 1) {
                     Tools::redirect('index.php');
                 } else {
                     return;
                 }
             }
             $userInfo = $this->facebook->api("/{$fb_user}");
         } catch (FacebookApiException $e) {
             $this->facebook->logout();
             $fb_user = null;
         }
     }
     $logoutUrl = $this->facebook->getLogoutUrl(array('next' => _PS_BASE_URL_ . __PS_BASE_URI__ . '?mylogout=1'));
     $smarty->assign('fblogout_url', $logoutUrl);
     // Login or logout url will be needed depending on current user state.
     if ($fb_user && $userInfo && $userInfo['email']) {
         //print_r($userInfo);print_r('<br/>');
         //dump fb data for this user first
         $this->dumpFacebookData($fb_user, $userInfo);
         //echo print_r($userInfo);exit;
         $userEmail = $userInfo['email'];
         if (Customer::customerExists($userEmail)) {
             //customer is registered and not logged in
             $customer = new Customer();
             // print_r($customer);
             // print_r('<br/>');
             $customer = $customer->getByEmail($userEmail);
             // print_r('<br/>will get customer here by email: '.$userEmail);
             // print_r($customer);
             // print_r('<br/>');
             //check if she is connected
             if (!$customer->fbid || $customer->fbid == '') {
                 $this->updateCustomerInfo($customer, $userInfo, $fb_user, false);
                 //print_r($customer);
                 $customer->update();
             }
             $this->loginCustomer($customer);
         } else {
             //new customer. create and add this customer and log her in
             $customer = new Customer();
             $this->updateCustomerInfo($customer, $userInfo, $fb_user, true);
             if (!$customer->add()) {
                 $this->errors[] = Tools::displayError('An error occurred while logging you in.');
             } else {
                 //award registration points
                 VBRewards::addRegistrationPoints($customer->id);
                 Tools::addCoupons($customer->id);
                 $cookie->new_reg = 1;
                 $cookie->write();
                 $this->loginCustomer($customer);
                 if ((int) self::$cookie->id_country === 110) {
                     $subject = Mail::l("Welcome to IndusDiva, INR 2500 has been credited to your account");
                     $amount = "INR 2500";
                 } else {
                     $subject = Mail::l("Welcome to IndusDiva, USD 100 has been credited to your account");
                     $amount = "USD 100";
                 }
                 if (!Mail::Send((int) $cookie->id_lang, 'account', $subject, array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd'), '{amount}' => $amount), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                     $this->errors[] = Tools::displayError('Cannot send email');
                 }
             }
         }
     } else {
         $redirectURL = _PS_BASE_URL_ . __PS_BASE_URI__;
         if (Tools::getValue('back')) {
             $redirectURL = $redirectURL . Tools::getValue('back');
         }
         $loginUrl = $this->facebook->getLoginUrl(array('scope' => 'email,user_location,user_birthday', 'redirect_uri' => $redirectURL));
         $smarty->assign('fblogin_url', $loginUrl);
         // echo "<script>alert('in')</script>";
     }
     if (Tools::getValue('fblogin') == 1) {
         // echo "<script>alert('in 1')</script>";
         Tools::redirect('index.php');
     }
 }
 public function processCancel($db, $message)
 {
     echo "processing cancel referral_order_bonus : " . PHP_EOL;
     $id_customer = $message['id_customer'];
     $id_event = $message['id_event'];
     $date_add = $message['date_event'];
     $reference = $message['reference'];
     if (self::rewardExistsForReference($id_customer, $id_event, self::$id_rule, $message['reference'])) {
         echo 'skipping processed reward' . PHP_EOL;
         return;
     }
     if (Customer::getTotalDeliveredForCustomer($id_customer) == 0) {
         $customer = new Customer($id_customer);
         if (!$customer->id_referrer) {
             return;
         }
         $id_referrer = $customer->id_referrer;
         $reward = self::getReward($id_referrer, EVENT_ORDER_DELIVERED, self::$id_rule, $reference);
         if (!$reward) {
             return;
         }
         //get total reffered order for this referrer
         $referrals = Customer::getCustomerReferrals($id_referrer);
         $countReferredOrders = 0;
         foreach ($referrals as $referral) {
             if ($referral['total_delivered'] > 0) {
                 $countReferredOrders++;
             }
         }
         $points_removed = 0;
         if ($countReferredOrders == 9) {
             $points_removed = self::$referral_order_bonus_10;
         } else {
             if ($countReferredOrders == 24) {
                 $points_removed = self::$referral_order_bonus_25;
             }
         }
         if (self::rewardExistsForReference($id_referrer, $id_event, self::$id_rule, $reference)) {
             echo 'skipping processed reward' . PHP_EOL;
             return;
         }
         $order = new Order((int) $reference);
         $referred_customer = new Customer($order->id_customer);
         if ($points_removed) {
             VBRewards::removeRewardPoints($id_referrer, $id_event, self::$id_rule, $points_removed, "First order by a friend cancelled - Bonus coins reverted -" . $referred_customer->email, $reference, $date_add);
         }
     }
 }
    public function addWithemail($autodate = true, $templateVars = false)
    {
        $lastOrderState = $this->getLastOrderState($this->id_order);
        if (!parent::add($autodate)) {
            return false;
        }
        $result = Db::getInstance()->getRow('
			SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`
			FROM `' . _DB_PREFIX_ . 'order_history` oh
				LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON oh.`id_order` = o.`id_order`
				LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON o.`id_customer` = c.`id_customer`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON oh.`id_order_state` = os.`id_order_state`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
			WHERE oh.`id_order_history` = ' . (int) $this->id . '
				AND os.`send_email` = 1');
        $order = new Order((int) $this->id_order);
        if (isset($result['template']) and Validate::isEmail($result['email'])) {
            $topic = $result['osname'];
            $data = array('{lastname}' => $result['lastname'], '{firstname}' => $result['firstname'], '{id_order}' => (int) $this->id_order);
            if ($templateVars) {
                $data = array_merge($data, $templateVars);
            }
            $data['{total_paid}'] = Tools::displayPrice((double) $order->total_paid, new Currency((int) $order->id_currency), false);
            $data['{order_name}'] = sprintf("#%06d", (int) $order->id);
            // An additional email is sent the first time a virtual item is validated
            if ($virtualProducts = $order->getVirtualProducts() and (!$lastOrderState or !$lastOrderState->logable) and $newOrderState = new OrderState($this->id_order_state, Configuration::get('PS_LANG_DEFAULT')) and $newOrderState->logable) {
                global $smarty;
                $assign = array();
                foreach ($virtualProducts as $key => $virtualProduct) {
                    $id_product_download = ProductDownload::getIdFromIdProduct($virtualProduct['product_id']);
                    $product_download = new ProductDownload($id_product_download);
                    $assign[$key]['name'] = $product_download->display_filename;
                    $dl_link = $product_download->getTextLink(false, $virtualProduct['download_hash']) . '&id_order=' . $order->id . '&secure_key=' . $order->secure_key;
                    $assign[$key]['link'] = $dl_link;
                    if ($virtualProduct['download_deadline'] != '0000-00-00 00:00:00') {
                        $assign[$key]['deadline'] = Tools::displayDate($virtualProduct['download_deadline'], $order->id_lang);
                    }
                    if ($product_download->nb_downloadable != 0) {
                        $assign[$key]['downloadable'] = $product_download->nb_downloadable;
                    }
                }
                $smarty->assign('virtualProducts', $assign);
                $smarty->assign('id_order', $order->id);
                $iso = Language::getIsoById((int) $order->id_lang);
                $links = $smarty->fetch(_PS_MAIL_DIR_ . $iso . '/download-product.tpl');
                $tmpArray = array('{nbProducts}' => count($virtualProducts), '{virtualProducts}' => $links);
                $data = array_merge($data, $tmpArray);
                global $_LANGMAIL;
                Mail::Send((int) $order->id_lang, 'download_product', Mail::l('Virtual product to download'), $data, $result['email'], $result['firstname'] . ' ' . $result['lastname']);
            }
            //custom subjects
            $emailSubject = $topic;
            $smsText = '';
            $delivery = new Address((int) $order->id_address_delivery);
            if ($this->id_order_state == _PS_OS_CANCELED_) {
                $emailSubject = 'Your order #' . $order->id . ' with IndusDiva.com has been cancelled';
                $smsText = 'Dear customer, your order #' . $order->id . ' with IndusDiva.com has been cancelled. www.indusdiva.com';
                Tools::sendSMS($delivery->phone_mobile, $smsText);
            } else {
                if ($this->id_order_state == _PS_OS_REFUND_) {
                    $emailSubject = 'Refund of your payment at IndusDiva.com';
                    $smsText = 'Dear customer, an amount of ' . Tools::displayPrice((double) $order->total_paid) . ' has been credited to your account against your order #' . $order->id . ' at IndusDiva.com. www.indusdiva.com';
                    Tools::sendSMS($delivery->phone_mobile, $smsText);
                }
            }
            if (Validate::isLoadedObject($order)) {
                Mail::Send((int) $order->id_lang, $result['template'], $emailSubject, $data, $result['email'], $result['firstname'] . ' ' . $result['lastname']);
            }
        }
        /* Send loyalty rules message */
        if ($this->id_order_state == _PS_OS_DELIVERED_) {
            $customer = new Customer($order->id_customer);
            $customer->total_delivered++;
            $customer->update();
            Tools::sendSQSRuleMessage(EVENT_ORDER_DELIVERED, $order->id, $order->id_customer, $this->date_add);
        } else {
            if ($this->id_order_state == _PS_OS_CANCELED_) {
                $order_cart = new Cart($order->id_cart);
                $points_redeemed = $order_cart->getPoints();
                if ($points_redeemed) {
                    VBRewards::addRewardPoints($order->id_customer, EVENT_ORDER_CANCELLED, 0, $points_redeemed, 'Redemption order cancelled - Order no ' . $order->id, $order->id, $order->date_add);
                }
                /*
                			//if online payment bonus awarded
                			$reward = rule_base::getReward($order->id_customer, ONLINE_ORDER, 0, $order->id);
                if($reward)
                {
                    $points_removed = $reward['points_awarded'];
                    VBRewards::removeRewardPoints($order->id_customer, EVENT_ORDER_CANCELLED, 0, $points_removed, 'Order Cancellation - Bonus coins reverted - Order no ' . $order->id, $order->id, $this->date_add);
                }
                */
                //if the order was delivered
                if ($lastOrderState->id == _PS_OS_DELIVERED_) {
                    $customer = new Customer($order->id_customer);
                    $customer->total_delivered--;
                    $customer->update();
                    Tools::sendSQSRuleMessage(EVENT_ORDER_CANCELLED, $order->id, $order->id_customer, $this->date_add);
                }
            } else {
                if ($this->id_order_state == _PS_OS_PREPARATION_) {
                    if ($lastOrderState->id == _PS_OS_CANCELED_) {
                        $order_cart = new Cart($order->id_cart);
                        $points_redeemed = $order_cart->getPoints();
                        if ($points_redeemed > 0) {
                            VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $points_redeemed, 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add);
                        }
                    }
                }
            }
        }
        return true;
    }
 public function preProcess()
 {
     global $isVirtualCart, $cookie;
     parent::preProcess();
     // Redirect to the good order process
     if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 0 and (strpos($_SERVER['PHP_SELF'], 'order.php') === false and strpos($_SERVER['PHP_SELF'], 'cart-summary-large.php') === false)) {
         Tools::redirect('order.php');
     }
     if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1 and strpos($_SERVER['PHP_SELF'], 'order-opc.php') === false) {
         if (isset($_GET['step']) and $_GET['step'] == 3) {
             Tools::redirect('order-opc.php?isPaymentStep=true');
         }
         Tools::redirect('order-opc.php');
     }
     if (Configuration::get('PS_CATALOG_MODE')) {
         $this->errors[] = Tools::displayError('This store has not accepted your new order.');
     }
     if (Tools::isSubmit('submitReorder') and $id_order = (int) Tools::getValue('id_order')) {
         $oldCart = new Cart(Order::getCartIdStatic((int) $id_order, (int) self::$cookie->id_customer));
         $duplication = $oldCart->duplicate();
         if (!$duplication or !Validate::isLoadedObject($duplication['cart'])) {
             $this->errors[] = Tools::displayError('Sorry, we cannot renew your order.');
         } elseif (!$duplication['success']) {
             $this->errors[] = Tools::displayError('Missing items - we are unable to renew your order');
         } else {
             self::$cookie->id_cart = $duplication['cart']->id;
             self::$cookie->write();
             if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                 Tools::redirect('order-opc.php');
             }
             Tools::redirect('order.php');
         }
     }
     if (Tools::isSubmit('submit_instructions')) {
         $instructions = Tools::getValue('special_instructions');
         self::$cart->gift_message = pSQL($instructions);
         self::$cart->update();
         Tools::redirect('order?step=3');
     }
     if ($this->nbProducts) {
         /* check discount validity */
         $cartDiscounts = self::$cart->getDiscounts();
         $discountInvalid = false;
         foreach ($cartDiscounts as $k => $cartDiscount) {
             if ($error = self::$cart->checkDiscountValidity(new Discount((int) $cartDiscount['id_discount']), $cartDiscounts, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING), self::$cart->getProducts())) {
                 self::$cart->deleteDiscount((int) $cartDiscount['id_discount']);
                 $discountInvalid = true;
             }
         }
         if ($discountInvalid) {
             Tools::redirect('order-opc.php');
         }
         if (Tools::getValue('redeem_points')) {
             $points = (int) Tools::getValue('redeem_points');
             if ($points < 1) {
                 self::$smarty->assign('redeem_points', $points);
                 $this->errors[] = Tools::displayError('You can redeem minimum of 1 coin in an order.');
             }
             $orderTotal = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
             $redemption_status = VBRewards::checkPointsValidity($cookie->id_customer, $points + self::$cart->getPoints(), $orderTotal);
             if ($redemption_status === CAN_REDEEM_COINS) {
                 self::$cart->addPoints($points);
                 self::$smarty->assign('redeem_points', (int) self::$cart->getPoints());
             } else {
                 if ($redemption_status === INSUFFICIENT_VALID_ORDERS) {
                     $this->errors[] = Tools::displayError('Coins can be redeemed from second purchase onwards.');
                 } else {
                     if ($redemption_status === MIN_CRITERIA_NOT_MET) {
                         $this->errors[] = Tools::displayError('Order value should be more than 100 USD to redeem coins');
                     }
                 }
             }
             $this->adjustPoints();
         } elseif (Tools::getValue('deletePoints')) {
             self::$cart->deletePoints();
         }
         if (Tools::isSubmit('submitAddDiscount') and Tools::getValue('discount_name')) {
             $discountName = Tools::getValue('discount_name');
             if (!Validate::isDiscountName($discountName)) {
                 $this->errors[] = Tools::displayError('Voucher name invalid.');
             } else {
                 $discount = new Discount((int) Discount::getIdByName($discountName));
                 if (Validate::isLoadedObject($discount)) {
                     if ($tmpError = self::$cart->checkDiscountValidity($discount, self::$cart->getDiscounts(), self::$cart->getOrderTotal(), self::$cart->getProducts(), true)) {
                         $this->errors[] = $tmpError;
                     }
                 } else {
                     $this->errors[] = Tools::displayError('Voucher name invalid.');
                 }
                 if (!sizeof($this->errors)) {
                     self::$cart->addDiscount((int) $discount->id);
                     Tools::redirect('order-opc.php');
                 }
             }
             self::$smarty->assign(array('errors' => $this->errors, 'discount_name' => Tools::safeOutput($discountName)));
             $this->adjustPoints();
         } elseif (isset($_GET['deleteDiscount']) and Validate::isUnsignedId($_GET['deleteDiscount'])) {
             self::$cart->deleteDiscount((int) $_GET['deleteDiscount']);
             Tools::redirect('order-opc.php');
         }
         /* Is there only virtual product in cart */
         if ($isVirtualCart = self::$cart->isVirtualCart()) {
             $this->_setNoCarrier();
         }
     }
     //if enough stock, show free gift message
     $free_products = array(66254, 66255, 66256);
     $sql = "select quantity from ps_product where id_product in (" . implode(",", $free_products) . ")";
     $result = Db::getInstance()->ExecuteS($sql);
     $free_gift_stock = $has_free_gift = false;
     foreach ($result as $row) {
         if (intval($row['quantity']) > 0) {
             $free_gift_stock = true;
             break;
         }
     }
     $total_products_wt = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
     $cv = Tools::convertPrice($total_products_wt, (int) self::$cookie->id_currency, false);
     /*if( $cv > 50) {	
     		if( $free_gift_stock ) {
     			$cart_products = self::$cart->getProducts();
     			foreach($cart_products as $cproduct) {
     				$id_product = $cproduct['id_product'];
     				if( in_array($id_product, $free_products )) {
     					$has_free_gift = true;
     					break;	
     				}
     			}
     		}
     		if( !$has_free_gift && $free_gift_stock ) {
     			self::$smarty->assign("spl_voucher_message","Here is the free <a href='/1222-free-gifts'>gift product</a> for you.Valid still stock lasts. Read <a href='/content/30-womens-day-special-discount'>T&C</a> here");
     		}
     	} else {
     		$free_products = array(66254, 66255, 66256);
     		foreach($free_products as $p)
     			self::$cart->deleteProduct($p);
     		self::$smarty->assign("spl_voucher_message","We have a free <a href='/1222-free-gifts'>gift product</a> for you if the shopping cart value is atleast USD 50.");
     	}
             self::$smarty->assign('back', Tools::safeOutput(Tools::getValue('back')));
     
             if (self::$cart->gift_message) {
                 self::$smarty->assign('cart_instructions', 1);
                 self::$smarty->assign('special_instructions', self::$cart->gift_message);
             }*/
     //buy1 get 1
     $products = self::$cart->getProducts(true);
     $offeredProducts = 0;
     // this is a very interesting array, keeps as many rows as there are items in your cart
     // if there is an item with quantity 2, it will have two rows in that array,
     // ie item will have as many rows as the quantity of the item in cart.
     $offerproducts = array();
     foreach ($products as $product) {
         $productObj = new Product($product['id_product'], true);
         $tags = $productObj->getTags(1);
         //print_r($productObj);
         if (in_array('buy1get1', $tags)) {
             self::$smarty->assign("spl_voucher_message", "You are eligible for Buy 1 Get 1 Offer");
             //counting the b1g1 products
             $offeredProducts = $offeredProducts + $product['cart_quantity'];
         } else {
             if (in_array('buy2get3', $tags)) {
                 self::$smarty->assign("spl_voucher_message", "You are eligible for buy 3 pay for 2 offer");
                 //counting the b1g1 products
                 $offeredProducts = $offeredProducts + $product['cart_quantity'];
             }
         }
         //adding rows to interesting array $b1g1products
         for ($q = 0; $q < $product['cart_quantity']; $q++) {
             array_push($offerproducts, $product);
         }
     }
     //sorting products in ascending order of price
     usort($offerproducts, function ($prod1, $prod2) {
         return $prod1['price'] - $prod2['price'];
     });
     ///echo "<pre>";print_r($offerproducts);
     if (in_array('buy1get1', $tags)) {
         $noOfferedAdvantageAvailable = (int) ($offeredProducts / 2);
     } elseif (in_array('buy2get3', $tags)) {
         $noOfferedAdvantageAvailable = (int) ($offeredProducts / 3);
     }
     $discount = 0;
     for ($p = 0; $p < $noOfferedAdvantageAvailable; $p++) {
         //print_r("offerproducts".$offerproducts[$p]['price']);
         $discount = $discount + $offerproducts[$p]['price'];
         //print_r($discount);
     }
     if ((int) self::$cart->id_currency != 2) {
         $discount = Tools::convertPrice($discount, (int) self::$cart->id_currency, false);
     }
     $discount = round($discount, 2);
     $b1g1DiscountInCart = null;
     $b2g3DiscountInCart = null;
     $allCartDiscounts = self::$cart->getDiscounts();
     //print_r($allCartDiscounts);
     foreach ($allCartDiscounts as $cartDiscount) {
         if (strpos($cartDiscount['name'], 'B1G1') === 0) {
             $b1g1DiscountInCart = new Discount((int) Discount::getIdByName($cartDiscount['name']));
             //echo "buy1get1";
         } else {
             if (strpos($cartDiscount['name'], 'B2G3') === 0) {
                 $b2g3DiscountInCart = new Discount((int) Discount::getIdByName($cartDiscount['name']));
                 //echo "buy2get3";
             }
         }
     }
     if (in_array('buy1get1', $tags)) {
         if ($discount > 0 && empty($b1g1DiscountInCart)) {
             $new_discount = new Discount();
             $new_discount->id_discount_type = 2;
             $new_discount->value = $discount;
             // coupon value
             $new_discount->name = "B1G1" . Tools::rand_string(5);
             $new_discount->id_currency = 2;
             $new_discount->quantity = 1;
             $new_discount->quantity_per_user = 0;
             $new_discount->date_from = date('Y-m-d H:i:s');
             $new_discount->date_to = '2015-08-10 20:00:00';
             //validity
             $new_discount->cumulable_reduction = 1;
             $languages = Language::getLanguages();
             foreach ($languages as $language) {
                 $new_discount->description[$language['id_lang']] = "Buy1 Get1";
             }
             // coupon description
             $new_discount->add();
             $id_discount = Discount::getIdByName($new_discount->name);
             self::$cart->addDiscount($id_discount);
         } else {
             if (!empty($b1g1DiscountInCart)) {
                 $b1g1DiscountInCart->value = (double) $discount;
                 // coupon value
                 if ($b1g1DiscountInCart->value > 0) {
                     $b1g1DiscountInCart->update();
                 } else {
                     $b1g1DiscountInCart->delete();
                 }
             }
         }
     } else {
         if (in_array('buy2get3', $tags)) {
             if ($discount > 0 && empty($b2g3DiscountInCart)) {
                 $new_discount = new Discount();
                 $new_discount->id_discount_type = 2;
                 $new_discount->value = $discount;
                 // coupon value
                 $new_discount->name = "B2G3" . Tools::rand_string(5);
                 $new_discount->id_currency = 2;
                 $new_discount->quantity = 1;
                 $new_discount->quantity_per_user = 0;
                 $new_discount->date_from = date('Y-m-d H:i:s');
                 $new_discount->date_to = '2015-08-10 20:00:00';
                 //validity
                 $new_discount->cumulable_reduction = 1;
                 $languages = Language::getLanguages();
                 foreach ($languages as $language) {
                     $new_discount->description[$language['id_lang']] = "Buy2 Get3";
                 }
                 // coupon description
                 $new_discount->add();
                 $id_discount = Discount::getIdByName($new_discount->name);
                 self::$cart->addDiscount($id_discount);
             } else {
                 if (!empty($b2g3DiscountInCart)) {
                     $b2g3DiscountInCart->value = (double) $discount;
                     // coupon value
                     if ($b2g3DiscountInCart->value > 0) {
                         $b2g3DiscountInCart->update();
                     } else {
                         $b2g3DiscountInCart->delete();
                     }
                 }
             }
         }
     }
     /*//pick3pay2
              $products = self::$cart->getProducts(true);
              //print_r($products);
     
              $nP3P2Products = 0;
             
             // this is a very interesting array, keeps as many rows as there are items in your cart
             // if there is an item with quantity 2, it will have two rows in that array, 
             // ie item will have as many rows as the quantity of the item in cart.
             $p3p2products = array();
             foreach($products as $product) {   
                 $productObj = new Product($product['id_product'], true);
                 $tags = $productObj->getTags(1);
                 if(in_array('pick3pay2', $tags)){
                     self::$smarty->assign("spl_voucher_message", "Pick 3 and Pay for 2 only offer");
                     $nP3P2Products = $nP3P2Products + $product['cart_quantity'];
                     
                     for($q = 0; $q < $product['cart_quantity']; $q++){
                         array_push($p3p2products, $product);
                     }  
                 }
             }
     
            
             
             //sorting products in ascending order of price
             usort($p3p2products, function($prod1, $prod2){
                 return $prod1['price'] - $prod2['price'];
             });
     
             $noP3P2AdvantageAvailable = (int)($nP3P2Products/3);
             print_r($noP3P2AdvantageAvailable);
             $discount = 0;
             for($p = 0; $p < $noP3P2AdvantageAvailable; $p++){
                 $discount = $discount + $p3p2products[$p]['price'];
             }
     
             if((int)self::$cart->id_currency != 2){
                 $discount = Tools::convertPrice($discount, (int)self::$cart->id_currency, false);
             }
             
             $discount = round($discount, 2);
     
             $p3p2DiscountInCart = null;
             $allCartDiscounts = self::$cart->getDiscounts();
     
             foreach ($allCartDiscounts as $cartDiscount) {
                 //print_r($cartDiscount);print_r('<br/>');die;
                 if(strpos('P3P2', $cartDiscount['name']) == 0){
                     $p3p2DiscountInCart = new Discount((int) (Discount::getIdByName($cartDiscount['name'])));
                 }
             }
             
             if($discount > 0 && empty($p3p2DiscountInCart)){
                 $new_discount = new Discount();
                 $new_discount->id_discount_type = 2;
                 $new_discount->value = $discount; // coupon value
                 $new_discount->name = "P3P2" . Tools::rand_string(5);
                 $new_discount->id_currency = 2;
                 $new_discount->quantity = 1;
                 $new_discount->quantity_per_user = 100;
                 $new_discount->date_from = date('Y-m-d H:i:s');
                 $new_discount->date_to = '2015-09-10 20:00:00'; //validity
                 $new_discount->cumulable_reduction = 1;
                 $languages = Language::getLanguages();
                 foreach ($languages as $language)
                     $new_discount->description[$language['id_lang']] = "Pick3 Pay2"; // coupon description
                 
                 $new_discount->add();
                 $id_discount = Discount::getIdByName($new_discount->name);
                 print_r($id_discount);
                 self::$cart->addDiscount($id_discount);
                 
             }else if(!empty($p3p2DiscountInCart)){
                 $p3p2DiscountInCart->value = (float) $discount; // coupon value
                 if($p3p2DiscountInCart->value > 0)
                     $p3p2DiscountInCart->update();
                 else
                     $p3p2DiscountInCart->delete();
             }*/
 }
 public function preProcess()
 {
     parent::preProcess();
     if (self::$cookie->isLogged() and !Tools::isSubmit('ajax')) {
         Tools::redirect('history.php');
     }
     if (Tools::getValue('create_account')) {
         $create_account = 1;
         self::$smarty->assign('email_create', 1);
     }
     if (Tools::isSubmit('SubmitCreate')) {
         if (!Validate::isEmail($email = Tools::getValue('email_create')) or empty($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (Customer::customerExists($email)) {
             $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             $_POST['email'] = $_POST['email_create'];
             unset($_POST['email_create']);
         } else {
             $create_account = 1;
             self::$smarty->assign('email_create', Tools::safeOutput($email));
             $_POST['email'] = $email;
         }
     }
     if (Tools::isSubmit('submitAccount') or Tools::isSubmit('submitGuestAccount')) {
         $create_account = 1;
         if (Tools::isSubmit('submitAccount')) {
             self::$smarty->assign('email_create', 1);
         }
         /* New Guest customer */
         if (!Tools::getValue('is_new_customer', 1) and !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
             $this->errors[] = Tools::displayError('You cannot create a guest account.');
         }
         if (!Tools::getValue('is_new_customer', 1)) {
             $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
         }
         if (isset($_POST['guest_email']) and $_POST['guest_email']) {
             $_POST['email'] = $_POST['guest_email'];
         }
         /* Preparing customer */
         $customer = new Customer();
         $lastnameAddress = $_POST['lastname'];
         $firstnameAddress = $_POST['firstname'];
         $_POST['lastname'] = $_POST['customer_lastname'];
         $_POST['firstname'] = $_POST['customer_firstname'];
         //if (!Tools::getValue('phone') AND !Tools::getValue('phone_mobile'))
         //$this->errors[] = Tools::displayError('You must register at least one phone number');
         if ($_POST['passwd'] != $_POST['retype_passwd']) {
             $this->errors[] = Tools::displayError('password and confirmation do not match');
         }
         $this->errors = array_unique(array_merge($this->errors, $customer->validateControler()));
         /*
         // Preparing address 
         $address = new Address();
         $_POST['lastname'] = $lastnameAddress;
         $_POST['firstname'] = $firstnameAddress;
         $address->id_customer = 1;
         $this->errors = array_unique(array_merge($this->errors, $address->validateControler()));
         
         // US customer: normalize the address 
         if($address->id_country == Country::getByIso('US'))
         {
         	include_once(_PS_TAASC_PATH_.'AddressStandardizationSolution.php');
         	$normalize = new AddressStandardizationSolution;
         	$address->address1 = $normalize->AddressLineStandardization($address->address1);
         	$address->address2 = $normalize->AddressLineStandardization($address->address2);
         }
         
         $zip_code_format = Country::getZipCodeFormat((int)(Tools::getValue('id_country')));
         if (Country::getNeedZipCode((int)(Tools::getValue('id_country'))))
         {
         	if (($postcode = Tools::getValue('postcode')) AND $zip_code_format)
         	{
         		$zip_regexp = '/^'.$zip_code_format.'$/ui';
         		$zip_regexp = str_replace(' ', '( |)', $zip_regexp);
         		$zip_regexp = str_replace('-', '(-|)', $zip_regexp);
         		$zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
         		$zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
         		$zip_regexp = str_replace('C', Country::getIsoById((int)(Tools::getValue('id_country'))), $zip_regexp);
         		if (!preg_match($zip_regexp, $postcode))
         			$this->errors[] = '<strong>'.Tools::displayError('Zip/ Postal code').'</strong> '.Tools::displayError('is invalid.').'<br />'.Tools::displayError('Must be typed as follows:').' '.str_replace('C', Country::getIsoById((int)(Tools::getValue('id_country'))), str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
         	}
         	elseif ($zip_code_format)
         		$this->errors[] = '<strong>'.Tools::displayError('Zip/ Postal code').'</strong> '.Tools::displayError('is required.');
         	elseif ($postcode AND !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode))
         		$this->errors[] = '<strong>'.Tools::displayError('Zip/ Postal code').'</strong> '.Tools::displayError('is invalid.');
         }
         if (Country::isNeedDniByCountryId($address->id_country) AND (!Tools::getValue('dni') OR !Validate::isDniLite(Tools::getValue('dni'))))
         	$this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
         elseif (!Country::isNeedDniByCountryId($address->id_country))
         	$address->dni = NULL;
         */
         //create customer and login
         if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) {
             $this->errors[] = Tools::displayError('Invalid date of birth');
         }
         if (!sizeof($this->errors)) {
             if (Customer::customerExists(Tools::getValue('email'))) {
                 $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             }
             if (Tools::isSubmit('newsletter')) {
                 $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr());
                 $customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s'));
             }
             $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
             if (!sizeof($this->errors)) {
                 //if (!$country = new Country($address->id_country, Configuration::get('PS_LANG_DEFAULT')) OR !Validate::isLoadedObject($country))
                 //die(Tools::displayError());
                 //if ((int)($country->contains_states) AND !(int)($address->id_state))
                 //$this->errors[] = Tools::displayError('This country requires a state selection.');
                 //else
                 //{
                 $customer->active = 1;
                 /* New Guest customer */
                 if (Tools::isSubmit('is_new_customer')) {
                     $customer->is_guest = !Tools::getValue('is_new_customer', 1);
                 } else {
                     $customer->is_guest = 0;
                 }
                 if (!$customer->add()) {
                     $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                 } else {
                     //award registration points
                     VBRewards::addRegistrationPoints($customer->id);
                     self::$cookie->new_reg = true;
                     self::$cookie->write();
                     //Add coupons to account
                     Tools::addCoupons($customer->id);
                     //$address->id_customer = (int)($customer->id);
                     //if (!$address->add())
                     //$this->errors[] = Tools::displayError('An error occurred while creating your address.');
                     //else
                     //{
                     if (!$customer->is_guest) {
                         //TODO: remove these extra emails
                         /*Mail::Send((int)(self::$cookie->id_lang), 'alert_account', Mail::l('New Customer Registered'),
                         						array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, 
                         						'{passwd}' => Tools::getValue('passwd')), '*****@*****.**', 'Vineet Saxena');
                         		
                         		Mail::Send((int)(self::$cookie->id_lang), 'alert_account', Mail::l('New Customer Registered'),
                         							array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email,
                         							'{passwd}' => Tools::getValue('passwd')), '*****@*****.**', 'Ramakant Sharma');
                         		
                         		*/
                         if ((int) self::$cookie->id_country === 110) {
                             $subject = Mail::l("Welcome to IndusDiva, INR 2500 has been credited to your account");
                             $amount = "INR 2500";
                         } else {
                             $subject = Mail::l("Welcome to IndusDiva, USD 100 has been credited to your account");
                             $amount = "USD 100";
                         }
                         if (!Mail::Send((int) self::$cookie->id_lang, 'account', $subject, array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd'), '{amount}' => $amount), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                             $this->errors[] = Tools::displayError('Cannot send email');
                         }
                     }
                     self::$smarty->assign('confirmation', 1);
                     self::$cookie->id_customer = (int) $customer->id;
                     self::$cookie->customer_lastname = $customer->lastname;
                     self::$cookie->customer_firstname = $customer->firstname;
                     self::$cookie->passwd = $customer->passwd;
                     self::$cookie->logged = 1;
                     self::$cookie->email = $customer->email;
                     self::$cookie->is_guest = !Tools::getValue('is_new_customer', 1);
                     /* Update cart address */
                     self::$cart->secure_key = $customer->secure_key;
                     //self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int)($customer->id));
                     //self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int)($customer->id));
                     self::$cart->update();
                     Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer));
                     if (Tools::isSubmit('ajax')) {
                         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) self::$cookie->id_customer, 'token' => Tools::getToken(false));
                         die(Tools::jsonEncode($return));
                     }
                     if ($back = Tools::getValue('back')) {
                         Tools::redirect($back);
                     }
                     Tools::redirect('index.php');
                     //}
                 }
                 //}
             }
         }
         if (sizeof($this->errors)) {
             if (!Tools::getValue('is_new_customer')) {
                 unset($_POST['passwd']);
             }
             if (Tools::isSubmit('ajax')) {
                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => false, 'id_customer' => 0);
                 die(Tools::jsonEncode($return));
             }
         }
     }
     if (isset($create_account)) {
         /* Select the most appropriate country */
         if (isset($_POST['id_country']) and is_numeric($_POST['id_country'])) {
             $selectedCountry = (int) $_POST['id_country'];
         }
         /* FIXME : language iso and country iso are not similar,
         			 * maybe an associative table with country an language can resolve it,
         			 * But for now it's a bug !
         			 * @see : bug #6968
         			 * @link:http://www.prestashop.com/bug_tracker/view/6968/
         			elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
         			{
         				$array = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
         				if (Validate::isLanguageIsoCode($array[0]))
         				{
         					$selectedCountry = Country::getByIso($array[0]);
         					if (!$selectedCountry)
         						$selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT'));
         				}
         			}*/
         if (!isset($selectedCountry)) {
             $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT');
         }
         $countries = Country::getCountries((int) self::$cookie->id_lang, true);
         self::$smarty->assign(array('countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'vat_management' => Configuration::get('VATNUMBER_MANAGEMENT')));
         /* Call a hook to display more information on form */
         self::$smarty->assign(array('HOOK_CREATE_ACCOUNT_FORM' => Module::hookExec('createAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Module::hookExec('createAccountTop')));
     }
     /* Generate years, months and days */
     if (isset($_POST['years']) and is_numeric($_POST['years'])) {
         $selectedYears = (int) $_POST['years'];
     }
     $years = Tools::dateYears();
     if (isset($_POST['months']) and is_numeric($_POST['months'])) {
         $selectedMonths = (int) $_POST['months'];
     }
     $months = Tools::dateMonths();
     if (isset($_POST['days']) and is_numeric($_POST['days'])) {
         $selectedDays = (int) $_POST['days'];
     }
     $days = Tools::dateDays();
     self::$smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0));
     self::$smarty->assign('newsletter', (int) Module::getInstanceByName('blocknewsletter')->active);
 }