<?php
//error_reporting(E_ALL);
ini_set('display_errors', 0);
$result['status'] = 0;
if (isset($_GET['action_type'])) {
    switch ($_GET['action_type']) {

        case 'login': { 
                $result = loginAPI($_GET['username'],$_GET['password']);
                break;
            }
        case 'forgotpassword':{
                $result = forgot($_GET['email']);
            break;
        }
        case 'changeBuyerPassword':{
                $result = changePasswordAPI($_GET['user_id'],$_GET['old_password'],$_GET['new_password']);
            break;
        }        
        case 'featuredProductlist': { 
                $result = featuredProductlistAPI($_GET['order']);
                break;
            }  
        case 'userProductDetails': { 
                $result = userProductDetailsAPI($_GET['product_id']);
                break;
            }    
        case 'productOptionVal': { 
                $result = getProductOptionValAPI($_GET['productoption_id']);
                break;
            }     
        case 'getCategoriesforBuyer': { 
                $result = getCategoriesforBuyerAPI();
                break;
            }
        case 'subCategoryListforBuyer':{
                $result = getCategoriesforBuyerAPI($_GET['category_id']);
                break;
            }    
        case 'categorywiseproductlist':{           
                $result = getcategorywiseproductlistAPI($_GET['category_id'],$_GET['order']);
                break;
            }  
        case 'searchProduct':{
                $result = searchProductAPI($_GET['search_txt']);
                break;
            }
        case 'addtocart':{           
                $result = addtocartAPI($_GET['product_id'],$_GET['product_option_id'],$_GET['qty'],$_GET['user_id']);
                break;
            } 
        case 'getUserCartCount':{           
                $result = getUserCartCountAPI($_GET['user_id']);
                break;
            } 
        case 'showUserCart':{           
                $result = showUserCartAPI($_GET['user_id']);
                break;
            }    
        case 'deletefromcart':{           
                $result = deletefromCartAPI($_GET['item_id']);
                break;
            }   
        case 'register':{           
                $result = registerAPI();
                break;
            }  
        case 'userProfile':{           
                $result = getUserProfileAPI($_GET['user_id']);
                break;
            } 
        case 'userProfileUpdate':{           
                $result = editUserProfileAPI();
                break;
            }  
        case 'myorders':{           
               $result = orderlistAPI($_GET['user_id']);
               break;
           }  
        case 'orderDetail':{           
               $result = orderDetailAPI($_GET['user_id'],$_GET['order_id']);
               break;
           }  
        case 'refundRequest':{           
               $result = refundRequestAPI($_GET['user_id']);
               break;
           } 
       case 'changeOrderStatus':{           
               $result = changeUserOrderStatusAPI($_GET['order_id'],$_GET['artist_id'],$_GET['status']);
               break;
           }  
       case 'updateCartQuantity':{
               $result = updateCartQuantityAPI($_GET['cart_id'],$_GET['qty']);
               break; 
           }
       case 'getCountryList':{
               $result = countrylistAPI();
               break; 
           }    
       case 'getCountryStateList':{
               $result = countryWiseStatelistAPI($_GET['county_code']);
               break; 
           }     
       case 'productInfoForRefundRequest':{
              $result = productInfoRefundRequestAPI($_GET['order_id']);
              break; 
           }
       case 'makeRefundRequest':{
            $result = makeRefundRequestAPI();
            break;           
           }
       case 'getshippingOption':{
            $result = getShippingOptionsAPI();
            break;           
           }   
       case 'getBillingAddress':{
            $result = getBillingAddressAPI($_GET['user_id']);
            break;           
           } 
      case 'updateBillingAddress':{
            $result = updateBillingAddressAPI();
            break;           
           }     
       case 'getShippingRates':{
            $result = getShippingRatesAPI();
            break;           
           }    
       case 'getPaymentoptionsAndTotal':{
            $result = getPaymentoptionsAndTotalAPI();
            break;           
           }    
       case 'makePaymentAuthorize':{
            $result = makePaymentAuthorizeAPI();
            break;           
           } 
       case 'paypalSuccess':{
            $result = paypalSuccessAPI();
            break;           
           } 
       case 'sortSearchResult':{
            $result = sortSearchResultAPI();
            break;           
           }
       case 'getShippingOptionsWithRates':{
            $result = getShippingOptionsWithRatesAPI();
            break;           
           }  
       case 'getAllShippingOptionsWithRates':{
            $result = getAllShippingOptionsWithRatesAPI();
            break;           
           }
        case 'aboutUsContent':{
            $result = aboutUsContentAPI();
            break;           
           }   
        case 'getSitenameandLogo':{
            $result = getSitenameandLogoAPI();
            break;           
           }     
        default: {
            $result['status'] = 0;
            $result['data'] = "Not a valid request";
            break;
            }
    }
} else {
    $result['status'] = 0;
    $result['data'] = "Not a valid request";
}
print_r(json_encode($result));


//---- Buyer Login API ---//
function loginAPI($username=NULL,$password=NULL) { 
    include "../includes/config.php";
    if (isset($username) && isset($password)) {
        
        $sql = "SELECT * FROM ".$tableprefix."users 
			WHERE user_name='".addslashes($username)."' 
			AND password = '".addslashes($password)."' AND deleted = 'N' ";
        
			$result=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result) > 0 )
			{                           
                            $row = mysql_fetch_assoc($result);  
                            $currentstatus['status'] = 1;
                            $currentstatus['data']   = $row;
                            return($currentstatus);  
                        } else {
                             $currentstatus['status'] = 0;
                             $currentstatus['data'] = "Invalid credentials.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Username/password missing.";
        return($currentstatus);       
    }
   
}

//-- Get Site Name & Logo --//
function getSitenameandLogoAPI(){
    include "../includes/config.php";
    $path = $rootserver."/banners/";
    $sql = "SELECT CONCAT( '$path',site_logo) AS logo,site_name FROM " . $tableprefix . "settings ";
   
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {   
        $row = mysql_fetch_assoc($result);
        $currentstatus['status'] = 1;
        $currentstatus['data'] = $row;
        return($currentstatus);        
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Something went wrong..";
        return($currentstatus); 
    }
}
//---- Buyer Forgot Password API ---//
function forgot($mail) 
{
   include "../includes/config.php";
   include "apifunctions.php";   
   if ($mail!=NULL) {
        if (!isValidEmail($mail)) {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "Please enter a valid mail ID";
            return($currentstatus);
        } else {
            $sql = "SELECT first_name,last_name,user_name, user_id FROM " . $tableprefix . "users WHERE email = '" . $mail . "' ";
            $res = mysql_query($sql);
            if (mysql_num_rows($res) != 0) {
                $row = mysql_fetch_array($res);
                $firstname = $row["first_name"];
                $lastname = $row["last_name"];
                $username = $row["user_name"];
                $userid = $row["user_id"];

                $randnum1 = mt_rand();
                if (strlen($randnum1) > 6) {
                    $randnum1 = substr($randnum1, 0, 6);
                }
                $newpass = $randnum1;
                $pass = md5($newpass);
                $sqlreset = "UPDATE " . $tableprefix . "users SET password = '$pass' WHERE user_id = '" . addslashes($userid) . "' ";

                $userfullname = $firstname;
                if ($lastname != "") {
                    $userfullname .= " " . $lastname;
                }
                $to = $mail;
                $subject = MAIL_ADMIN_FORGOT_PASSWORD_SUBJECT_1 . "Your password with  " . htmlentities(stripslashes(SITE_NAME)) . " " . MAIL_ADMIN_FORGOT_PASSWORD_SUBJECT_2;

                /* ----------Multicart 2.0 Upgradation--------------- */

                $mailmessage = readEmailTemplate('user_forgotpassword');

                $mailmessage = str_replace('[name]', $userfullname, $mailmessage);
                $mailmessage = str_replace('[user_name]', $username, $mailmessage);
                $mailmessage = str_replace('[password]', $newpass, $mailmessage);

                $mailmessage = nl2br($mailmessage);

                $mail_send_details = "<html><head><link href='" . SITE_URL . "/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=" . $logofolder . "/" . $logoimage . " width='125' height='39'/></div></div><div>" . $mailmessage . "</div></div><div align='left' class='clear_float'><img src=" . $imagefolder . "/clear.gif width=1 height=1/></div></div></div></center></body></html>";

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
                $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
                $mailsent = @mail($to, $subject, $mail_send_details, $headers);

                /* ----------Multicart 2.0 Upgradation--------------- */

                $successmessage = "";
                if ($mailsent) {
                    mysql_query($sqlreset);
                    $currentstatus['status'] = 1;
                    $currentstatus['data'] = PASSWORD_SEND_TO_MSG;
                    return($currentstatus);
                } else {
                    $currentstatus['status'] = 0;
                    $currentstatus['data'] = RETRY_MSG;
                    return($currentstatus);
                }
            } else {
                $currentstatus['status'] = 0;
                $currentstatus['data'] = EMAIL_NOT_REGISTERED_TEXT;
                return($currentstatus);
            }
        }
    } else {
        $currentstatus ['status'] = 0;
        $currentstatus ['data'] = "Email ID is missing";
    }   
   return $currentstatus;
}

//-----Change password-----//
function changePasswordAPI($user_id=NULL,$old_password=NULL,$new_password=NULL){
    include "../includes/config.php";
    if ($user_id!=NULL && $old_password!=NULL) {        
        
        $sql = "SELECT password FROM ".$tableprefix."users WHERE user_id = '".addslashes($user_id)."' 
                AND deleted = 'N' AND password = '".addslashes($old_password)."'";
       
			$result=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result) > 0 )
			{   
                            // Update with new password
                           $sql = "UPDATE ".$tableprefix."users SET 
                            password = '".$new_password."'
                            WHERE user_id =  '".$user_id."'";                            

                            $res = mysql_query($sql);
                            if($res)
                            {                           
                                $row = fetchAll($result);
                                $currentstatus['status'] = 1;
                                $currentstatus['data']   = "Password changed successfully.";
                                return($currentstatus);  
                            } else {
                                 $currentstatus['status'] = 0;
                                 $currentstatus['data'] = "Invalid user ID.";
                                 return($currentstatus); 
                            }                           
                        } else {
                             $currentstatus['status'] = 0;
                             $currentstatus['data'] = "Old password is incorrect.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Old password/user ID missing.";
        return($currentstatus);       
    }
    
}

//-----Featured Product List for buyer API ------//
function featuredProductlistAPI($order_type=NULL) {
    
    include "../includes/config.php";    
    $productListingFee = getSettingsValue('product_listing_fee');
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    $sql = "SELECT po.image_small,po.image_big,
            CASE WHEN po.image_small != ''  THEN CONCAT( '$path',po.image_small) ELSE '' END AS image_small,  
            CASE WHEN po.image_big != ''  THEN CONCAT( '$path',po.image_big) ELSE '' END AS image_big,  
            pd.product_id,po.product_option_id,po.product_stock,pd.product_name,(pd.product_price + po.additional_price) AS product_price,po.discount,ar.artist_id,
                    (SELECT pm.vimage_name FROM " . $tableprefix . "product_view_images pm where pm.nimage_productid=pd.product_id LIMIT 0,1)AS smallimage
			  FROM " . $tableprefix . "products pd
                          INNER JOIN " . $tableprefix . "product_options po ON po.product_id = pd.product_id AND po.default_option = 'YES'                          
                          LEFT JOIN " . $tableprefix . "artists ar on pd.product_artist_id=ar.artist_id LEFT JOIN " . $tableprefix . "record_ratings r ON pd.product_id = r.nrseller_id";     
        $whereCondition =" WHERE pd.product_artist_id=ar.artist_id AND pd.featured='Y' AND pd.vapproved='Y' AND ar.vapproved='Y' AND ar.plan_expired='N'";
        $whereCondition.=" AND pd.deleted='N' ";  // check deleted status
        $whereCondition.=" AND pd.publish_status='Y' ";  // check published status
        $whereCondition.=" AND pd.seller_vacation_mode='N' ";  // check seller vacation ode settings
        $whereCondition.=" AND pd.vSellerStatus='Y' ";  // check seller approved or plan expiry status
    //INNER JOIN " . $tableprefix . "artists ar ON ar.artist_id = pd.product_artist_id
    if ($productListingFee > 0) {
        $whereCondition .= " AND pd.payment_status='COMPLETED' ";
    }
    if(isset($order_type)&& $order_type!=NULL)
    {                   
            if($order_type=="ratingDesc"){
                    $order = "GROUP BY pd.product_id ORDER BY AVG(r.nrating_id) DESC ";
            }	
            else if($order_type=="vendorDesc"){
                    $order = "GROUP BY pd.product_id ORDER BY ar.artist_name DESC ";
            }
            else if($order_type=="vendorAsc"){
                    $order = "GROUP BY pd.product_id ORDER BY ar.artist_name ASC";
            }
            else if($order_type=="priceDesc"){
                    $order = "GROUP BY pd.product_id ORDER BY product_price DESC ";
            }  
            else if($order_type=="priceAsc"){
                    $order = "GROUP BY pd.product_id ORDER BY product_price ASC";
            }
            else {
                    $order = "GROUP BY pd.product_id ";
            }
    }
    else {
            $order = "ORDER BY pd.date_added  DESC";
    }
    
    $sql .= $whereCondition;
    $sql .= $order;
 
             
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                { 
                    $row = fetchAll($result);
                    foreach ($row as $key => $value) {
                        //--- Get product rating ---//
                        $select_rating_count = mysql_query("SELECT ROUND(SUM(nrating_id)/COUNT(nrating_id)) AS average_rating FROM " . $tableprefix . "record_ratings WHERE
                                                                                                            vType='p' AND nrseller_id = " . $value->product_id);

                        $average_rating_count = 0;
                        if (mysql_num_rows($select_rating_count) > 0) {
                            $rating_count = @mysql_fetch_array($select_rating_count);

                            if ($rating_count['average_rating'] != '') {
                                $average_rating_count = $rating_count['average_rating'];
                            } else {
                                $average_rating_count = 0;
                            }
                        }
                        $row[$key]->user_product_rating=$average_rating_count;
                    }                    
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = $row;                   
                    return($currentstatus);  
                    
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "No products added.";
                     return($currentstatus); 
                }
    
}

//--Get product details --//
function userProductDetailsAPI($productId=NULL){
    include "../includes/config.php";
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    if (isset($productId)) {
        
        $sql = "SELECT
        p.product_id,p.product_name,p.product_description,p.product_name,p.product_code,
        CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS product_image_small,  
        CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS product_image_big,     
        po.product_option_id,po.product_stock,(p.product_price + po.additional_price) AS product_price,
        po.discount,po.discount_description,po.product_shipping_weight,
        ar.company,ar.storename,ap.artist_photo,ar.state,ar.city,ar.country,ar.artist_name,ar.first_name,ar.last_name,ar.artist_id,ap.artist_description,c.category_id
        FROM " . $tableprefix . "products p
        INNER JOIN " . $tableprefix . "product_options po ON po.product_id = p.product_id AND po.default_option = 'YES'
        INNER JOIN  " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id
        INNER JOIN  " . $tableprefix . "categories  c ON c.category_id = p.product_category
        LEFT JOIN " . $tableprefix . "artist_portfolios ap ON ar.artist_id = ap.artist_id
        WHERE p.product_id = '" . addslashes($productId) . "' ";
        
        $result=mysql_query($sql) or die(mysql_error());        
        if(mysql_num_rows($result) > 0 )
        {                     
             $row = mysql_fetch_assoc($result);  
             $query_product_more_options = "SELECT product_option_id FROM ".$tableprefix."product_options WHERE product_id = '{$productId}'";
             $query_product_more_optionsQ = mysql_query($query_product_more_options);
             $product_more_options_count = mysql_num_rows($query_product_more_optionsQ);
             if($product_more_options_count>1) {
                 $cnt = 0;
                 while ($product_options_obj = mysql_fetch_object($query_product_more_optionsQ)) {                     
                    $query_available_options = "SELECT GROUP_CONCAT(concat(o.option_name, '-', pov.value) ORDER BY o.option_name ASC SEPARATOR ', ') AS option_val FROM " . $tableprefix . "product_option_values pov
	INNER JOIN " . $tableprefix . "options o ON o.option_id = pov.option_id WHERE pov.product_option_id = " . $product_options_obj->product_option_id . " ORDER BY o.option_name";
                    $query_available_optionsQ = mysql_query($query_available_options);

                    while ($product_options_val_obj = mysql_fetch_object($query_available_optionsQ)) {
                        //$options[][$product_options_obj->product_option_id] = $product_options_val_obj->option_val;
                        $options[$cnt]["option_id"] = $product_options_obj->product_option_id;
                        $options[$cnt]["option"]    = $product_options_val_obj->option_val;                                           
                    }
                    $cnt++;
                }
               
             }else{ 
                   $options = "Default";
                  /*$product_options_obj = mysql_fetch_object($query_product_more_optionsQ);
                  $query_available_options = "SELECT GROUP_CONCAT(concat(o.option_name, '-', pov.value) ORDER BY o.option_name ASC SEPARATOR ', ') AS option_val FROM ".$tableprefix."product_option_values pov
                  INNER JOIN ".$tableprefix."options o ON o.option_id = pov.option_id WHERE pov.product_option_id = ".$product_options_obj->product_option_id." ORDER BY o.option_name";
                  $query_available_optionsQ = mysql_query($query_available_options);
                  while($product_options_val_obj = mysql_fetch_object($query_available_optionsQ)) {
                    $options[][$product_options_obj->product_option_id] = ($product_options_val_obj->option_val!=NULL)?$product_options_val_obj->option_val:"Default Option";                   
                  }*/
                   
             }
             // Select More Images
             $sql_im = "select CASE WHEN vimage_name != ''  THEN CONCAT( '$path',vimage_name) ELSE '' END AS vimage_name  
                        from " . $tableprefix . "product_view_images  where nimage_productid ='" . mysql_real_escape_string($productId) . "' ";
             $result_im = mysql_query($sql_im) or die(mysql_error());
             $more_images = fetchAll($result_im);
             if(!empty($more_images))
                $row['more_images'] =  $more_images; 
             else
                $row['more_images'] =  "No Images"; 
           
             $row['options'] =  $options;
             $currentstatus['status'] = 1;
             $currentstatus['data']   = $row;             
             return($currentstatus);                      
        }else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "Invalid product ID.";
            return($currentstatus); 
       }
        
    }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "ProductId missing.";
        return($currentstatus);       
    }
}

//--Get product option details --//
function getProductOptionValAPI($productOptionID=NULL){
    include "../includes/config.php";
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    if (isset($productOptionID) && $productOptionID!=NULL) {
        
        $query 		= "SELECT (p.product_price+po.additional_price) AS product_price,po.product_stock,
                          CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS product_image_small,  
                          CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS product_image_big,  
                          po.discount,po.discount_description,po.product_shipping_weight
		         	 	FROM " . $tableprefix."product_options po
                                        INNER JOIN " . $tableprefix."products p ON p.product_id = po.product_id
                                        WHERE po.product_option_id = '".$productOptionID."'";
               
	$queryQ 	=  mysql_query($query);
	$details 	=  mysql_fetch_object($queryQ);                
        
        if(!empty($details) > 0 )
        { 
             $currentstatus['status'] = 1;
             $currentstatus['data']   = $details;             
             return($currentstatus);                      
        }else { 
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No records found.";
            return($currentstatus); 
       }
        
    }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Product option Id missing.";
        return($currentstatus);       
    }
}
//-- Category List --//
function getCategoriesforBuyerAPI($catId=NULL){
    include "../includes/config.php";
    $path = $rootserver."/categories/avatar/";
     if (isset($catId)&& $catId!= NULL) {
         $sql = " select category_id,category_name,parent_id,route,count,gift_certificate_flag,
                  CASE WHEN avatar != ''  THEN CONCAT( '$path',avatar) ELSE '' END AS category_image                       
                  FROM  " . $tableprefix . "categories where parent_id='$catId' AND category_id != 1";
     }else{
         $sql = " select category_id,category_name,parent_id,route,count,gift_certificate_flag,
                  CASE WHEN avatar != ''  THEN CONCAT( '$path',avatar) ELSE '' END AS category_image 
                  FROM  " . $tableprefix . "categories where parent_id=0 AND category_id != 1";
     } 
             
        $result=mysql_query($sql) or die(mysql_error());			
        if(mysql_num_rows($result) > 0 )
        {                           
            $row = fetchAll($result);
            $currentstatus['status'] = 1;
            $currentstatus['data'] = $row;
            return($currentstatus);
        }else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No categories found";
            return($currentstatus);       
        }     
}

//--Get getcategorywiseproductlist --//
function getcategorywiseproductlistAPI($category_id=NULL,$order_type=NULL){
    
    include "../includes/config.php";    
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    $productListingFee = getSettingsValue('product_listing_fee'); 
    if ($category_id != NULL) {
        if (CheckGiftCertificateCategory($category_id) == 'Y') {
            $sql = "SELECT p.product_id,p.product_name,(p.product_price + po.additional_price) AS product_price,
                    CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS image_small,  
                    CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS image_big,  
                    po.product_option_id,po.product_stock,po.discount,s.artist_name,s.artist_id,s.storename,
                    (SELECT pm.vimage_name FROM " . $tableprefix . "product_view_images pm where pm.nimage_productid=p.product_id LIMIT 0,1)AS smallimage, AVG(r.nrating_id) as user_product_rating
                          FROM " . $tableprefix . "products p
                          INNER JOIN " . $tableprefix . "product_options po ON po.product_id = p.product_id AND po.default_option = 'YES'
                          INNER JOIN " . $tableprefix . "giftcoupon_master gm oN gm.ngift_product_id=p.product_id
                          LEFT JOIN " . $tableprefix . "artists s on p.product_artist_id=s.artist_id 
                          LEFT JOIN " . $tableprefix . "record_ratings r ON p.product_id = r.nrseller_id ";                          
                    $sql .=" WHERE p.vapproved='Y' ";
                    $sql .=" AND p.deleted='N' ";  // check deleted status
                    $sql .=" AND p.publish_status='Y' ";  // check published status
                    $sql .=" AND p.seller_vacation_mode='N' ";  // check seller vacation ode settings
                    $sql .=" AND p.vSellerStatus='Y' ";  // check seller approved or plan expiry status
            if ($productListingFee > 0) {
                    $sql .= " AND p.payment_status='COMPLETED' ";
            }
            $sql .= "AND s.vapproved='Y' AND s.plan_expired='N' AND s.is_vacation_mode = 'N'";
        } else {
            $sql = "SELECT p.product_id,p.product_name,(p.product_price + po.additional_price) AS product_price,
                    CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS image_small,  
                    CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS image_big,  
                    po.product_option_id,po.product_stock,po.discount,s.artist_name,s.artist_id,s.storename,
            (SELECT pm.vimage_name FROM " . $tableprefix . "product_view_images pm where pm.nimage_productid=p.product_id LIMIT 0,1)AS smallimage, AVG(r.nrating_id) as user_product_rating
                          FROM " . $tableprefix . "products p
                          INNER JOIN " . $tableprefix . "product_options po ON po.product_id = p.product_id AND po.default_option = 'YES'
                          LEFT JOIN " . $tableprefix . "artists s on p.product_artist_id=s.artist_id 
                          LEFT JOIN " . $tableprefix . "record_ratings r ON p.product_id = r.nrseller_id";
                    $sql.=" WHERE p.vapproved='Y' ";
                    $sql.=" AND p.deleted='N' ";  // check deleted status
                    $sql.=" AND p.publish_status='Y' ";  // check published status
                    $sql.=" AND p.seller_vacation_mode='N' ";  // check seller vacation ode settings
                    $sql.=" AND p.vSellerStatus='Y' ";  // check seller approved or plan expiry status                          
            if ($productListingFee > 0) {
                $sql .= " AND p.payment_status='COMPLETED' ";
            }
            $sql .= "
                    AND s.vapproved='Y' AND s.plan_expired='N' AND s.is_vacation_mode = 'N'";
        }

        $qrystring = " AND p.product_category = " . $category_id ." ";
        
            if(isset($order_type)&& $order_type!=NULL)
            {                   
                    if($order_type=="ratingDesc"){
                            $order = "GROUP BY p.product_id ORDER BY AVG(r.nrating_id) DESC ";
                    }	
                    else if($order_type=="vendorDesc"){
                            $order = "GROUP BY p.product_id ORDER BY s.artist_name DESC ";
                    }
                    else if($order_type=="vendorAsc"){
                            $order = "GROUP BY p.product_id ORDER BY s.artist_name ASC";
                    }
                    else if($order_type=="priceDesc"){
                            $order = "GROUP BY p.product_id ORDER BY product_price DESC ";
                    }  
                    else if($order_type=="priceAsc"){
                            $order = "GROUP BY p.product_id ORDER BY product_price ASC";
                    }
                    else {
                            $order = "GROUP BY p.product_id ";
                    }
            }
            else {
                    $order = "GROUP BY p.product_id ";
            }
        $query = $sql . $qrystring . $order;

        $result = mysql_query($query) or die(mysql_error());        
        $row = fetchAll($result);
        
        if ($row[0]->product_id!=NULL) {
            $currentstatus['status'] = 1;
            $currentstatus['data'] = $row;
            return($currentstatus);
        } else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No categories found";
            return($currentstatus);
        }
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Category Id missing.";
        return($currentstatus);
    }
}


function sortSearchResultAPI(){
  
   $post_val['data'] = json_decode(stripslashes($_REQUEST['search_array']));   
   $order_type = $_REQUEST['orderType'];
   
   //sortType:  4-> SORT_ASC, 3->SORT_DESC
   if(isset($order_type)&& $order_type!=NULL)
            {                   
                    if($order_type=="ratingDesc"){
                            $sortOrder = 3;
                            $sortkey   = "user_product_rating";                            
                    }	
                    else if($order_type=="vendorDesc"){
                            $sortOrder = 3;
                            $sortkey   = "artist_id";                            
                    }
                    else if($order_type=="vendorAsc"){
                            $sortOrder = 4;
                            $sortkey   = "artist_id";                            
                    }
                    else if($order_type=="priceDesc"){
                            $sortOrder = 3;
                            $sortkey   = "product_price";                            
                    }  
                    else if($order_type=="priceAsc"){
                            $sortOrder = 4;
                            $sortkey   = "product_price";                            
                    }
            }
            else {
                    $sortOrder = 4;
                    $sortkey   = "product_id";
            }   
   $arrList=array($post_val['data']->products);  
   
   if($post_val['data'] && $order_type != NULL){
   
        foreach($post_val['data']->products as $key=>$value){     
           $new_searchArr[] = (array)$value;
        }     
        $res = sortBySubkey($new_searchArr, $sortkey,$sortOrder);      
        $currentstatus['status'] = 1;
        $currentstatus['data'] = $res;
        return($currentstatus);
   }else{
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient data.";
        return($currentstatus);
   }
}

function sortBySubkey($array, $subkey, $sortType = 4) {
    //sortType:  4-> SORT_ASC, 3->SORT_DESC
    foreach ($array as $key => $row) {
        $arrKey[$key] = $row[$subkey];
    }
    array_multisort($arrKey, $sortType, $array);  
    return $array;
}

function searchProductAPI($searchtxt=NULL){
    include "../includes/config.php";    
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    
    if($searchtxt!=NULL){
        $where .= ' AND p.product_name LIKE "%'.mysql_real_escape_string($searchtxt).'%" 
                    OR p.product_description LIKE "%'.mysql_real_escape_string($searchtxt).'%" GROUP BY p.product_id ';
        $sql = "SELECT DISTINCT p.product_id,p.product_description,po.product_option_id,(p.product_price+po.additional_price) AS product_price,            
                CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS image_small,  
                CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS image_big,    
                po.product_stock,po.discount,p.product_name,s.artist_name,s.artist_id,                
		(SELECT pm.vimage_name FROM " . $tableprefix . "product_view_images pm where pm.nimage_productid=p.product_id LIMIT 0,1)AS smallimage,AVG(r.nrating_id) as user_product_rating
				FROM " . $tableprefix . "products p
				INNER JOIN " . $tableprefix . "product_options po ON po.product_id = p.product_id AND po.default_option = 'YES'
				INNER JOIN " . $tableprefix . "artists s ON p.product_artist_id  = s.artist_id
                                LEFT JOIN " . $tableprefix . "record_ratings r ON p.product_id = r.nrseller_id     
				WHERE p.deleted != 'Y' AND p.vapproved='Y' AND s.plan_expired='N' ";
        if (getSettingsValue('product_listing_fee') > 0) {
            $sql .= " AND p.payment_status='COMPLETED' ";
        }
        $sql = $sql . $where;
       
        $result = mysql_query($sql) or die(mysql_error());        
        $row = fetchAll($result);
        if(!empty($row)){
            $currentstatus['status'] = 1;
            $currentstatus['data'] = $row;
            return($currentstatus);
        }else{
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No results found.";
            return($currentstatus);
        }
        
    }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient data.";
        return($currentstatus);
    }
}

//-- Add to cart API--//
function addtocartAPI($productid=NULL,$product_option_id=NULL,$usr_qty=NULL,$user_id=NULL){
    include "../includes/config.php";    
    include "apifunctions.php";   
    
    if ($productid && $product_option_id && $usr_qty != NULL) {
        //---Product stock check ---//
        $currentProductStock = getProductStock($product_option_id);
        if ($currentProductStock == 0) {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "Product out of stock.";
            return($currentstatus);
        }

        if (isset($usr_qty) && $usr_qty != '') {
            $qty = ($currentProductStock < $usr_qty) ? $currentProductStock : $usr_qty;
        } else {
            $qty = 1;
        }
        //---Product stock check ends ---//

        if ($user_id != NULL) {
            $select_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
						FROM " . $tableprefix . "cart c
                                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                WHERE  c.user_id = '" . $user_id . "' ";

            $result_cart = mysql_query($select_cart);
            if (mysql_num_rows($result_cart) > 0) {


                $select_digital_check = "SELECT ct.cart_id FROM " . $tableprefix . "cart ct," . $tableprefix . "products  prd
											 WHERE ct.product_id = prd.product_id
											  AND prd.vdigital_product = 'Y'
											  AND ct.user_id = '" . $user_id . "'";

                $result_digital_check = mysql_query($select_digital_check) or die(mysql_error());

                /* ---checking gift coupon-- */
                $select_gift_coupon = "SELECT prd.product_id FROM " . $tableprefix . "products prd," . $tableprefix . "categories ctry,
												" . $tableprefix . "cart ct
										   WHERE prd.product_category = ctry.category_id
										    AND ct.product_id = prd.product_id
											AND ctry.gift_certificate_flag = 'Y'
											AND ct.user_id = '" . $user_id . "'";

                $result_gift_coupon = mysql_query($select_gift_coupon) or die(mysql_error());

                if (mysql_num_rows($result_digital_check) > 0 || mysql_num_rows($result_gift_coupon) > 0) {
                    $select_digital = "SELECT prd.product_id FROM " . $tableprefix . "products prd
										   WHERE prd.vdigital_product = 'Y'
										    AND prd.product_id = '" . addslashes($productid) . "'";

                    $result_digital = mysql_query($select_digital) or die(mysql_error());

                    /* ---checking gift coupon-- */
                    $select_gift_coupon = "SELECT prd.product_id FROM " . $tableprefix . "products prd," . $tableprefix . "categories ctry
											   WHERE prd.product_category = ctry.category_id
												AND ctry.gift_certificate_flag = 'Y'
												AND prd.product_id = '" . addslashes($productid) . "'";

                    //echo $select_gift_coupon;

                    $result_gift_coupon = mysql_query($select_gift_coupon) or die(mysql_error());

                    if (mysql_num_rows($result_digital) == 0 && mysql_num_rows($result_gift_coupon) == 0) {
                        $currentstatus['status'] = 0;
                        $currentstatus['data'] = "As your cart contains digital product, adding a non digital product is not possible.";
                        return($currentstatus);
                        exit;
                    }
                } else {
                    /* ----------Checking digital product ends------------ */


                    /* ----------Checking NON digital product starts------------ */

                    $select_digital = "SELECT prd.product_id FROM " . $tableprefix . "products prd
										   	   WHERE prd.vdigital_product = 'Y'
											   	AND prd.product_id = '" . $productid . "'";

                    $result_digital = mysql_query($select_digital) or die(mysql_error());

                    if (mysql_num_rows($result_digital) > 0) {
                        $currentstatus['status'] = 0;
                        $currentstatus['data'] = "As your cart contains non digital product, adding a digital product is not possible.";
                        return($currentstatus);
                        exit;
                    }

                    /* ---checking gift coupon-- */

                    $select_gift_coupon = "SELECT prd.product_id FROM " . $tableprefix . "products prd," . $tableprefix . "categories ctry
										   	       WHERE prd.product_category = ctry.category_id
												    AND ctry.gift_certificate_flag = 'Y'
											   	    AND prd.product_id = '" . addslashes($productid) . "'";

                    //echo $select_digital;

                    $result_gift_coupon = mysql_query($select_gift_coupon) or die(mysql_error());

                    if (mysql_num_rows($result_gift_coupon) > 0) {
                        $currentstatus['status'] = 0;
                        $currentstatus['data'] = "As your cart contains non digital product, adding a digital product is not possible.";
                        return($currentstatus);
                        exit;
                    }
                }
                /* ----------Checking NON digital product ends------------ */
            }
            $sql = "SELECT cart_id,quantity FROM " . $tableprefix . "cart  WHERE product_option_id = '" . $product_option_id . "' and user_id = '" . $user_id . "' ";
            $res = mysql_query($sql);
            if (mysql_num_rows($res) > 0) {
                $rs_cartobj = mysql_fetch_object($res);

                $txtQty = $rs_cartobj->quantity;
                $txtNewQty = $txtQty + $qty;


                if ($txtNewQty > $currentProductStock) {
                    $sql1_up = "UPDATE  " . $tableprefix . "cart
							SET quantity = '" . $currentProductStock . "' WHERE cart_id = '" . $rs_cartobj->cart_id . "' AND  user_id = '" . $user_id . "' ";
                    $res = mysql_query($sql1_up) or die(mysql_error());
                    $select_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
						FROM " . $tableprefix . "cart c
                                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                WHERE  c.user_id = '" . $user_id . "' ";

                    $result_cart = mysql_query($select_cart);
                    if (mysql_num_rows($result_cart) > 0) {
                        $row = fetchAll($result_cart);
                        $currentstatus['status'] = 1;
                        $currentstatus['data'] = $row;
                        return($currentstatus);
                    }
                } else {
                    $sql1_up = "UPDATE  " . $tableprefix . "cart
							SET quantity = '" . $txtNewQty . "' WHERE cart_id = '" . $rs_cartobj->cart_id . "' AND  user_id = '" . $user_id . "' ";
                    $res = mysql_query($sql1_up) or die(mysql_error());

                    $select_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
						FROM " . $tableprefix . "cart c
                                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                WHERE  c.user_id = '" . $user_id . "' ";

                    $result_cart = mysql_query($select_cart);
                    if (mysql_num_rows($result_cart) > 0) {
                        $row = fetchAll($result_cart);
                        $currentstatus['status'] = 1;
                        $currentstatus['data'] = $row;
                        return($currentstatus);
                    }
                }
            }
            $time = time();
            $sql1 = "INSERT INTO " . $tableprefix . "cart (user_id,product_id,product_option_id,quantity,status,datetime_added) VALUES ('" . $user_id . "','" . $productid . "','" . $product_option_id . "','" . $qty . "','0','" . $time . "') ";

            $res = mysql_query($sql1);
            $cart_insert_id = mysql_insert_id();
            if ($cart_insert_id) {
                $row = fetchAll($result_cart);
                $currentstatus['status'] = 1;
                $currentstatus['data'] = "Added to cart successfully.";
                return($currentstatus);
            }
            
        } else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "User ID missing.";
            return($currentstatus);
        }
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Cannot proceed due to insufficient data.";
        return($currentstatus);
    }
}

// Function To Get Count of Cart Items of a Particular User
function getUserCartCountAPI($userid=NULL) {
    include "../includes/config.php";    
    if ($userid != NULL) {
        $sql_cart = "SELECT count(c.cart_id) as cartCount
	 			FROM " . $tableprefix . "cart  c
                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
			    WHERE c.user_id='" . $userid . "' ";
        $rs_cart = mysql_query($sql_cart) or die(mysql_error());
        $cartObj = mysql_fetch_object($rs_cart);
        $cartCount = $cartObj->cartCount;
        if (!$cartCount) {
            $cartCount = 0;
            $currentstatus['status'] = 1;
            $currentstatus['data'] = $cartCount;
            return($currentstatus);
        } else {
            $currentstatus['status'] = 1;
            $currentstatus['data'] = $cartCount;
            return($currentstatus);
        }
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "User Id missing.";
        return($currentstatus);
    }

}

//--Function to show user cart --//
function showUserCartAPI($user_id=NULL){
    include "../includes/config.php";
    include "apifunctions.php";

    if(ENABLE_AMAZON_S3_IMAGES == "Y")
       $path = AMAZON_S3_DOMAIN_URL."products/". $image['image_name'] ;
    else
        $path =  SITE_URL . "/products/". $image['image_name'];
    //$path = $rootserver."/products/";
    if($user_id!=NULL){
             $select_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id,po.product_stock,
                                                CASE WHEN po.image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS image_small,  
                                                CASE WHEN po.image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS image_big 
						FROM " . $tableprefix . "cart c
                                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                WHERE  c.user_id = '" . $user_id . "' ";

             
            $result_cart = mysql_query($select_cart);
            if (mysql_num_rows($result_cart) > 0) {
                $row = fetchAll($result_cart);
                $currentstatus['status'] = 1;
                $currentstatus['data'] = $row;
                return($currentstatus);
            }else{
                $currentstatus['status'] = 0;
                $currentstatus['data'] = "No records found.";
                return($currentstatus);
            }
        } else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "User ID missing.";
            return($currentstatus);
        }
}

//-- Delete from cart API --//
function deletefromCartAPI($itemIds=NULL){
    include "../includes/config.php";   
    if($itemIds!=NULL){        
        $sql = "DELETE FROM " . $tableprefix . "cart WHERE cart_id IN (" . $itemIds . ") ";
        mysql_query($sql);
        $currentstatus['status'] = 1;
        $currentstatus['data'] = "Selected item(s) deleted successfully.";
        return($currentstatus);
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Item ID missing.";
        return($currentstatus);
        }
}

//-- Register user --//
function registerAPI(){
    
    include "../includes/config.php";   
    include "apifunctions.php";      
    
    $txtUserName = stripslashes($_REQUEST['username']);
    $txtFirstName= stripslashes($_REQUEST['firstname']);
    $txtLastName = stripslashes($_REQUEST['lastname']);    
    $txtEmail    = stripslashes($_REQUEST['email']);   
    $txtPassword = stripslashes($_REQUEST["password"]);
    $txtDeviceId = stripslashes($_REQUEST["device_id"]);
    $check_news = ($_REQUEST["news_letter"]==1)?"Y":"N";   

    $message = "";

    if ($txtUserName==NULL) {
        $message = USERNAME_EMPTY_MSG ;
    } else {
        $qry = "SELECT  LOWER(user_name) FROM  " . $tableprefix . "users WHERE user_name='" . strtolower(addslashes($txtUserName)) . "' ";
        if (mysql_num_rows(mysql_query($qry)) > 0) {
            $message = USERNAME_EXISTS_MSG ;
        }
    }   

    if ($txtEmail==NULL) {
        $message = EMAIL_EMPTY_MSG ;
    } else {
        if (!isValidEmail($txtEmail)) {
            $message = INVALID_EMAIL_MSG ;
        }
    }

    $qry2 = "select email from  " . $tableprefix . "users where email='" . addslashes($txtEmail) . "'";
    if (mysql_num_rows(mysql_query($qry2)) > 0) {
        $message = EMAIL_ADDRESS_MSG ;
    }
    
    if($message!=""){
        $currentstatus['status'] = 0;
        $currentstatus['data'] = $message;
        return($currentstatus);
    }


    if($txtUserName!=NULL){
   
    if ($message != "") { // error
        $message = CORRECT_ERRORS_TEXT . $message;
        $currentstatus['status'] = 0;
        $currentstatus['data'] = $message;
        return($currentstatus);
    } else { // no error so insert user details
        $sql = "INSERT INTO " . $tableprefix . "users (
			user_name ,
			password,
			first_name,
			last_name,			
			email,
			device_id,
			newsLetter,
			date_registered
			) VALUES (
			'" . addslashes($txtUserName) . "',
			'" . addslashes(md5($txtPassword)) . "',
			'" . addslashes($txtFirstName) . "',
			'" . addslashes($txtLastName) . "',
			'" . addslashes($txtEmail) . "',
			'" . addslashes($txtDeviceId) . "',
			'" . addslashes($check_news) . "',							
			now()
			)";

        mysql_query($sql);
        $userid = mysql_insert_id();
   		

        if ($txtLastName != "") {
            $userfullname .= " " . $txtLastName;
        }

        $to = $txtEmail;

        $subject = MAIL_USER_ACCOUNT_MODIFY_SUBJECT_1 . " " . SITE_NAME;

        /* -------Email Template Reading Fuction Call-------- */

        $mailcontent = readEmailTemplate('member_registration');


        $mailcontent = str_replace('[user_name]', $txtUserName, $mailcontent);
        $mailcontent = str_replace('[password]', $txtPassword, $mailcontent);

        /* ---------------User Login Url------------------- */


        $mailcontent .= "\r\n" . MAIL_PLAN_PURCHASE_TEXT_CLICK . "&nbsp;<a href=" . SITE_URL . "/login.php>" . MAIL_PLAN_PURCHASE_TEXT_HERE . "</a> " . MAIL_PLAN_PURCHASE_TEXT_TO_LOGIN . "\r\n\n";

        /* ---------------User Login Url------------------- */

        $from = "From: " . SITE_EMAIL . "\n";
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Reply-To: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Return-Path: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Organization: " . SITE_NAME . "\r\n";
        $mailcontent = nl2br($mailcontent);

        $mail_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>' . SITE_NAME . ' - ' . MAIL_USER_REGISTRATION_TITLE . '</title>
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>' . $mailcontent . '</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';
        
        $mail_send_details = str_replace('[first_name]', $txtFirstName, $mail_send_details);
        $mail_send_details = str_replace('[last_name]', $txtLastName, $mail_send_details);
        
        $mailsent = mail($to, $subject, $mail_send_details, $headers);
        // **********************************************************************Send Mail To Administrator 


        $subject_admin = MAIL_USER_REGISTRATION_SUBJECT . " " . SITE_NAME;
        /* -------Email Template Reading Fuction Call-------- */
        $mailcontent_admin = readEmailTemplate('member_registration_admin');
        $mailcontent_admin = str_replace('[user_name]', $txtUserName, $mailcontent_admin);
        $mailcontent_admin = str_replace('[password]', $txtPassword, $mailcontent_admin);
        $mailcontent_admin = str_replace('[first_name]', $txtFirstName, $mailcontent_admin);
        $mailcontent_admin = str_replace('[last_name]', $txtLastName, $mailcontent_admin);

        /* ---------------User Login Url------------------- */


        $mailcontent_admin .= "\r\n" . MAIL_PLAN_PURCHASE_TEXT_CLICK . "&nbsp;<a href=" . SITE_URL . "/admin/login.php>" . MAIL_PLAN_PURCHASE_TEXT_HERE . "</a> " . MAIL_USER_REGISTRATION_TO_LOGIN_TO_VIEW_DETAILS_OF_MEMBER . "\r\n\n";

        /* ---------------User Login Url------------------- */

        $from = "From: " . SITE_EMAIL . "\n";
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Reply-To: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Return-Path: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
        $headers .= "Organization: " . SITE_NAME . "\r\n";

        $mailcontent_admin = nl2br($mailcontent_admin);
        $mail_send_details_admin = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>' . SITE_NAME . ' - ' . MAIL_USER_REGISTRATION_TITLE . '</title>
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>' . $mailcontent_admin . '</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';

        $adminemail = getSettingsValue('site_email');
        $mailsent = mail($adminemail, $subject_admin, $mail_send_details_admin, $headers);
        $sql = "SELECT * FROM ".$tableprefix."users 
			WHERE user_id='".$userid."' 
			AND deleted = 'N' ";
        
			$result=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result) > 0 )
			{                           
                            $row = mysql_fetch_assoc($result);  
                            $currentstatus['status'] = 1;
                            $currentstatus['data']   = $row;
                            return($currentstatus);  
                        }else{
                            $currentstatus['status'] = 0;
                            $currentstatus['data']   = "Sorry, something went wrong..";
                            return($currentstatus);
                        }
    }
  }
}

//-- Function to display user profile --//
function getUserProfileAPI($userid){
    include "../includes/config.php";
    include "apifunctions.php";
    if (isset($userid) && $userid != NULL) {
        
    $sql = "SELECT * FROM ".$tableprefix."users WHERE user_id = '".addslashes($userid)."' ";

        $result=mysql_query($sql) or die(mysql_error());			
        if(mysql_num_rows($result) > 0 )
        {                           
            $row = mysql_fetch_assoc($result);
            $row['state_code']=$row['state'];
            $row['country_code']=$row['country'];
            $row['state']  =  (getCodeValue($row['state'],2,$row['country'])!=NULL)?getCodeValue($row['state'],2,$row['country']):$row['state'];
            $row['country']=  getCodeValue($row['country'], 1);
            $currentstatus['status'] = 1;
            $currentstatus['data']   = $row;
            return($currentstatus);  
        } else {
             $currentstatus['status'] = 0;
             $currentstatus['data'] = "Invalid user ID.";
             return($currentstatus); 
        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "User ID is missing.";
        return($currentstatus);       
    }
}

//---User Details Update API---//
function editUserProfileAPI() {

    include "../includes/config.php";

    if (isset($_REQUEST['user_id']) && $_REQUEST['user_id'] != NULL) {
        
        $arrUser['user_id'] = stripslashes($_REQUEST['user_id']);
        $arrUser['first_name'] = stripslashes($_REQUEST['first_name']);
        $arrUser['last_name'] = stripslashes($_REQUEST['last_name']); 
        $arrUser['email'] = stripslashes($_REQUEST['email']);
        $arrUser['address1'] = stripslashes($_REQUEST['address1']);
        $arrUser['address2'] = stripslashes($_REQUEST['address2']);
        $arrUser['city'] = stripslashes($_REQUEST['city']);
        $arrUser['country'] = stripslashes($_REQUEST['country']);
        $arrUser['state'] = stripslashes($_REQUEST['state']);
        $arrUser['phone'] = stripslashes($_REQUEST['phone']);        
        $arrUser['fax'] = stripslashes($_REQUEST['fax']);
        $arrUser['zip'] = stripslashes($_REQUEST['zip']);
        $arrUser['newsLetter'] = stripslashes($_REQUEST['newsLetter']);
        
        $qry2 = "select email from  " . $tableprefix . "users where email='" . $arrUser['email'] . "' AND user_id <> '".$arrUser['user_id']."' ";
        if (mysql_num_rows(mysql_query($qry2)) > 0) {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = EMAIL_ADDRESS_MSG;
            return($currentstatus);            
        } 
    
        // Primary Seller info
        $sql = "UPDATE  " . $tableprefix . "users SET
                    first_name = '" . addslashes($arrUser['first_name']) . "',
                    last_name = '" . addslashes($arrUser['last_name']) . "',
                    address1 = '" . addslashes($arrUser['address1']) . "',
                    address2 = '" . addslashes($arrUser['address2']) . "',	
                    city = '" . addslashes($arrUser['city']) . "',			
                    phone = '" . addslashes($arrUser['phone']) . "',			
                    email = '" . addslashes($arrUser['email']) . "',			    
                    fax = '" . addslashes($arrUser['fax']) . "',	
                    zip = '" . addslashes($arrUser['zip']) . "',	    
                    country = '" . addslashes($arrUser['country']) . "',    
                    state = '" . addslashes($arrUser['state']) . "',      
                    newsLetter = '" . addslashes($arrUser['newsLetter']) . "'";
        $sql .=" WHERE user_id=" . $arrUser['user_id'];        
        mysql_query($sql) or die(mysql_error());

        $currentstatus['status'] = 1;
        $currentstatus['data'] = "User profile updated";
        return($currentstatus);
    }
    $currentstatus['status'] = 0;
    $currentstatus['data'] = "User ID is missing";
    return($currentstatus);
}

//-- User order List --//
function orderlistAPI($userid=NULL){
    include "../includes/config.php";
    include "apifunctions.php";
    
    if($userid!=NULL){
        $sql=      "SELECT o.*,s.order_status,od.product_name,od.product_id,gm.ngift_product_id,od.user_refund_id as refund_id,od.artist_id,
			sum( (od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as total,od.item_delivery_date
			FROM ".$tableprefix."orders o 
			INNER JOIN ".$tableprefix."order_status s ON o.order_status = s.order_status_id 
			LEFT JOIN ".$tableprefix."order_details od ON od.order_id=o.order_id 
			LEFT JOIN ".$tableprefix."giftcoupon_master gm ON gm.ngift_product_id=od.product_id 
			WHERE o.user_id = '".addslashes($userid)."'
			AND o.vpayment_status != 'P'  
			GROUP BY od.order_id 
			ORDER BY o.order_id DESC";
                        $result=mysql_query($sql) or die(mysql_error());			
                        if(mysql_num_rows($result) > 0 )
                        {                           
                            $row = fetchAll($result);
                            foreach ($row as $key => $value) {                                    
                                $row[$key]->Order_shipping_status = getOrderStatus($value->order_id);
                                $row[$key]->ShippingTotal   = getShippingTotal($value->order_id);                                
                                $row[$key]->DigitalProduct  = checkProductType($value->product_id);     
                                $row[$key]->currentDate     =  date('Y-m-d H:i:s');
                            }
                            
                            $currentstatus['status'] = 1;
                            $currentstatus['data'] = $row;
                            return($currentstatus);                            
                        }else{
                            $currentstatus['status'] = 0;
                            $currentstatus['data'] = "No orders found.";
                            return($currentstatus);
                        }
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "User ID is missing";
        return($currentstatus);
    }
}

//--Order Details API --//
function orderDetailAPI($userid=NULL,$order_id=NULL){
    include "../includes/config.php";
    include "apifunctions.php";
    
    if($order_id!=NULL){
        
        $select_order_gift = "SELECT prd.product_id 
                  FROM ".$tableprefix."products prd
                  INNER JOIN ".$tableprefix."order_details ord_det ON ord_det.product_id = prd.product_id
                  INNER JOIN ".$tableprefix."orders ord ON ord.order_id = ord_det.order_id
                  INNER JOIN ".$tableprefix."categories cat ON prd.product_category = cat.category_id
                  WHERE cat.gift_certificate_flag = 'Y'
                  AND ord.order_id = ".$order_id;
				  
        $result_order_gift = mysql_query($select_order_gift) or die(mysql_error());

        if(mysql_num_rows($result_order_gift) > 0)
        {
                $hide_shipping_display = 1;
                $gift_certificate=1;
        }
  
        $sql=      "SELECT o.*,
			sum( (od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as order_total_price
			FROM ".$tableprefix."orders o 
			LEFT JOIN ".$tableprefix."order_details od ON od.order_id=o.order_id 
			WHERE o.user_id = '".$userid."' AND o.order_id = ".$order_id." GROUP BY o.order_id ";
		 
        $result = mysql_query($sql);

        if(mysql_num_rows($result) != 0)
        {                       
                $prow = mysql_fetch_assoc($result);               
                $prow['ordernumber'] = $prow["order_id"];                
                $prow['ordertotal'] = $prow["order_total_price"];
                $prow['hide_shipping_display'] = $hide_shipping_display;
                $prow['gift_certificate'] = $gift_certificate;

                $prow['couponCodeDiscount'] =$prow["couponCodeDiscount"];
                if($prow["nused_gift_amount"] >0 || $couponCodeDiscount>0 ) {

                   $prow['giftDiscountAmount']           = $prow["nused_gift_amount"];
                   $prow['couponCodeDiscountAmount']     = $prow["couponCodeDiscount"];
                   $prow['TotalDiscount']   = $prow['giftDiscountAmount'] + $prow['couponCodeDiscount'];
                   $prow['priceafterdiscount']=$prow['ordertotal']-$prow['TotalDiscount'];
                   $prow['ordertotal']=number_format($prow['priceafterdiscount'],2,".","");

                }
                            
                $prow['orderdate'] = $prow["order_date"];
                $prow['userid'] = $prow["user_id"];
                $prow['exchange_price'] = $prow["nexchange_price"];
                $prow['netItemTotal']=$prow['ordertotal']+$taxrate;

        }
        /*---------Multicart 2.0 Upgradation---------*/
        else
        {
                $order_flag = 1;
        }

        $totalshippingAmount = 0;
        $select_shipping_cost1 = "SELECT sd.vshipping_name, sd.nshipping_cost,sd.nshp_productname
                                    FROM ".$tableprefix."shipping_details sd
                                   WHERE sd.norder_id = ".$order_id." AND  nshp_status = 'C' order by sd.nshp_productname";

        $result_shipping_cost1 = mysql_query($select_shipping_cost1);

        if(mysql_num_rows($result_shipping_cost1) > 0)
        {
                while($shipping_row=mysql_fetch_assoc($result_shipping_cost1))
                {
                    $totalshippingAmount+=$shipping_row['nshipping_cost'];
                    $prow['shippingDetails'][]=$shipping_row;
                } // end while                 
        } // en
        
               
        $prow['totalShippingCost']   =   $totalshippingAmount;
        $prow['taxrate']             =   $prow["taxrate"];   
        $prow['netOrderTotal']       =   $prow['netItemTotal'] + $totalshippingAmount+$prow["taxrate"];
       
        //--Items details according to different sellers ---//
        $artistlist = getOrderArtists($order_id);        
        $artists = explode(",",$artistlist );
        if(!empty($artists)){
            $ordermsg = ORDER_CNT_TEXT;
            $prow['order_message']  = str_replace("COUNT",count($artists),$ordermsg);                     
            for($i=0;$i< count($artists);$i++){
                $companyName = getArtistCompanyName($artists[$i]);
                
                if($gift_certificate==0)
                    { // check if products are not gifts certificates

                           $sql=" SELECT od.*,s.order_status,o.vorder_currency,o.taxrate,gm.ngift_product_id,gm.vgift_coupon_code
                                          FROM ".$tableprefix."order_details od
                                          INNER JOIN ".$tableprefix."order_status s ON s.order_status_id = od.item_status
                                          LEFT JOIN ".$tableprefix."giftcoupon_master gm ON gm.ngift_product_id=od.product_id 
                                          LEFT JOIN ".$tableprefix."orders o ON o.order_id=od.order_id 
                                          WHERE  od.order_id = '".addslashes($order_id)."'  AND  (od.artist_id = '".$artists[$i]."') 
      order by  od.product_name";

                   } // end if 			
							
                    if($gift_certificate==1)
                         { //	check if products are not gifts certificates
                                      $sql="SELECT od.*,s.order_status,o.vorder_currency,o.taxrate,gm.ngift_product_id,gm.vgift_coupon_code
                                                    FROM ".$tableprefix."order_details od
                                                    INNER JOIN ".$tableprefix."order_status s ON s.order_status_id = od.item_status
                                                    LEFT JOIN ".$tableprefix."giftcertificates gm ON gm.ngift_product_id=od.product_id  AND gm.ngift_order_id=od.order_id
                                                    LEFT JOIN ".$tableprefix."products p ON p.product_id=od.product_id 
                                                    LEFT JOIN ".$tableprefix."orders o ON o.order_id=od.order_id 
                                                    WHERE  od.order_id = '".addslashes($order_id)."'  AND  (od.artist_id = '".$artists[$i]."') 
                order by  od.product_name";
                        }
                $result1 = mysql_query($sql);       
                $cnt=0;
                while($rw = mysql_fetch_assoc($result1)){
                    //echo "<pre>";print_r($rw);exit;
                    $rw['company_name']=$companyName;
                    $rw['artist_id']=$artists[$i];
                    if($rw['order_status']=="Delivered"){$prow['order_status']="4";}
                    $prow['item_details'][$i]['seller_item'][$cnt]=$rw;
                    $cnt++;
                }
            }
         }
        $currentstatus['status'] = 1;
        $currentstatus['data']   = $prow;
        return($currentstatus); 
    }else{
    $currentstatus['status'] = 0;
    $currentstatus['data']   = "Order ID missing.";
    return($currentstatus); 
    }
    
    
}

//-- Refund Request --//
function refundRequestAPI($userId=NULL){
    include "../includes/config.php";
    include "apifunctions.php";
    if($userId!=NULL){        
         $sql="select o.billing_first_name,o.billing_last_name,o.billing_email ,o.order_id,a.artist_name,od.product_name,r.*,
             case when r.status is null then 'Awaiting Response'
             else r.status
             end as refund_status
	     from ".$tableprefix."orders o ,".$tableprefix."artists a , ".$tableprefix."order_details od ,".$tableprefix."refunds r 
	     where ".$qryopt." o.order_id=r.order_id  AND od.user_refund_id=r.refund_id and od.product_id=r.product_id
	     and a.artist_id=r.seller_id and r.buyer_id=".$userId." GROUP BY r.refund_id ORDER BY r.refund_id DESC ";
         
         $result = mysql_query($sql) or die(mysql_error());        
         $row = fetchAll($result);
         if(!empty($row)){
            $currentstatus['status'] = 1;
            $currentstatus['data']   = $row;
            return($currentstatus); 
         }else{
            $currentstatus['status'] = 0;
            $currentstatus['data']   = "No requests found.";
            return($currentstatus); 
         }
        
    }else{
    $currentstatus['status'] = 0;
    $currentstatus['data']   = "User ID missing.";
    return($currentstatus); 
    }
}

//-- Make Refund Request --//
function makeRefundRequestAPI(){
    include "../includes/config.php";
    include "apifunctions.php";
        
    //$post_val['data']  = stripslashes($_REQUEST['refund']);
    $post_val['data'] = json_decode(stripslashes($_REQUEST['refund']));
    $orderid           = $post_val['data']->order_id;
    $comments          = $post_val['data']->comments;    
    $refund_product    = $post_val['data']->products ;
    $user_id           = $post_val['data']->user_id;   
    
    
    if($orderid!=NULL){    
    foreach ($refund_product as $key => $value) {  
        
        $reason = addslashes($value->reason);
        $quantity = $value->product_quantity;
        $sellerid = $value->artist_id;
        $productname = addslashes($value->product_name);
        $prdctid = $value->product_id;       
        $userid = $user_id;  
        $productid = $prdctid;

        $sql_insert = "insert into  " . $tableprefix . "refunds(seller_id,buyer_id,product_id,order_id,quantity,return_reason,Additional_info,date)
					VALUES('" . $sellerid . "','" . $userid . "','" . $productid . "','" . $orderid . "','" . $quantity . "','" . $reason . "','" . $comments . "',now()) ";
        
        $rs_insert = mysql_query($sql_insert) or die(mysql_error());
        if ($rs_insert) { // updating order details table with refund id 
            $recordsper++;
            $refund_id = mysql_insert_id();
            $sql_update = "UPDATE " . $tableprefix . "order_details  set user_refund_id=" . $refund_id . " where order_id=" . $orderid . " and product_id=" . $productid . " ";
            
            $rs_update = mysql_query($sql_update);
            $sql = "select o.billing_first_name,o.billing_last_name,o.billing_email,o.order_id,DATE_FORMAT(o.order_date,'%m-%d-%Y') orderdate,a.artist_name,a.first_name,a.last_name,a.email as selleremail,od.product_name,r.status,r.*
	 		from " . $tableprefix . "orders o ," . $tableprefix . "artists a , " . $tableprefix . "order_details od ," . $tableprefix . "refunds r 
	 		where o.order_id=r.order_id  AND od.order_id=r.order_id and od.product_id=r.product_id AND  a.artist_id=r.seller_id  and r.buyer_id=" . $userid . " and r.refund_id=" . $refund_id . " ";
            $result = mysql_query($sql) or die(mysql_error());
            $numresults = mysql_num_rows($result);

            if ($numresults > 0) {
                $rm = mysql_fetch_array($result);
                //$username=$rm['user_name'];
                $sellername = $rm['artist_name'];

                $buyerfname = $rm['billing_first_name'];

                $buyerlname = $rm['billing_last_name'];

                $productname = $rm['product_name'];
                $quanity = $rm['quantity'];
                $reason = stripslashes($rm['return_reason']);
                $buyer_comments = stripslashes($rm['Additional_info']);               
                $date = date("m-d-Y");
                $to_seller = $rm['selleremail'];                
                $sellerfname = $rm['first_name'];
                $sellerlname = $rm['last_name'];
                $date_new = date("m-d-Y");
            }
            $date_new = dateFormat($date_new, "Y-m-d", "m/d/Y");
            $date_new_format = $date_new;

            // Send Mails to Seller 
            $refundid = $refund_id;
            $subject = MAIL_REFUND_REQUEST_SUBJECT . " " . SITE_NAME;
            /* -------Email Template Reading Fuction Call-------- */
            $mailcontent = readEmailTemplate('refund_registration_seller');
            //$mailcontent = htmlentities(stripslashes($mailcontent));

            $mailcontent = str_replace('[p_name]', stripslashes($productname), $mailcontent);
            $mailcontent = str_replace('[return_reason]', stripslashes($reason), $mailcontent);
            $mailcontent = str_replace('[quantity]', $quanity, $mailcontent);
            $mailcontent = str_replace('[date]', date('m-d-Y'), $mailcontent);
            if ($buyer_comments != '') {
                $mailcontent = str_replace('[comments]', $buyer_comments, $mailcontent);
            }
            $mailcontent = str_replace('[order_id]', $orderid, $mailcontent);
            $mailcontent = str_replace('[refund_id]', $refundid, $mailcontent);
            $mailcontent = str_replace('[seller_first_name]', $sellerfname, $mailcontent);
            $mailcontent = str_replace('[seller_last_name]', $sellerlname, $mailcontent);
            $mailcontent = str_replace('[first_name]', $buyerfname, $mailcontent);
            $mailcontent = str_replace('[last_name]', $buyerlname, $mailcontent);
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
            $mailcontent = nl2br($mailcontent);
            $mail_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >' . SITE_NAME . '</title>
  <link href="./themes/' . $active_template[4] . ' rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>' . $mailcontent . '</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';

            $mailsent = mail($to_seller, $subject, $mail_send_details, $headers);

            //////////////////////////////////////////////////////////////////// 
            // send mail to Administrator 

            $u_sql = "select first_name,last_name,email from " . $tableprefix . "users where user_id = " . $_SESSION["sess_userid"];
            $u_rs = mysql_query($u_sql);
            $u_rw = mysql_fetch_array($u_rs);
            $username = $u_rw["first_name"] . " " . $u_rw["last_name"];
            $to_buyer = $u_rw["email"];

            $subject = MAIL_REFUND_REQUEST_TO_ADMIN_SUBJECT . " " . SITE_NAME;

            $to_admin = SITE_EMAIL;
            /* -------Email Template Reading Fuction Call-------- */
            $mailcontent = readEmailTemplate('refund_request_reg_admin');
            $mailcontent = str_replace('[user_name]', $username, $mailcontent);
            $mailcontent = str_replace('[p_name]', stripslashes($productname), $mailcontent);
            $mailcontent = str_replace('[seller_name]', $sellername, $mailcontent);
            $mailcontent = str_replace('[reason]', stripslashes($reason), $mailcontent);
            $mailcontent = str_replace('[quantity]', $quanity, $mailcontent);
            $mailcontent = str_replace('[date]', date('m-d-Y'), $mailcontent);

            $mailcontent = str_replace('[first_name]', $buyerfname, $mailcontent);
            $mailcontent = str_replace('[last_name]', $buyerlname, $mailcontent);

            if ($buyer_comments != '') {
                $mailcontent = str_replace('[comments]', $buyer_comments, $mailcontent);
            }
            $mailcontent = str_replace('[order_id]', $orderid, $mailcontent);
            $mailcontent = str_replace('[refund_id]', $refundid, $mailcontent);

            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
            $mailcontent = nl2br($mailcontent);

            $mail_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >' . SITE_NAME . '</title>
  <link href="./themes/' . $active_template[4] . ' rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>' . $mailcontent . '</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';
//echo $mail_send_details;exit;

            $mailsent = mail($to_admin, $subject, $mail_send_details, $headers);
            // End Send Mail Message To Administrator

            if ($row['rma_confirm_message'] == 'Y') { //  check send mail confirmation 
                $subject = MAIL_REFUND_REQUEST_CONFIRMATION_SUBJECT . " " . SITE_NAME;
                /* -------Email Template Reading Fuction Call-------- */
                $mailcontent = readEmailTemplate('refund_registration');
                $mailcontent = str_replace('[p_name]', stripslashes($productname), $mailcontent);
                $mailcontent = str_replace('[return_reason]', $reason, $mailcontent);
                $mailcontent = str_replace('[quantity]', $quanity, $mailcontent);
                $mailcontent = str_replace('[date]', date('m-d-Y'), $mailcontent);
                if ($buyer_comments != '') {

                    $mailcontent = str_replace('[comments]', $buyer_comments, $mailcontent);
                }
                $mailcontent = str_replace('[order_id]', $orderid, $mailcontent);
                $mailcontent = str_replace('[refund_id]', $refundid, $mailcontent);
                $mailcontent = str_replace('[seller_first_name]', $sellerfname, $mailcontent);
                $mailcontent = str_replace('[seller_last_name]', $sellerlname, $mailcontent);
                $mailcontent = str_replace('[first_name]', $buyerfname, $mailcontent);
                $mailcontent = str_replace('[last_name]', $buyerlname, $mailcontent);

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
                $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";
                $mailcontent = nl2br($mailcontent);
                $mail_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >' . SITE_NAME . '</title>
  <link href="./themes/' . $active_template[4] . ' rel="stylesheet" type="text/css">
</head>
<body>

<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">
         
         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>' . $mailcontent . '</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';


                $mailsent = @mail($to_buyer, $subject, $mail_send_details, $headers);
            } // end if 
        } // end if update
       /* //--- Get Artist Id----//
        $sql_artist = "SELECT * FROM " . $tableprefix . "orders o INNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id where o.order_id='" . $orderid . "' AND vpayment_status='C' ";
        $result = mysql_query($sql_artist) or die(mysql_error());
        $artist_row = mysql_fetch_assoc($result);
        $artistId = $artist_row['artist_id'];
        $productName = $artist_row['product_name'];
        // Send push notification
        $devicesql = "Select device_id from " . $tableprefix . "artists where artist_id ='$artistId'"; //Get seller device ID           
        $result = mysql_query($devicesql);
        $device_row = mysql_fetch_assoc($result);
        $msg = "Refund request received for product " . $productName . " at " . SITE_NAME . ", please check.";
        send_push_nofication($msg, SITE_NAME, "armia", $device_row['device_id'], "Refund", "order"); //Message,From,passphrase,device token,type-->product,order...
        //-------------------------//*/
    }
    $currentstatus['status'] = 1;
    $currentstatus['data']   = "Refund request sent.";
    return($currentstatus); 
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Insufficient Data.";
        return($currentstatus); 
    }
    
}

//-- Function to get different ShippingOptions available ---//
function getShippingOptionsAPI(){ 
    include "../includes/config.php";
    $path = $rootserver."/images/";
    $sql = "SELECT * FROM " . $tableprefix . "settings ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result) != 0) {
        $row = mysql_fetch_array($result);
        
        $arrShipping[0]['name'] = "Fedex Express Ground Shipping ";
        $arrShipping[0]['mode'] = ($row['enable_fedexshipping']=="FDXG")?"Y":"N";
        $arrShipping[0]['code'] = "FDXG";
        $arrShipping[0]['img'] = $path."fedex.gif";
        
        $arrShipping[1]['name'] = "UPS Shipping ";
        $arrShipping[1]['mode'] = $row['enable_shipping'];
        $arrShipping[1]['code'] = "UPS";
        $arrShipping[1]['img']  = $path."ups.gif";   
        
        $arrShipping[2]['name'] = "USPS Shipping ";
        $arrShipping[2]['mode'] = $row['enable_uspsshipping'];
        $arrShipping[2]['code'] = "USPS";
        $arrShipping[2]['img']  = $path."usps.gif";
        
        $arrShipping[3]['name'] = "Canada Post Shipping";
        $arrShipping[3]['mode'] = $row['enable_canadapost'];
        $arrShipping[3]['code'] = "CP";
        $arrShipping[3]['img']  = $path."canadapost.gif";
        
        $arrShipping[4]['name'] = "Australia Post Shipping ";
        $arrShipping[4]['mode'] = $row['enable_australiapost'];
        $arrShipping[4]['code'] = "AP";
        $arrShipping[4]['img']  = $path."australiapost.jpg";
        
        $arrShipping[4]['name'] = "Flat Rate";
        $arrShipping[4]['mode'] = $row['enable_flatrate'];
        $arrShipping[4]['code'] = "Flat Rate";
        $arrShipping[4]['img']  = "";
        
        $currentstatus['status'] = 1;
        $currentstatus['data']   = $arrShipping;
        return($currentstatus); 
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Something went wrong.";
        return($currentstatus); 
    }
}

//-- Change user order status --//
function changeUserOrderStatusAPI($order_id=NULL,$artist_id=NULL,$status=NULL){
    include "../includes/config.php";
    include "apifunctions.php";
    if($order_id && $artist_id && $status != NULL){
    $sql ="UPDATE  ".$tableprefix."order_details SET
            item_status = '".$status."'
            WHERE order_id = '".$order_id."' AND artist_id = '".$artist_id."' ";
            $res = mysql_query($sql);            	
            // Update Item Delivery Time
            if($status=="4")
            {		
                $sql_deliverytime_up	= "UPDATE  ".$tableprefix."order_details SET item_delivery_date =now()
                                                                            WHERE order_id = '".$order_id."' AND artist_id = '".$artist_id."' ";								
                mysql_query($sql_deliverytime_up) or die(mysql_error());
            }
            $currentstatus['status'] = 1;
            $currentstatus['data']   = "Order Status Changed.";
            return($currentstatus); 
        
    }else{
    $currentstatus['status'] = 0;
    $currentstatus['data']   = "Insufficient Data.";
    return($currentstatus); 
    }
    
}

//-- Update cart quantitiy --//
function updateCartQuantityAPI($cartid=NULL,$qty=NULL){
    include "../includes/config.php";
    if($cartid && $qty != NULL){
        $sql = "UPDATE " . $tableprefix . "cart SET quantity = '" . $qty . "' WHERE cart_id='" . $cartid . "' ";
        mysql_query($sql);
        $currentstatus['status'] = 1;
        $currentstatus['data']   = "Item quantity updated.";
        return($currentstatus); 
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Insufficient Data.";
        return($currentstatus); 
    }
    
}

//-- Country list API --//
function countrylistAPI(){
    include "apifunctions.php";
    $data = getCodeValue("",3);
    if(!empty($data)){
        $cnt=0;
        foreach ($data as $key => $value) {
            $arrCounty[$cnt]['name']=$value;
            $arrCounty[$cnt]['code']=$key;
            $cnt++;
        }       
        $currentstatus['status'] = 1;
        $currentstatus['data']   = $arrCounty;
        return($currentstatus); 
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Something wrong.";
        return($currentstatus); 
    }
}

//-- Country wise state list --//
function countryWiseStatelistAPI($countryCode=NULL){
    include "apifunctions.php";    
    if($countryCode!=NULL){
        $data = getCodeValue("",4,$countryCode);
        if(!empty($data)){
            $cnt=0;
            foreach ($data as $key => $value) {
                $arrState[$cnt]['name']=$value;
                $arrState[$cnt]['code']=$key;
                $cnt++;
            }
            $currentstatus['status'] = 1;
            $currentstatus['data']   = $arrState;
            return($currentstatus); 
        }else{
            $currentstatus['status'] = 0;
            $currentstatus['data']   = "Something wrong.";
            return($currentstatus); 
        }
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Country Code missing";
        return($currentstatus); 
    }
}

//-- Refund requsest for products in orderlist --//
function productInfoRefundRequestAPI($orderid=NULL){
    include "../includes/config.php";
    if($orderid != NULL){        
          $sql = "(SELECT od.*,o.user_id, 'Cant make it work' as reason
				FROM " . $tableprefix . "order_details od
				INNER JOIN " . $tableprefix . "orders o
				ON o.order_id =od.order_id
				WHERE od.order_id=" . $orderid . "
				AND od.item_status=4
				AND DATE_ADD(od.item_delivery_date,INTERVAL 48 HOUR) >= now()
				ORDER BY od.order_detail_id  DESC)
                                UNION
                                (SELECT od.*,o.user_id, 'Cant make it work' as reason
				FROM " . $tableprefix . "order_details od
				INNER JOIN " . $tableprefix . "orders o
				ON o.order_id =od.order_id
                                LEFT JOIN " . $tableprefix . "products p ON p.product_id = od.product_id
				WHERE od.order_id=" . $orderid . "
				AND od.item_status=4
				AND p.vdigital_product='Y'
				ORDER BY od.order_detail_id  DESC)";
                          
        $rs=mysql_query($sql); 
        $row = fetchAll($rs);
        if(!empty($row)){
            $currentstatus['status'] = 1;
            $currentstatus['data']   = $row;
        }else{
            $currentstatus['status'] = 0;
            $currentstatus['data']   = "No records found.";
        }        
    }else{
        $currentstatus['status'] = 0;
        $currentstatus['data']   = "Order ID missing.";
    }
    return($currentstatus); 
}

//--Get Shipping Options--//
function getShippingRatesAPI(){
    include "../includes/config.php";
    include "apifunctions.php"; 
    
    $shippingOption = stripslashes($_REQUEST['shipping_option']);
    $userId         = stripslashes($_REQUEST['user_id']);
    $shippingCountry= stripslashes($_REQUEST['shippingCountry']);    
    $shippingState  = stripslashes($_REQUEST['shippingState']);   
    $shippingZip    = stripslashes($_REQUEST["shippingZip"]);    
    $flatrateEnabled=getSettingsValue('enable_flatrate');
    if($shippingOption && $userId!=NULL){
        
               //--Set shipping configurations--//
               switch ($shippingOption) {
                CASE "FDXE":
                CASE "FDXG":
                require_once '../library/class.fedex.php';
                require_once '../library/class.fedex.rate.php';
                require_once '../library/class.fedex.package.php';
                ini_set("soap.wsdl_cache_enabled", "0");

                $sql = "select * from " . $tableprefix . "fedexsettings ";
                $rs = mysql_query($sql) or die(mysql_error());
                if (mysql_num_rows($rs) > 0) {
                    $serviceName = array();
                    $row = mysql_fetch_array($rs);
                    $fedexaccno = stripslashes($row['FedexAccno']);
                    $fedexmeterno = stripslashes($row['FedexMeterno']);
                    $weightunits = $row['FedexWeight'];
                    $server = $row['FedexServer'];
                    $dropoff = stripslashes($row['FedexDropOff']);
                    $packageTypes = stripslashes($row['FedexPackage']);
                    $fedexPassword = stripslashes($row['FedexPassword']);
                    $fedexKey = stripslashes($row['FedexKey']);
                    $sName = $row['FedexService'];
                    $currency = $row['FedexCurrency'];
                    if ($shippingOption == "FDXE") {
                        $sarry = $fedexService;
                        $shippingTitle = "Fedex Express Shipping";
                    } else {
                        $sarry = $fedexGroundService;
                        $shippingTitle = "Fedex Express Ground Shipping";
                    }
                    
                    $objRates = new stdClass();
                    $objRates->ship_account = trim($fedexaccno);
                    $objRates->meter = trim($fedexmeterno);
                    $objRates->password = trim($fedexPassword);
                    $objRates->account = "";
                    $objRates->bill_account = "";
                    $objRates->duty_account = "";
                    $objRates->account_to_validate = "";
                    $objRates->track_account = "";
                    $objRates->key = trim($fedexKey);
                    $objRates->wsdl_path = "RateService_v9.wsdl";
                    $objRate = new fedexRates();
                    $objRate->requestType("rate");
                    $objRate->setData($objRates);
                    $objRate->wsdl_root_path = "wsdl/";
                    $client = new SoapClient($objRate->wsdl_root_path . $objRate->wsdl_path, array('trace' => 1));
                } // end num rows check
                switch ($server) {
                    case "test":
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    case "production":
                        // change this to actual server when go on live
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    default:
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                }
                break;

            CASE "USPS":
                //// check enabled shipping is usps or not
                include_once("../usps/xmlparser.php");
                include_once('../usps/usps.php');
                $shippingTitle = "USPS";
                $sql = "select * from " . $tableprefix . "usps_settings ";
                $rs = mysql_query($sql) or die(mysql_error());
                if (mysql_num_rows($rs) > 0) {
                    $row = mysql_fetch_array($rs);
                    $uspsid = $row['username'];
                    $server = $row['server'];
                } // end num rows check
                $uspsRequired_Service =  array("Express Mail","Express Mail Hold For Pickup","Express Mail Sunday/Holiday Delivery","Priority Mail","Parcel Post","Priority Mail Large Flat Rate Box","
Priority Mail Express 2-Day","Priority Mail 2-Day","Priority Mail 2-Day Small Flat Rate Box","Media Mail","Library Mail");
                switch ($server) {
                    case "test":
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                    case "production":
                        //change this line when usps is on live 
                        $uspsserver = "http://production.shippingapis.com/ShippingAPI.dll";
                        break;
                    default :
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                } // end switch

                break;
            CASE "UPS":
                require("../ups.php");
                include_once("../shipping.php");
                include_once('../http_client.php');
                $shippingTitle = "UPS";
                // Shipping setting for UPS Shipping
                $select_shipping_settings = "SELECT * FROM " . $tableprefix . "shipping_settings";
                $result_shipping_settings = mysql_query($select_shipping_settings);
                if (mysql_num_rows($result_shipping_settings) > 0) {
                    $rs_ship = mysql_fetch_array($result_shipping_settings);
                    $ups_weight = $rs_ship['nShippingweight'];
                    $ups_rate = $rs_ship['ups_rate'];
                    $ups_container = $rs_ship['container_type'];
                    $ups_type = $rs_ship['address_quote_method'];
                }                
                $upsrate = new Ups;
                break;
            CASE "AP":
                $shippingTitle = "Australian Post";                
                $australianServiceArray = array("STANDARD" => "Standard Post", "EXPRESS" => "Express Post", "AIR" => "Air Post", "SEA" => "Sea Post");
                break;
            CASE "CP":
                require_once("../includes/class.canadapost.php");
                $shippingTitle = "Canada Post";
                break;
            CASE "Flat Rate":
                $shippingTitle = "Our Shipping";
            DEFAULT:
        }
        //--Get items from cart for current user --//
        $select_cart_details = "SELECT prd.product_id,prd.product_name,po.product_option_id,po.product_length,po.product_width,po.product_height,crt.quantity,
                       po.product_shipping_weight,art.country AS origin_country,art.state AS origin_state,art.zip AS origin_zip,art.artist_id,art.artist_name,
                       art.defaultflatrate,art.additionalflatrate
                       FROM ".$tableprefix."cart crt
                       INNER JOIN ".$tableprefix."product_options po ON crt.product_option_id = po.product_option_id
                       INNER JOIN ".$tableprefix."products prd ON prd.product_id = po.product_id
                       INNER JOIN ".$tableprefix."artists art ON art.artist_id = prd.product_artist_id
                       WHERE crt.user_id = ".$userId." ORDER BY crt.cart_id";
        $result_cart_details = mysql_query($select_cart_details) or die(mysql_error());
        
       //Get shipping rates for various products
        while($cart_details_data = mysql_fetch_assoc($result_cart_details)) {
            $artistId = $cart_details_data['artist_id'];
            $productDataArray[$artistId][] = $cart_details_data;
        } 
        
        /*****************************************/
        foreach($productDataArray as $cart_details_row){ 

        // Seller Location (Source)
        $origin_country     = $cart_details_row[0]['origin_country'];
        $origin_state       = $cart_details_row[0]['origin_state'];
        $origin_zip         = $cart_details_row[0]['origin_zip'];

        // User Location (Destination)
        $destination_country     = $shippingCountry;
        $destination_state       = $shippingState;
        $destination_zip         = $shippingZip;

        // Seller Details
        $artist_id          = $cart_details_row[0]['artist_id'];
        $artistName         = $cart_details_row[0]['artist_name'];

        $quantity = 0;
        $shipping_weight = 0;
        $productSubArray = "";
        $productLength = "";
        $productHeight = "";
        $productWidth = "";
        // Product Details
        foreach($cart_details_row as $pData){

            $product_name       = $pData['product_name'];
            $product_id         = $pData['product_id'];
            $product_option_id  = $pData['product_option_id'];
            $optionsStr         = "";
            $optionVal          = getProductOptionsName($product_option_id);
        if($optionVal!="") {
                $optionsStr         = '<span class="spoptions">'.$optionVal.'</span>';
            }
            $productSubArray['productName'][$product_option_id] = '<span class="spname">'.$product_name.'</span>'.$optionsStr;
            
            $quantity           += trim($pData['quantity']);


            $productLength[]         = $pData['product_length'];
            $productHeight[]         = $pData['product_height'];
            $productWidth[]          = $pData['product_width'];

            $shipping_weight    += trim($pData['product_shipping_weight']);
             
        }
        $productSubArray['artistName'] = $artistName;

        $product_length = max($productLength);
        $product_height = max($productHeight);
        $product_width  = max($productWidth);

        $productArray[$artist_id] =  $productSubArray;
        $fedex_shipping_weight  = $shipping_weight * $quantity;

        //set for ups only       
        //======================Getting rates for each product from shipping gateways-Santhosh=================================
        switch($shippingOption) { 

            CASE "FDXE":
            CASE "FDXG":

                 $aryShipper = array(
		'Contact' => array(
			'PersonName' => 'Sender Name',
			'CompanyName' => 'Sender Company Name',
			'PhoneNumber' => '9012638716'),
		'Address' => array(
			'StreetLines' => array('Address Line 1'),
			'City' => $origin_city,
			'StateOrProvinceCode' => $origin_state,
			'PostalCode' => $origin_zip,
			'CountryCode' => $origin_country)
	);

   $aryRecipient = array(
		'Contact' => array(
			'PersonName' => 'Recipient Name',
			'CompanyName' => 'Company Name',
			'PhoneNumber' => '9012637906'
		),
		'Address' => array(
			'StreetLines' => array('Address Line 1'),
			'City' => $destination_city,
			'StateOrProvinceCode' => $destination_state,
			'PostalCode' => $destination_zip,
			'CountryCode' => $destination_country,
			'Residential' => false)
	);
   
   
   $fedexService                      = array('PRIORITY_OVERNIGHT','STANDARD_OVERNIGHT','INTERNATIONAL_PRIORITY','FEDEX_GROUND','FIRST_OVERNIGHT','FEDEX2DAY');
   $rateResponseArr                   = array();
   
   
            foreach($fedexService as $serviceNames) {  
                     $packages = array();

                     $aryPackage = array();

                     $total_packages = 1;
                     
                     if($product_length==0 || $product_length>70)
                     {
                         $product_length = '17.88';
                     }
                     
                      if($product_width==0 || $product_width>70)
                     {
                         $product_width = '12.88';
                     }
                     
                     if($product_height==0 || $product_height>10)
                     {
                         $product_height = '3.00';
                     }
                     

                     $packages[0] = new Package("FEDEX Package # 1", $total_packages, 1);
                     $packages[0]->setPackageWeight($fedex_shipping_weight);     //Package Actual Weight
                     $packages[0]->setPackageDimensions($product_length, $product_width, $product_height);       //Package (Length x Width x Height)
                     $aryPackage[0] = $packages[0]->getObjectArray();

                     $aryOrder = array(
                                     'TotalPackages' => $total_packages,
                                     'PackageType' => 'YOUR_PACKAGING',        #FEDEX_10KG_BOX, FEDEX_25KG_BOX, FEDEX_BOX, FEDEX_ENVELOPE, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
                                     'ServiceType' => $serviceNames,
                                     'TermsOfSaleType' => "DDU",         #    DDU/DDP
                                     'DropoffType' => 'REGULAR_PICKUP'         # BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER, STATION
                     );

                     $request = $objRate->rateRequest($aryRecipient,$aryShipper,$aryOrder,$aryPackage);


                     $rateResponseArr[]    = $objRate->getRates($request,$client);
                     
                }
                 if(!empty($rateResponseArr))  {
                    foreach($rateResponseArr as $serviceVals)
                     {
                       if(@$serviceVals->error=='' && $serviceVals->ServiceName!='')
                        $resultShippingArray[$artist_id][]= array("service_name"=>@$serviceVals->ServiceName,"rate"=>@$serviceVals->amount,"seller_name"=>$artistName,"seller_id"=>$artist_id);
                     }
                 }
              
                break;
            CASE "USPS":
                
                $usps_shipping_weight = $shipping_weight * $quantity;
                
                if($usps_shipping_weight<1) {
                    $usps_shipping_weight = 1;
                }
                $usps_shipping_weightSplit = explode(".", $usps_shipping_weight);
                $shipping_pounds = $usps_shipping_weightSplit[0];
                $ouncelength     =  count_digit($usps_shipping_weightSplit[1]);
                if($ouncelength == 0) {
                    $shipping_ounces = 0;
                }
                if($ouncelength == 1) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10) * 16;
                }
                if($ouncelength == 2) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 100) * 16;
                }
                if($ouncelength == 3) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 1000) * 16;
                }
                if($ouncelength == 4) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10000) * 16;
                }
               
                $usps = new USPS;
                if($server=="test") {
                    $usps->setWeight(10,5);
                    $usps->setDestZip("20008");
                    $usps->setOrigZip("10022");
                }else {
                    $usps->setDestZip($destination_zip);
                    $usps->setOrigZip($origin_zip);
                    $usps->setWeight($shipping_pounds,$shipping_ounces);
                }
                
                $usps->setServer($uspsserver);
                $usps->setUserName($uspsid);
                $uspspaswd = "";
                $usps->setPass($uspspaswd);
                $usps->setService("All");               

                $usps->setCountry("USA");

                $usps->setMachinable("true");

                $usps->setSize("REGULAR");

                $uspsprice = array();

                $uspsprice = $usps->getPrice();                
                

               $special_chars = "&lt;sup&gt;&amp;reg;&lt;/sup&gt;";
                    if($uspsprice->error->description=="") {
                       
                       foreach($uspsprice->list AS $key=>$eachItem) {
                           if($eachItem->mailservice!="" && $eachItem->rate!="") {
                             //$eachItemServicename = str_replace($special_chars,"",$eachItem->mailservice);
                              $eachItemServicename  = @htmlspecialchars_decode($eachItem->mailservice);
                              $eachItemServicename = @preg_replace ("/<sup>(.*?)<\/sup>/i", "", $eachItemServicename);
                             if(in_array($eachItemServicename,$uspsRequired_Service)) {
                                 $resultShippingArray[$artist_id][]= array("service_name"=>$eachItemServicename,"rate"=>$eachItem->rate,"seller_name"=>$artistName,"seller_id"=>$artist_id);                                
                           }
                           }
                       }
                   }
                
                break;
            CASE "UPS":

                $ups_shipping_weight = $shipping_weight * $quantity;
            
                //Ups Country Code Selection Modification done Bu asha On 26/11/2012
                if($destination_country=='UK')
                    {
                         $destination_country='GB';
                    }

                     if($origin_country=='UK')
                    {
                         $origin_country='GB';
                    }
                    // Remove Space from Zip Codes  Modified By Asha ON 22/11/2012

                      $destination_zip = preg_replace('/\s+/', '', $destination_zip);

                      $origin_zip = preg_replace('/\s+/', '', $origin_zip);
                      
                      $ups_types=array('1DM' => 'Next Day Air Early AM',
				 '1DA' => 'Next Day Air',
				 '1DP' => 'Next Day Air Saver',
				 '2DM' => '2nd Day Air Early AM',
				 '2DA' => '2nd Day Air',
				 '3DS' => '3 Day Select',
				 'GND' => 'UPS Ground',
				 'STD' => 'Canada Standard',
				 'XPR' => 'Worldwide Express',
				 'XDM' => 'Worldwide Express Plus',
				 'XPD' => 'Worldwide Expedited');

                $ups_shipping_weight = ($ups_shipping_weight < 0.1 ? 0.1 : $ups_shipping_weight);
                foreach($ups_types as $types=>$ups) {

                    $upsrate->upsProduct($types); // See upsProduct() function for codes

                    $upsrate->origin($origin_zip,$origin_country); // Use ISO country codes!

                    $upsrate->dest($destination_zip,$destination_country); // Use ISO country codes!

                    $upsrate->rate($ups_rate); // See the rate() function for codes

                    $upsrate->container($ups_container); // See the container() function for codes

                    $upsrate->weight(number_format($ups_shipping_weight,2,".",""));

                    $upsrate->rescom($ups_type); // See the rescom() function for codes

                    $quote = $upsrate->getQuote(); 

                    if($quote!="error" && $ups!="" && $quote!="") {
                        $resultShippingArray[$artist_id][]= array("service_name"=>$ups,"rate"=>$quote,"seller_name"=>$artistName,"seller_id"=>$artist_id);
                    }

                    // end price empty check

                }//end foreach
                break;
            CASE "AP":
            //weight in LBS

                foreach($australianServiceArray AS $eachService =>$eachServiceVal) {

                    $query = 'Pickup_Postcode='.$origin_zip;
                    $query .= '&Destination_Postcode='.$destination_zip;
                    $query .= '&Country='.$destination_country;
                    //LBS to gram Conversion - Santhosh thomas Alexander
                    //If the Site is customized and product weight is in grams then no need to convert
                    $query .= '&Weight='.number_format(($shipping_weight*0.454*1000),2);
                    $query .= '&Service_Type='.$eachService;
                    $query .= '&Length='.number_format(($product_length*10),2);
                    $query .= '&Width='.number_format(($product_width*10),2);
                    $query .= '&Height='.number_format(($product_height*10),2);
                    $query .= '&Quantity='.$quantity;
                    if($product_length<15)
                        $product_length = 15;
                    if($product_width<15)
                        $product_width = 15;
                    $girth =  (($product_height + $product_width)*2) + $product_length;
                   
                    $myfile = file('http://drc.edeliver.com.au/ratecalc.asp?'.$query);


                    $APchargeArray = split('=',$myfile[0]);
                    $charge = $APchargeArray[1];
                    $APerrorArray = split('=',$myfile[2]);
                    $strAPerrorMessage_epi = trim($APerrorArray[1]);
                    $errormessage[] = $strAPerrorMessage_epi;
                    if($strAPerrorMessage_epi=="OK") {
                        if($eachServiceVal !="" && $charge!="") {
                            $resultShippingArray[$artist_id][]= array("service_name"=>$eachServiceVal,"rate"=>$charge,"seller_name"=>$artistName,"seller_id"=>$artist_id);
                        }
                    }
                }                
                break;
            CASE "CP":
                $cPost = new CanadaPost();
                $cPost->setPrice($product_price);
                $cPost->setCustomer( array(
                        'city' => '',
                        'provOrState' =>$destination_state,
                        'country' => $destination_country,
                        'postalCode' => $destination_zip
                        )
                );
                $shipping_weight.$product_length.$product_width.$product_height;
                $cPost->addProduct ( array (
                        'quantity' =>$quantity,
                        'weight' =>$shipping_weight,
                        'length' =>$product_length,
                        'width' =>$product_width ,
                        'height' =>$product_height ,
                        'description' =>'Product Description'
                        )
                );
                $assoc_Array = array();
                $assoc_Array[$product_option_id] = $cPost->getRates('array');

                if($cPost->getErrorMessage()=="success") {
                    foreach($assoc_Array[$product_option_id]['product'] AS $canShipping) {
                        if($canShipping['name']!="" && $canShipping['rate']!="") {
                            $resultShippingArray[$artist_id][]= array("service_name"=>$canShipping['name'],"rate"=>$canShipping['rate'],"seller_name"=>$artistName,"seller_id"=>$artist_id);
                        }
                    }
                }


                break;
            case "Flat Rate":
                $queryFlatRate         = "SELECT * FROM ".$tableprefix."flat_rate_seller WHERE seller_id ='".$artist_id."'";
                $queryFlatRateQ        = mysql_query($queryFlatRate);
                if(mysql_num_rows($queryFlatRateQ)==0) {
                    $queryFlatRate     = "SELECT * FROM ".$tableprefix."flat_rate_default";
                    $queryFlatRateQ    = mysql_query($queryFlatRate);
                }
                while($flatRateObj = mysql_fetch_object($queryFlatRateQ)) {
                    $flat_rate_name = $flatRateObj->flat_rate_name;
                    $first_Item_charge = $flatRateObj->first_Item_charge;
                    $additional_Item_charge = $flatRateObj->additional_Item_charge;
                    $rate = $first_Item_charge+($additional_Item_charge*($quantity-1));
                    $resultShippingArray[$artist_id][]= array("service_name"=>stripslashes($flat_rate_name),"rate"=>$rate,"seller_name"=>$artistName,"seller_id"=>$artist_id);
                }
            DEFAULT:

        }
        // if the rate array is empty for other shipping Options check whether
        // admin has enabled the flat rate shipping so that customer can still
        // buy with the flat option.

        $Selected_Shipping_options  = $shippingTitle;
        if(empty($selectedShippingOption)) {
            $selectedShippingOption = $shippingTitle;
        }
       
        $shipping_options_availabe  = count($resultShippingArray[$artist_id]);

        if($shipping_options_availabe == 0 && $shippingOption!="Flat Rate") {
            if($flatrateEnabled=='Y' ) {
                $queryFlatRate         = "SELECT * FROM ".$tableprefix."flat_rate_seller WHERE seller_id ='".$artist_id."'";
                $queryFlatRateQ        = mysql_query($queryFlatRate);

                if(mysql_num_rows($queryFlatRateQ)==0) {
                    $queryFlatRate     = "SELECT * FROM ".$tableprefix."flat_rate_default";
                    $queryFlatRateQ    = mysql_query($queryFlatRate);
                }
                $shippingTitle = "Flat Rate Shipping" ;

                while($flatRateObj = mysql_fetch_object($queryFlatRateQ)) {
                    $flat_rate_name = $flatRateObj->flat_rate_name;
                    $first_Item_charge = $flatRateObj->first_Item_charge;
                    $additional_Item_charge = $flatRateObj->additional_Item_charge;
                    $rate = $first_Item_charge+($additional_Item_charge*($quantity-1));
                    $resultShippingArray[$artist_id][]= array("service_name"=>$flat_rate_name,"rate"=>$rate,"seller_name"=>$artistName,"seller_id"=>$artist_id);
                }
                ?>
                <?php
            }else{
                $shippingTitle = "No rates are available." ;
            }
        } 
    }//End lopp    
        $currentstatus['status'] = (!empty($resultShippingArray))?1:0;
        $currentstatus['data']['shipping_title']  = $shippingTitle;
        $currentstatus['data']   = $resultShippingArray;
        return($currentstatus); 
    }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
        return($currentstatus); 
    }
    
}

//---Get shipping options with the respective rates--//
function getShippingOptionsWithRatesAPI(){
    include "../includes/config.php";
    include "apifunctions.php";
    include_once("../usps/xmlparser.php"); 
    include_once("../shipping.php");
    include_once('../http_client.php');
    require_once("../includes/class.canadapost.php");

    //---Fedex--//
    ini_set("soap.wsdl_cache_enabled", "0");
    $path = $rootserver . "/images/";
    $requestType = stripslashes($_REQUEST['type']);
    $userId = stripslashes($_REQUEST['user_id']);
    $shippingCountry = stripslashes($_REQUEST['shippingCountry']);
    $shippingState = stripslashes($_REQUEST['shippingState']);
    $shippingZip = stripslashes($_REQUEST["shippingZip"]);
    $flatrateEnabled = getSettingsValue('enable_flatrate');
    if ($userId != NULL) {
        $sql = "SELECT * FROM " . $tableprefix . "settings ";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $shipRow = mysql_fetch_array($result);
        }
        /*if ($shipRow['enable_fedexshipping'] == "FDXG") {
            require_once '../library/class.fedex.php';
            require_once '../library/class.fedex.rate.php';
            require_once '../library/class.fedex.package.php';
            $sql = "select * from " . $tableprefix . "fedexsettings ";
            $rs = mysql_query($sql) or die(mysql_error());
            if (mysql_num_rows($rs) > 0) {
                $serviceName = array();
                $row = mysql_fetch_array($rs);
                $fedexaccno = stripslashes($row['FedexAccno']);
                $fedexmeterno = stripslashes($row['FedexMeterno']);
                $weightunits = $row['FedexWeight'];
                $server = $row['FedexServer'];
                $dropoff = stripslashes($row['FedexDropOff']);
                $packageTypes = stripslashes($row['FedexPackage']);
                $fedexPassword = stripslashes($row['FedexPassword']);
                $fedexKey = stripslashes($row['FedexKey']);
                $sName = $row['FedexService'];
                $currency = $row['FedexCurrency'];
                $sarry = $fedexGroundService;
            }
        }*/
        if ($shipRow['enable_uspsshipping'] == "Y") {
            include_once('../usps/usps.php');
            $sql = "select * from " . $tableprefix . "usps_settings ";
            $rs = mysql_query($sql) or die(mysql_error());
            if (mysql_num_rows($rs) > 0) {
                $row = mysql_fetch_array($rs);
                $uspsid = $row['username'];
                $server = $row['server'];
            } // end num rows check
        }
        if ($shipRow['enable_shipping'] == "Y") {
            // Shipping setting for UPS Shipping
            require("../ups.php");
            $select_shipping_settings = "SELECT * FROM " . $tableprefix . "shipping_settings";

            $result_shipping_settings = mysql_query($select_shipping_settings);
            if (mysql_num_rows($result_shipping_settings) > 0) {
                $rs_ship = mysql_fetch_array($result_shipping_settings);
                $ups_weight = $rs_ship['nShippingweight'];
                $ups_rate = $rs_ship['ups_rate'];
                $ups_container = $rs_ship['container_type'];
                $ups_type = $rs_ship['address_quote_method'];
            }
            $upsrate = new Ups;
        }

//--Get items from cart for current user --//
        $select_cart_details = "SELECT prd.product_id,prd.product_name,po.product_option_id,po.product_length,po.product_width,po.product_height,crt.quantity,
                       po.product_shipping_weight,art.country AS origin_country,art.state AS origin_state,art.zip AS origin_zip,art.artist_id,art.artist_name,
                       art.defaultflatrate,art.additionalflatrate
                       FROM " . $tableprefix . "cart crt
                       INNER JOIN " . $tableprefix . "product_options po ON crt.product_option_id = po.product_option_id
                       INNER JOIN " . $tableprefix . "products prd ON prd.product_id = po.product_id
                       INNER JOIN " . $tableprefix . "artists art ON art.artist_id = prd.product_artist_id
                       WHERE crt.user_id = " . $userId . " ORDER BY crt.cart_id";
        $result_cart_details = mysql_query($select_cart_details) or die(mysql_error());

        //Get shipping rates for various products
        while ($cart_details_data = mysql_fetch_assoc($result_cart_details)) {
            $artistId = $cart_details_data['artist_id'];
            $arrArtistId[] = $cart_details_data['artist_id'];
            $productDataArray[$artistId][] = $cart_details_data;
        }        
        foreach ($productDataArray as $cart_details_row) {

            // Seller Location (Source)
            $origin_country = $cart_details_row[0]['origin_country'];
            $origin_state = $cart_details_row[0]['origin_state'];
            $origin_zip = $cart_details_row[0]['origin_zip'];

            // User Location (Destination)
            $destination_country = $shippingCountry;
            $destination_state = $shippingState;
            $destination_zip = $shippingZip;

            // Seller Details
            $artist_id = $cart_details_row[0]['artist_id'];
            $artistName = $cart_details_row[0]['artist_name'];

            $quantity = 0;
            $shipping_weight = 0;
            $productSubArray = "";
            $productLength = "";
            $productHeight = "";
            $productWidth = "";
            // Product Details
            foreach ($cart_details_row as $pData) {

                $product_name = $pData['product_name'];
                $product_id = $pData['product_id'];
                $product_option_id = $pData['product_option_id'];
                $optionsStr = "";
                $optionVal = getProductOptionsName($product_option_id);
                if ($optionVal != "") {
                    $optionsStr = '<span class="spoptions">' . $optionVal . '</span>';
                }
                $productSubArray['productName'][$product_option_id] = '<span class="spname">' . $product_name . '</span>' . $optionsStr;

                $quantity += trim($pData['quantity']);


                $productLength[] = $pData['product_length'];
                $productHeight[] = $pData['product_height'];
                $productWidth[] = $pData['product_width'];

                $shipping_weight += trim($pData['product_shipping_weight']);
            }
            $productSubArray['artistName'] = $artistName;
            $product_length = max($productLength);
            $product_height = max($productHeight);
            $product_width = max($productWidth);
            $productArray[$artist_id] = $productSubArray;
            $fedex_shipping_weight = $shipping_weight * $quantity;

            //--Fedex--//
            /*if ($shipRow['enable_fedexshipping'] == "FDXG") {
                $objRates = new stdClass();
                $objRates->ship_account = trim($fedexaccno);
                $objRates->meter = trim($fedexmeterno);
                $objRates->password = trim($fedexPassword);
                $objRates->account = "";
                $objRates->bill_account = "";
                $objRates->duty_account = "";
                $objRates->account_to_validate = "";
                $objRates->track_account = "";
                $objRates->key = trim($fedexKey);
                $objRates->wsdl_path = "RateService_v9.wsdl";
                $objRate = new fedexRates();
                $objRate->requestType("rate");
                $objRate->setData($objRates);
                $objRate->wsdl_root_path = "../wsdl/";
                $client = new SoapClient($objRate->wsdl_root_path . $objRate->wsdl_path, array('trace' => 1));


                switch ($server) {
                    case "test":
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    case "production":
                        // change this to actual server when go on live
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    default:
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                }

                $aryShipper = array(
                    'Contact' => array(
                        'PersonName' => 'Sender Name',
                        'CompanyName' => 'Sender Company Name',
                        'PhoneNumber' => '9012638716'),
                    'Address' => array(
                        'StreetLines' => array('Address Line 1'),
                        'City' => $origin_city,
                        'StateOrProvinceCode' => $origin_state,
                        'PostalCode' => $origin_zip,
                        'CountryCode' => $origin_country)
                );

                $aryRecipient = array(
                    'Contact' => array(
                        'PersonName' => 'Recipient Name',
                        'CompanyName' => 'Company Name',
                        'PhoneNumber' => '9012637906'
                    ),
                    'Address' => array(
                        'StreetLines' => array('Address Line 1'),
                        'City' => $destination_city,
                        'StateOrProvinceCode' => $destination_state,
                        'PostalCode' => $destination_zip,
                        'CountryCode' => $destination_country,
                        'Residential' => false)
                );


                $fedexService = array('PRIORITY_OVERNIGHT', 'STANDARD_OVERNIGHT', 'INTERNATIONAL_PRIORITY', 'FEDEX_GROUND', 'FIRST_OVERNIGHT', 'FEDEX2DAY');
                $rateResponseArr = array();


                foreach ($fedexService as $serviceNames) {
                    $packages = array();

                    $aryPackage = array();

                    $total_packages = 1;

                    if ($product_length == 0 || $product_length > 70) {
                        $product_length = '17.88';
                    }

                    if ($product_width == 0 || $product_width > 70) {
                        $product_width = '12.88';
                    }

                    if ($product_height == 0 || $product_height > 10) {
                        $product_height = '3.00';
                    }


                    $packages[0] = new Package("FEDEX Package # 1", $total_packages, 1);
                    $packages[0]->setPackageWeight($fedex_shipping_weight);     //Package Actual Weight
                    $packages[0]->setPackageDimensions($product_length, $product_width, $product_height);       //Package (Length x Width x Height)
                    $aryPackage[0] = $packages[0]->getObjectArray();

                    $aryOrder = array(
                        'TotalPackages' => $total_packages,
                        'PackageType' => 'YOUR_PACKAGING', #FEDEX_10KG_BOX, FEDEX_25KG_BOX, FEDEX_BOX, FEDEX_ENVELOPE, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
                        'ServiceType' => $serviceNames,
                        'TermsOfSaleType' => "DDU", #    DDU/DDP
                        'DropoffType' => 'REGULAR_PICKUP'         # BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER, STATION
                    );

                    $request = $objRate->rateRequest($aryRecipient, $aryShipper, $aryOrder, $aryPackage);
                    $rateResponseArr[] = $objRate->getRates($request, $client);
                }

                if (!empty($rateResponseArr)) {
                    foreach ($rateResponseArr as $serviceVals) {
                        if (@$serviceVals->error == '' && $serviceVals->ServiceName != '')
                            $resultShippingArray[0][$artist_id][] = array("service_name" => @$serviceVals->ServiceName, "rate" => @$serviceVals->amount, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Fedex Express Ground Shipping", "shipping_img" => $path . "fedex.gif");
                    }
                }
            }*/
            //-- Fedex ends --//        
            //--USPS--//
            if ($shipRow['enable_uspsshipping'] == "Y") {
                $uspsRequired_Service = array("Express Mail", "Express Mail Hold For Pickup", "Express Mail Sunday/Holiday Delivery", "Priority Mail", "Parcel Post", "Priority Mail Large Flat Rate Box", "
        Priority Mail Express 2-Day", "Priority Mail 2-Day", "Priority Mail 2-Day Small Flat Rate Box", "Media Mail", "Library Mail");
                switch ($server) {
                    case "test":
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                    case "production":
                        //change this line when usps is on live 
                        $uspsserver = "http://production.shippingapis.com/ShippingAPI.dll";
                        break;
                    default :
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                } // end switch      
                $usps_shipping_weight = $shipping_weight * $quantity;

                if ($usps_shipping_weight < 1) {
                    $usps_shipping_weight = 1;
                }
                $usps_shipping_weightSplit = explode(".", $usps_shipping_weight);
                $shipping_pounds = $usps_shipping_weightSplit[0];
                $ouncelength = count_digit($usps_shipping_weightSplit[1]);
                if ($ouncelength == 0) {
                    $shipping_ounces = 0;
                }
                if ($ouncelength == 1) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10) * 16;
                }
                if ($ouncelength == 2) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 100) * 16;
                }
                if ($ouncelength == 3) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 1000) * 16;
                }
                if ($ouncelength == 4) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10000) * 16;
                }

                $usps = new USPS;
                if ($server == "test") {
                    $usps->setWeight(10, 5);
                    $usps->setDestZip("20008");
                    $usps->setOrigZip("10022");
                } else {
                    $usps->setDestZip($destination_zip);
                    $usps->setOrigZip($origin_zip);
                    $usps->setWeight($shipping_pounds, $shipping_ounces);
                }

                $usps->setServer($uspsserver);
                $usps->setUserName($uspsid);
                $uspspaswd = "";
                $usps->setPass($uspspaswd);
                $usps->setService("All");

                $usps->setCountry("USA");

                $usps->setMachinable("true");

                $usps->setSize("REGULAR");

                $uspsprice = array();

                $uspsprice = $usps->getPrice();


                $special_chars = "&lt;sup&gt;&amp;reg;&lt;/sup&gt;";
                if ($uspsprice->error->description == "") {

                    foreach ($uspsprice->list AS $key => $eachItem) {
                        if ($eachItem->mailservice != "" && $eachItem->rate != "") {
                            //$eachItemServicename = str_replace($special_chars,"",$eachItem->mailservice);
                            $eachItemServicename = @htmlspecialchars_decode($eachItem->mailservice);
                            $eachItemServicename = @preg_replace("/<sup>(.*?)<\/sup>/i", "", $eachItemServicename);
                            if (in_array($eachItemServicename, $uspsRequired_Service)) {
                                $resultShippingArray[1][$artist_id][] = array("service_name" => $eachItemServicename, "rate" => $eachItem->rate, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "USPS Shipping", "shipping_img" => $path . "usps.gif");
                            }
                        }
                    }
                }
            }
            //--USPS Ends--//     
            //--UPS--//        
            if ($shipRow['enable_shipping'] == "Y") {
                $ups_shipping_weight = $shipping_weight * $quantity;

                //Ups Country Code Selection Modification done Bu asha On 26/11/2012
                if ($destination_country == 'UK') {
                    $destination_country = 'GB';
                }

                if ($origin_country == 'UK') {
                    $origin_country = 'GB';
                }
                // Remove Space from Zip Codes  Modified By Asha ON 22/11/2012

                $destination_zip = preg_replace('/\s+/', '', $destination_zip);

                $origin_zip = preg_replace('/\s+/', '', $origin_zip);

                $ups_types = array('1DM' => 'Next Day Air Early AM',
                    '1DA' => 'Next Day Air',
                    '1DP' => 'Next Day Air Saver',
                    '2DM' => '2nd Day Air Early AM',
                    '2DA' => '2nd Day Air',
                    '3DS' => '3 Day Select',
                    'GND' => 'UPS Ground',
                    'STD' => 'Canada Standard',
                    'XPR' => 'Worldwide Express',
                    'XDM' => 'Worldwide Express Plus',
                    'XPD' => 'Worldwide Expedited');

                $ups_shipping_weight = ($ups_shipping_weight < 0.1 ? 0.1 : $ups_shipping_weight);
                foreach ($ups_types as $types => $ups) {

                    $upsrate->upsProduct($types); // See upsProduct() function for codes

                    $upsrate->origin($origin_zip, $origin_country); // Use ISO country codes!

                    $upsrate->dest($destination_zip, $destination_country); // Use ISO country codes!

                    $upsrate->rate($ups_rate); // See the rate() function for codes

                    $upsrate->container($ups_container); // See the container() function for codes

                    $upsrate->weight(number_format($ups_shipping_weight, 2, ".", ""));

                    $upsrate->rescom($ups_type); // See the rescom() function for codes

                    $quote = $upsrate->getQuote();

                    if ($quote != "error" && $ups != "" && $quote != "") {
                        $resultShippingArray[2][$artist_id][] = array("service_name" => $ups, "rate" => $quote, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "UPS Shipping", "shipping_img" => $path . "ups.gif");
                    }

                    // end price empty check
                }//end foreach
            }
            //--UPS ends--//
            //-- AP --//
            /*if ($shipRow['enable_australiapost'] == "Y") {
                $australianServiceArray = array("STANDARD" => "Standard Post", "EXPRESS" => "Express Post", "AIR" => "Air Post", "SEA" => "Sea Post");
                foreach ($australianServiceArray AS $eachService => $eachServiceVal) {

                    $query = 'Pickup_Postcode=' . $origin_zip;
                    $query .= '&Destination_Postcode=' . $destination_zip;
                    $query .= '&Country=' . $destination_country;
                    //LBS to gram Conversion - Santhosh thomas Alexander
                    //If the Site is customized and product weight is in grams then no need to convert
                    $query .= '&Weight=' . number_format(($shipping_weight * 0.454 * 1000), 2);
                    $query .= '&Service_Type=' . $eachService;
                    $query .= '&Length=' . number_format(($product_length * 10), 2);
                    $query .= '&Width=' . number_format(($product_width * 10), 2);
                    $query .= '&Height=' . number_format(($product_height * 10), 2);
                    $query .= '&Quantity=' . $quantity;
                    if ($product_length < 15)
                        $product_length = 15;
                    if ($product_width < 15)
                        $product_width = 15;
                    $girth = (($product_height + $product_width) * 2) + $product_length;

                    $myfile = file('http://drc.edeliver.com.au/ratecalc.asp?' . $query);


                    $APchargeArray = split('=', $myfile[0]);
                    $charge = $APchargeArray[1];
                    $APerrorArray = split('=', $myfile[2]);
                    $strAPerrorMessage_epi = trim($APerrorArray[1]);
                    $errormessage[] = $strAPerrorMessage_epi;
                    if ($strAPerrorMessage_epi == "OK") {
                        if ($eachServiceVal != "" && $charge != "") {
                            $resultShippingArray[3][$artist_id][] = array("service_name" => $eachServiceVal, "rate" => $charge, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Australian Post Shipping", "shipping_img" => $path . "australiapost.jpg");
                        }
                    }
                }
            }*/
            //-- AP Ends --//    
            //--Canada Post--//
            if ($shipRow['enable_canadapost'] == "Y") {
                $cPost = new CanadaPost();
                $cPost->setPrice($product_price);
                $cPost->setCustomer(array(
                    'city' => '',
                    'provOrState' => $destination_state,
                    'country' => $destination_country,
                    'postalCode' => $destination_zip
                        )
                );
                $shipping_weight . $product_length . $product_width . $product_height;
                $cPost->addProduct(array(
                    'quantity' => $quantity,
                    'weight' => $shipping_weight,
                    'length' => $product_length,
                    'width' => $product_width,
                    'height' => $product_height,
                    'description' => 'Product Description'
                        )
                );
                $assoc_Array = array();
                $assoc_Array[$product_option_id] = $cPost->getRates('array');

                if ($cPost->getErrorMessage() == "success") {
                    foreach ($assoc_Array[$product_option_id]['product'] AS $canShipping) {
                        if ($canShipping['name'] != "" && $canShipping['rate'] != "") {
                            $resultShippingArray[4][$artist_id][] = array("service_name" => $canShipping['name'], "rate" => $canShipping['rate'], "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Canada Post Shipping", "shipping_img" => $path . "canadapost.gif");
                        }
                    }
                }
            }
            //--Canada Post Ends--//
            //--Flat Rate--//
            if ($shipRow['enable_flatrate'] == "Y") {
                $queryFlatRate = "SELECT * FROM " . $tableprefix . "flat_rate_seller WHERE seller_id ='" . $artist_id . "'";
                $queryFlatRateQ = mysql_query($queryFlatRate);
                if (mysql_num_rows($queryFlatRateQ) == 0) {
                    $queryFlatRate = "SELECT * FROM " . $tableprefix . "flat_rate_default";
                    $queryFlatRateQ = mysql_query($queryFlatRate);
                }
                while ($flatRateObj = mysql_fetch_object($queryFlatRateQ)) {
                    $flat_rate_name = $flatRateObj->flat_rate_name;
                    $first_Item_charge = $flatRateObj->first_Item_charge;
                    $additional_Item_charge = $flatRateObj->additional_Item_charge;
                    $rate = $first_Item_charge + ($additional_Item_charge * ($quantity - 1));
                    $resultShippingArray[5][$artist_id][] = array("service_name" => stripslashes($flat_rate_name), "rate" => $rate, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Our Shipping", "shipping_img" => "");
                }
            }
            //--Flat Rate--//
        }
        if ($requestType == "lowest") {
            $cheapestRate = 50000;
            foreach ($arrArtistId as $sellerId) {
                foreach ($resultShippingArray as $key => $value) {                
                    foreach ($value[$sellerId] as $ky => $val) {
                        if ($val['rate'] < $cheapestRate) {
                            $cheapestRate = $val['rate'];
                            $shippingRes = array("service_name" => $val['service_name'], "rate" => $val['rate'], "seller_name" => $val['seller_name'], "seller_id" => $val['seller_id'], "shipping_title" => $val['shipping_title'], "shipping_img" => $val['shipping_img']);
                        }
                    }
                }
                $shippingTot = $shippingTot + $cheapestRate;
            }//End lopp    
            $shippingRes['rate'] = $shippingTot;            
        }
        $currentstatus['status'] = 1;
        $currentstatus['data'] = ($requestType == "lowest") ? $shippingRes : $resultShippingArray;
        return($currentstatus);
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
        return($currentstatus);
    }
    
}
/////////////////////////////////
//---Get all shipping options with the respective rates--//
function getAllShippingOptionsWithRatesAPI(){
    include "../includes/config.php";
    include "apifunctions.php";
    include_once("../usps/xmlparser.php"); 
    include_once("../shipping.php");
    include_once('../http_client.php');
    require_once("../includes/class.canadapost.php");

    //---Fedex--//
    ini_set("soap.wsdl_cache_enabled", "0");
    $path = $rootserver . "/images/";    
    $userId = stripslashes($_REQUEST['user_id']);
    $shippingCountry = stripslashes($_REQUEST['shippingCountry']);
    $shippingState = stripslashes($_REQUEST['shippingState']);
    $shippingZip = stripslashes($_REQUEST["shippingZip"]);
    $flatrateEnabled = getSettingsValue('enable_flatrate');
    if ($userId != NULL) {
        $sql = "SELECT * FROM " . $tableprefix . "settings ";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) != 0) {
            $shipRow = mysql_fetch_array($result);
        }
        /*if ($shipRow['enable_fedexshipping'] == "FDXG") {
            require_once '../library/class.fedex.php';
            require_once '../library/class.fedex.rate.php';
            require_once '../library/class.fedex.package.php';
            $sql = "select * from " . $tableprefix . "fedexsettings ";
            $rs = mysql_query($sql) or die(mysql_error());
            if (mysql_num_rows($rs) > 0) {
                $serviceName = array();
                $row = mysql_fetch_array($rs);
                $fedexaccno = stripslashes($row['FedexAccno']);
                $fedexmeterno = stripslashes($row['FedexMeterno']);
                $weightunits = $row['FedexWeight'];
                $server = $row['FedexServer'];
                $dropoff = stripslashes($row['FedexDropOff']);
                $packageTypes = stripslashes($row['FedexPackage']);
                $fedexPassword = stripslashes($row['FedexPassword']);
                $fedexKey = stripslashes($row['FedexKey']);
                $sName = $row['FedexService'];
                $currency = $row['FedexCurrency'];
                $sarry = $fedexGroundService;
            }
        }*/
        if ($shipRow['enable_uspsshipping'] == "Y") {
            include_once('../usps/usps.php');
            $sql = "select * from " . $tableprefix . "usps_settings ";
            $rs = mysql_query($sql) or die(mysql_error());
            if (mysql_num_rows($rs) > 0) {
                $row = mysql_fetch_array($rs);
                $uspsid = $row['username'];
                $server = $row['server'];
            } // end num rows check
        }
        if ($shipRow['enable_shipping'] == "Y") {
            // Shipping setting for UPS Shipping
            require("../ups.php");
            $select_shipping_settings = "SELECT * FROM " . $tableprefix . "shipping_settings";

            $result_shipping_settings = mysql_query($select_shipping_settings);
            if (mysql_num_rows($result_shipping_settings) > 0) {
                $rs_ship = mysql_fetch_array($result_shipping_settings);
                $ups_weight = $rs_ship['nShippingweight'];
                $ups_rate = $rs_ship['ups_rate'];
                $ups_container = $rs_ship['container_type'];
                $ups_type = $rs_ship['address_quote_method'];
            }
            $upsrate = new Ups;
        }
        //--Get items from cart for current user --//
        $select_cart_details = "SELECT prd.product_id,prd.product_name,po.product_option_id,po.product_length,po.product_width,po.product_height,crt.quantity,
                       po.product_shipping_weight,art.country AS origin_country,art.state AS origin_state,art.zip AS origin_zip,art.artist_id,art.artist_name,
                       art.defaultflatrate,art.additionalflatrate
                       FROM " . $tableprefix . "cart crt
                       INNER JOIN " . $tableprefix . "product_options po ON crt.product_option_id = po.product_option_id
                       INNER JOIN " . $tableprefix . "products prd ON prd.product_id = po.product_id
                       INNER JOIN " . $tableprefix . "artists art ON art.artist_id = prd.product_artist_id
                       WHERE crt.user_id = " . $userId . " ORDER BY crt.cart_id";
        $result_cart_details = mysql_query($select_cart_details) or die(mysql_error());

        //Get shipping rates for various products
        while ($cart_details_data = mysql_fetch_assoc($result_cart_details)) {
            $artistId = $cart_details_data['artist_id'];
            $arrArtistId[] = $cart_details_data['artist_id'];
            $productDataArray[$artistId][] = $cart_details_data;
        }   
      
        foreach ($productDataArray as $cart_details_row) {

            // Seller Location (Source)
            $origin_country = $cart_details_row[0]['origin_country'];
            $origin_state = $cart_details_row[0]['origin_state'];
            $origin_zip = $cart_details_row[0]['origin_zip'];

            // User Location (Destination)
            $destination_country = $shippingCountry;
            $destination_state = $shippingState;
            $destination_zip = $shippingZip;

            // Seller Details
            $artist_id = $cart_details_row[0]['artist_id'];
            $artistName = $cart_details_row[0]['artist_name'];

            $quantity = 0;
            $shipping_weight = 0;
            $productSubArray = "";
            $productLength = "";
            $productHeight = "";
            $productWidth = "";
            // Product Details
            foreach ($cart_details_row as $pData) {

                $product_name = $pData['product_name'];
                $product_id = $pData['product_id'];
                $product_option_id = $pData['product_option_id'];
                $optionsStr = "";
                $optionVal = getProductOptionsName($product_option_id);
                if ($optionVal != "") {
                    $optionsStr = '<span class="spoptions">' . $optionVal . '</span>';
                }
                $productSubArray['productName'][$product_option_id] = '<span class="spname">' . $product_name . '</span>' . $optionsStr;

                $quantity += trim($pData['quantity']);


                $productLength[] = $pData['product_length'];
                $productHeight[] = $pData['product_height'];
                $productWidth[] = $pData['product_width'];

                $shipping_weight += trim($pData['product_shipping_weight']);
            }
            $productSubArray['artistName'] = $artistName;
            $product_length = max($productLength);
            $product_height = max($productHeight);
            $product_width = max($productWidth);
            $productArray[$artist_id] = $productSubArray;
            $fedex_shipping_weight = $shipping_weight * $quantity;

            //--Fedex--//
            /*if ($shipRow['enable_fedexshipping'] == "FDXG") {
                $objRates = new stdClass();
                $objRates->ship_account = trim($fedexaccno);
                $objRates->meter = trim($fedexmeterno);
                $objRates->password = trim($fedexPassword);
                $objRates->account = "";
                $objRates->bill_account = "";
                $objRates->duty_account = "";
                $objRates->account_to_validate = "";
                $objRates->track_account = "";
                $objRates->key = trim($fedexKey);
                $objRates->wsdl_path = "RateService_v9.wsdl";
                $objRate = new fedexRates();
                $objRate->requestType("rate");
                $objRate->setData($objRates);
                $objRate->wsdl_root_path = "../wsdl/";
                $client = new SoapClient($objRate->wsdl_root_path . $objRate->wsdl_path, array('trace' => 1));
                switch ($server) {
                    case "test":
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    case "production":
                        // change this to actual server when go on live
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                    default:
                        $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
                        break;
                }

                $aryShipper = array(
                    'Contact' => array(
                        'PersonName' => 'Sender Name',
                        'CompanyName' => 'Sender Company Name',
                        'PhoneNumber' => '9012638716'),
                    'Address' => array(
                        'StreetLines' => array('Address Line 1'),
                        'City' => $origin_city,
                        'StateOrProvinceCode' => $origin_state,
                        'PostalCode' => $origin_zip,
                        'CountryCode' => $origin_country)
                );

                $aryRecipient = array(
                    'Contact' => array(
                        'PersonName' => 'Recipient Name',
                        'CompanyName' => 'Company Name',
                        'PhoneNumber' => '9012637906'
                    ),
                    'Address' => array(
                        'StreetLines' => array('Address Line 1'),
                        'City' => $destination_city,
                        'StateOrProvinceCode' => $destination_state,
                        'PostalCode' => $destination_zip,
                        'CountryCode' => $destination_country,
                        'Residential' => false)
                );


                $fedexService = array('PRIORITY_OVERNIGHT', 'STANDARD_OVERNIGHT', 'INTERNATIONAL_PRIORITY', 'FEDEX_GROUND', 'FIRST_OVERNIGHT', 'FEDEX2DAY');
                $rateResponseArr = array();


                foreach ($fedexService as $serviceNames) {
                    $packages = array();

                    $aryPackage = array();

                    $total_packages = 1;

                    if ($product_length == 0 || $product_length > 70) {
                        $product_length = '17.88';
                    }

                    if ($product_width == 0 || $product_width > 70) {
                        $product_width = '12.88';
                    }

                    if ($product_height == 0 || $product_height > 10) {
                        $product_height = '3.00';
                    }


                    $packages[0] = new Package("FEDEX Package # 1", $total_packages, 1);
                    $packages[0]->setPackageWeight($fedex_shipping_weight);     //Package Actual Weight
                    $packages[0]->setPackageDimensions($product_length, $product_width, $product_height);       //Package (Length x Width x Height)
                    $aryPackage[0] = $packages[0]->getObjectArray();

                    $aryOrder = array(
                        'TotalPackages' => $total_packages,
                        'PackageType' => 'YOUR_PACKAGING', #FEDEX_10KG_BOX, FEDEX_25KG_BOX, FEDEX_BOX, FEDEX_ENVELOPE, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
                        'ServiceType' => $serviceNames,
                        'TermsOfSaleType' => "DDU", #    DDU/DDP
                        'DropoffType' => 'REGULAR_PICKUP'         # BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER, STATION
                    );

                    $request = $objRate->rateRequest($aryRecipient, $aryShipper, $aryOrder, $aryPackage);
                    $rateResponseArr[] = $objRate->getRates($request, $client);
                }

                if (!empty($rateResponseArr)) {
                    foreach ($rateResponseArr as $serviceVals) {
                        if (@$serviceVals->error == '' && $serviceVals->ServiceName != '')
                            $resultShippingArray[0][$artist_id][] = array("service_name" => @$serviceVals->ServiceName, "rate" => @$serviceVals->amount, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Fedex Express Ground Shipping", "shipping_img" => $path . "fedex.gif");
                    }
                }
            }*/
            //-- Fedex ends --//        
            //--USPS--//
            if ($shipRow['enable_uspsshipping'] == "Y") {
                $uspsRequired_Service = array("Express Mail", "Express Mail Hold For Pickup", "Express Mail Sunday/Holiday Delivery", "Priority Mail", "Parcel Post", "Priority Mail Large Flat Rate Box", "
        Priority Mail Express 2-Day", "Priority Mail 2-Day", "Priority Mail 2-Day Small Flat Rate Box", "Media Mail", "Library Mail");
                switch ($server) {
                    case "test":
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                    case "production":
                        //change this line when usps is on live 
                        $uspsserver = "http://production.shippingapis.com/ShippingAPI.dll";
                        break;
                    default :
                        $uspsserver = "http://stg-production.shippingapis.com/ShippingAPI.dll";
                        break;
                } // end switch      
                $usps_shipping_weight = $shipping_weight * $quantity;

                if ($usps_shipping_weight < 1) {
                    $usps_shipping_weight = 1;
                }
                $usps_shipping_weightSplit = explode(".", $usps_shipping_weight);
                $shipping_pounds = $usps_shipping_weightSplit[0];
                $ouncelength = count_digit($usps_shipping_weightSplit[1]);
                if ($ouncelength == 0) {
                    $shipping_ounces = 0;
                }
                if ($ouncelength == 1) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10) * 16;
                }
                if ($ouncelength == 2) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 100) * 16;
                }
                if ($ouncelength == 3) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 1000) * 16;
                }
                if ($ouncelength == 4) {
                    $shipping_ounces = ($usps_shipping_weightSplit[1] / 10000) * 16;
                }

                $usps = new USPS;
                if ($server == "test") {
                    $usps->setWeight(10, 5);
                    $usps->setDestZip("20008");
                    $usps->setOrigZip("10022");
                } else {
                    $usps->setDestZip($destination_zip);
                    $usps->setOrigZip($origin_zip);
                    $usps->setWeight($shipping_pounds, $shipping_ounces);
                }

                $usps->setServer($uspsserver);
                $usps->setUserName($uspsid);
                $uspspaswd = "";
                $usps->setPass($uspspaswd);
                $usps->setService("All");

                $usps->setCountry("USA");

                $usps->setMachinable("true");

                $usps->setSize("REGULAR");

                $uspsprice = array();

                $uspsprice = $usps->getPrice();


                $special_chars = "&lt;sup&gt;&amp;reg;&lt;/sup&gt;";
                if ($uspsprice->error->description == "") {

                    foreach ($uspsprice->list AS $key => $eachItem) {
                        if ($eachItem->mailservice != "" && $eachItem->rate != "") {
                            //$eachItemServicename = str_replace($special_chars,"",$eachItem->mailservice);
                            $eachItemServicename = @htmlspecialchars_decode($eachItem->mailservice);
                            $eachItemServicename = @preg_replace("/<sup>(.*?)<\/sup>/i", "", $eachItemServicename);
                            if (in_array($eachItemServicename, $uspsRequired_Service)) {
                                $resultShippingArray[1][$artist_id][] = array("service_name" => $eachItemServicename, "rate" => $eachItem->rate, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "USPS Shipping", "shipping_img" => $path . "usps.gif");
                            }
                        }
                    }
                }
            }
            //--USPS Ends--//     
            //--UPS--//        
            if ($shipRow['enable_shipping'] == "Y") {
                $ups_shipping_weight = $shipping_weight * $quantity;

                //Ups Country Code Selection Modification done Bu asha On 26/11/2012
                if ($destination_country == 'UK') {
                    $destination_country = 'GB';
                }

                if ($origin_country == 'UK') {
                    $origin_country = 'GB';
                }
                // Remove Space from Zip Codes  Modified By Asha ON 22/11/2012

                $destination_zip = preg_replace('/\s+/', '', $destination_zip);

                $origin_zip = preg_replace('/\s+/', '', $origin_zip);

                $ups_types = array('1DM' => 'Next Day Air Early AM',
                    '1DA' => 'Next Day Air',
                    '1DP' => 'Next Day Air Saver',
                    '2DM' => '2nd Day Air Early AM',
                    '2DA' => '2nd Day Air',
                    '3DS' => '3 Day Select',
                    'GND' => 'UPS Ground',
                    'STD' => 'Canada Standard',
                    'XPR' => 'Worldwide Express',
                    'XDM' => 'Worldwide Express Plus',
                    'XPD' => 'Worldwide Expedited');

                $ups_shipping_weight = ($ups_shipping_weight < 0.1 ? 0.1 : $ups_shipping_weight);
                foreach ($ups_types as $types => $ups) {

                    $upsrate->upsProduct($types); // See upsProduct() function for codes

                    $upsrate->origin($origin_zip, $origin_country); // Use ISO country codes!

                    $upsrate->dest($destination_zip, $destination_country); // Use ISO country codes!

                    $upsrate->rate($ups_rate); // See the rate() function for codes

                    $upsrate->container($ups_container); // See the container() function for codes

                    $upsrate->weight(number_format($ups_shipping_weight, 2, ".", ""));

                    $upsrate->rescom($ups_type); // See the rescom() function for codes

                    $quote = $upsrate->getQuote();

                    if ($quote != "error" && $ups != "" && $quote != "") {
                        $resultShippingArray[2][$artist_id][] = array("service_name" => $ups, "rate" => $quote, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "UPS Shipping", "shipping_img" => $path . "ups.gif");
                    }

                    // end price empty check
                }//end foreach
            }
            //--UPS ends--//
            //-- AP --//
            /*if ($shipRow['enable_australiapost'] == "Y") {
                $australianServiceArray = array("STANDARD" => "Standard Post", "EXPRESS" => "Express Post", "AIR" => "Air Post", "SEA" => "Sea Post");
                foreach ($australianServiceArray AS $eachService => $eachServiceVal) {

                    $query = 'Pickup_Postcode=' . $origin_zip;
                    $query .= '&Destination_Postcode=' . $destination_zip;
                    $query .= '&Country=' . $destination_country;
                    //LBS to gram Conversion - Santhosh thomas Alexander
                    //If the Site is customized and product weight is in grams then no need to convert
                    $query .= '&Weight=' . number_format(($shipping_weight * 0.454 * 1000), 2);
                    $query .= '&Service_Type=' . $eachService;
                    $query .= '&Length=' . number_format(($product_length * 10), 2);
                    $query .= '&Width=' . number_format(($product_width * 10), 2);
                    $query .= '&Height=' . number_format(($product_height * 10), 2);
                    $query .= '&Quantity=' . $quantity;
                    if ($product_length < 15)
                        $product_length = 15;
                    if ($product_width < 15)
                        $product_width = 15;
                    $girth = (($product_height + $product_width) * 2) + $product_length;

                    $myfile = file('http://drc.edeliver.com.au/ratecalc.asp?' . $query);


                    $APchargeArray = split('=', $myfile[0]);
                    $charge = $APchargeArray[1];
                    $APerrorArray = split('=', $myfile[2]);
                    $strAPerrorMessage_epi = trim($APerrorArray[1]);
                    $errormessage[] = $strAPerrorMessage_epi;
                    if ($strAPerrorMessage_epi == "OK") {
                        if ($eachServiceVal != "" && $charge != "") {
                            $resultShippingArray[3][$artist_id][] = array("service_name" => $eachServiceVal, "rate" => $charge, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Australian Post Shipping", "shipping_img" => $path . "australiapost.jpg");
                        }
                    }
                }
            }*/
            //-- AP Ends --//    
            //--Canada Post--//
            if ($shipRow['enable_canadapost'] == "Y") {
                $cPost = new CanadaPost();
                $cPost->setPrice($product_price);
                $cPost->setCustomer(array(
                    'city' => '',
                    'provOrState' => $destination_state,
                    'country' => $destination_country,
                    'postalCode' => $destination_zip
                        )
                );
                $shipping_weight . $product_length . $product_width . $product_height;
                $cPost->addProduct(array(
                    'quantity' => $quantity,
                    'weight' => $shipping_weight,
                    'length' => $product_length,
                    'width' => $product_width,
                    'height' => $product_height,
                    'description' => 'Product Description'
                        )
                );
                $assoc_Array = array();
                $assoc_Array[$product_option_id] = $cPost->getRates('array');

                if ($cPost->getErrorMessage() == "success") {
                    foreach ($assoc_Array[$product_option_id]['product'] AS $canShipping) {
                        if ($canShipping['name'] != "" && $canShipping['rate'] != "") {
                            $resultShippingArray[4][$artist_id][] = array("service_name" => $canShipping['name'], "rate" => $canShipping['rate'], "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Canada Post Shipping", "shipping_img" => $path . "canadapost.gif");
                        }
                    }
                }
            }
            //--Canada Post Ends--//
            //--Flat Rate--//
            if ($shipRow['enable_flatrate'] == "Y") {
                $queryFlatRate = "SELECT * FROM " . $tableprefix . "flat_rate_seller WHERE seller_id ='" . $artist_id . "'";
                $queryFlatRateQ = mysql_query($queryFlatRate);
                if (mysql_num_rows($queryFlatRateQ) == 0) {
                    $queryFlatRate = "SELECT * FROM " . $tableprefix . "flat_rate_default";
                    $queryFlatRateQ = mysql_query($queryFlatRate);
                }
                while ($flatRateObj = mysql_fetch_object($queryFlatRateQ)) {
                    $flat_rate_name = $flatRateObj->flat_rate_name;
                    $first_Item_charge = $flatRateObj->first_Item_charge;
                    $additional_Item_charge = $flatRateObj->additional_Item_charge;
                    $rate = $first_Item_charge + ($additional_Item_charge * ($quantity - 1));
                    $resultShippingArray[5][$artist_id][] = array("service_name" => stripslashes($flat_rate_name), "rate" => $rate, "seller_name" => $artistName, "seller_id" => $artist_id, "shipping_title" => "Our Shipping", "shipping_img" => "");
                }
            }
            //--Flat Rate--//
        }
       
        if(count($arrArtistId)>1){    
            $shipFlg=0;
            foreach ($resultShippingArray as $key => $value) {
                if($shipFlg==1){$shipFlg=0;break;}
                foreach ($arrArtistId as $sellerId) {               
                    if($shipFlg==1){$shipFlg=0;break;}
                    for ($c = 0; $c <= count($value[$sellerId]); $c++) {
                        $sum = 0;
                        foreach ($arrArtistId as $sellerService) {
                            $sum = $sum + $value[$sellerService][$c]['rate']; // Same Service rate for multiple products/sellers are added up
                        }
                        if($value[$sellerId][$c]['service_name']==NULL){$shipFlg=1;break;}
                        $shippingRes[$key][] = array("service_name" => $value[$sellerId][$c]['service_name'], "rate" => $sum, "seller_name" => $value[$sellerId][$c]['seller_name'], "seller_id" => $value[$sellerId][$c]['seller_id'], "shipping_title" => $value[$sellerId][$c]['shipping_title'], "shipping_img" => $value[$sellerId][$c]['shipping_img']);                   
                    }
                }
            }//End lopp    
        }else{//--for single seller--//
            foreach ($resultShippingArray as $key => $value) {     
               
                foreach ($value[$arrArtistId[0]] as $service) {  
                    $shippingRes[$key][] = array("service_name" => $service['service_name'], "rate" => $service['rate'], "seller_name" => $service['seller_name'], "seller_id" => $service['seller_id'], "shipping_title" => $service['shipping_title'], "shipping_img" => $service['shipping_img']);                   
                }  
         
            } 
        }
        
        $currentstatus['status'] = 1;
        $currentstatus['data'] = $shippingRes;
        return($currentstatus);
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
        return($currentstatus);
    }
    
}
//////////////////////////////////
//-- Get payment options enable and order total after selecting shipping --//
function getPaymentoptionsAndTotalAPI(){
    include "../includes/config.php";
    include "apifunctions.php";
    $path = $rootserver."/images/";
    $selected_shipping       = json_decode(stripslashes($_REQUEST['shipping_selected']));    
    $userId         = stripslashes($_REQUEST['user_id']);   
    $shippingMethod = $_REQUEST['shipping_method'];
    $flatrateEnabled= getSettingsValue('enable_flatrate');
    $paypalEmail    = getSettingsValue('paypalemail');
    $paypalSandbox  = getSettingsValue('enablepaypalsandbox');
    $paypalSplitPayment = getSettingsValue('enable_buyerToseller');   
        
    $paymentGateways[0]['name']= "credit card";
    $paymentGateways[0]['mode']= ($paypalSplitPayment=="Y")?"N":getSettingsValue('vauthorize_enable');
    $paymentGateways[0]['code']= "Authorize";
    $paymentGateways[0]['img'] = $path."cc.gif"; 
            
    $paymentGateways[1]['name']= "Paypal";
    $paymentGateways[1]['mode']= getSettingsValue('enablepaypal');
    $paymentGateways[1]['code']= "pp";
    $paymentGateways[1]['img'] = $path."pp.jpg";     
    $paymentGateways[1]['paypal_vendor_email'] = $paypalEmail;
    $paymentGateways[1]['paypal_test_mode'] = $paypalSandbox;
    
    $enable_tax      = getSettingsValue('enable_tax');
    $default_tax_rate= getSettingsValue('defaulttax_rate');
    $taxpercentage   = $default_tax_rate;
    
    if($selected_shipping && $userId!=NULL){
    //--Get items from cart for current user --//
    $select_cart_details = "SELECT prd.product_id,prd.product_name,po.product_option_id,po.product_length,po.product_width,po.product_height,crt.quantity,
                   po.product_shipping_weight,art.country AS origin_country,art.state AS origin_state,art.zip AS origin_zip,art.artist_id,art.artist_name,
                   art.defaultflatrate,art.additionalflatrate
                   FROM ".$tableprefix."cart crt
                   INNER JOIN ".$tableprefix."product_options po ON crt.product_option_id = po.product_option_id
                   INNER JOIN ".$tableprefix."products prd ON prd.product_id = po.product_id
                   INNER JOIN ".$tableprefix."artists art ON art.artist_id = prd.product_artist_id
                   WHERE crt.user_id = ".$userId." ORDER BY crt.cart_id";
    $result_cart_details = mysql_query($select_cart_details) or die(mysql_error());
    
     if(mysql_num_rows($result_cart_details)) {
        $cnt = 0;
        while($cartDataObj = mysql_fetch_object($result_cart_details)) {
                $cartData[$cnt][] = $cartDataObj;
                $cnt++;
        }
        $previous_seller = 0;        
        foreach($cartData as $cartObj){
            $ship_opt = "shipping_option_". $cartObj[0]->artist_id;
            $shipVal = $selected_shipping->$ship_opt;            
            if ($shippingMethod == "Flat Rate") { // For flat rate- Shipping cost is added up for all products of each seller, so just add up total of each seller only
                if ($shipVal != "") {
                    $shipValArr = explode('=>', $shipVal);
                    if ($cartObj[0]->artist_id != $previous_seller) {
                        $shippingTotal += $shipValArr[1];
                    }
                    $previous_seller = $cartObj[0]->artist_id;
                } else {
                    $shippingDetails[$cartObj[0]->artist_id] = array();
                }
            } else {
                if ($shipVal != "") {
                    $shipValArr = explode('=>', $shipVal);
                    $shippingDetails[$cartObj[0]->artist_id] = array("preffered_shipping" => $shipValArr[0], "rate" => $shipValArr[1]);
                    $shippingTotal += $shipValArr[1];
                } else {
                    $shippingDetails[$cartObj[0]->artist_id] = array();
                }
            }
        }
        
        
        $select_cart_details  = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
					FROM ".$tableprefix."cart c
                                        INNER JOIN ".$tableprefix."product_options po ON po.product_option_id = c.product_option_id
                                        INNER JOIN ".$tableprefix."products p ON p.product_id = po.product_id
					WHERE c.user_id = '".$userId."'";

$result_cart_details = mysql_query($select_cart_details) or die(mysql_error());

            $product_price = 0;
            $product_rate = 0;

            while ($rw = mysql_fetch_array($result_cart_details)) {
                $product_rate = $rw['product_price'];
                /* ------------Multicart 2.0 Upgradation------------ */
                $product_option_id = $rw["product_option_id"];
                $qty = $rw["quantity"];
                $product_price = $qty * $product_rate;

                if ($rw["discount"] != 0) {
                    $discountprice = $product_rate - ($product_rate * $rw["discount"]) / 100;
                    $discountrate = ($discountprice * $qty);
                    $product_price = $discountrate;
                }
                
            }

            if ($enable_tax == "1") {   // check taxrate activated for each state
                if ($tbase == "Subtotal") {
                    $taxrate = number_format(getCartTotal($userId), 2, ".", "") * ($taxpercentage / 100);
                }
                if ($tbase == "Subtotal and Shipping") {
                    $taxrate = (number_format(getCartTotal($userId), 2, ".", "") + $shipping_cost) * ($taxpercentage / 100);
                }
            }

            if ($enable_tax == "2") { // check default tax rate activated	
                $taxrate = number_format((getCartTotal($userId) * $taxpercentage / 100), 2, ".", "");
            }
            $cartTotalAmount = getCartTotal($userId);
     
        $paymentDetails['shipping_total'] = $shippingTotal;        
        $paymentDetails['tax_total']      = $taxrate;
        $paymentDetails['item_total']     = $cartTotalAmount;
        $paymentDetails['paymentGateways']= $paymentGateways;
        $currentstatus['status'] = 1;
        $currentstatus['data'] =$paymentDetails;
        return($currentstatus); 
        
    }
   }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
        return($currentstatus); 
   }
}

//-- Function to make payment with Authorize --//
function makePaymentAuthorizeAPI(){
    include "../includes/config.php";
    include_once('../classes/cls_products.php');
    include "apifunctions.php";
    $userid            = $_REQUEST["user_id"];
    $selected_shipping = json_decode(stripslashes($_REQUEST['shipping_selected']));
    $adminCurrency     = GetAdminCurrency();
   
     if ($userid != NULL) {
                $txtAuthorizeLoginId        =     getSettingsValue("authorize_loginid");
                $txtAuthorizeTransKey       =     getSettingsValue("authorize_transkey");
                $txtCurrency                =     $adminCurrency['currency_code'];
                $txtAuthorizeEmail          =     getSettingsValue("authorize_email");
                $txtAuthorizeTestMode       =     getSettingsValue("authorize_test_mode");   
                $txtFirstName               =     $_REQUEST["shippingFirstName"];  
                $txtLastName                =     $_REQUEST["shippingLastName"];  
                $txtAddress1                =     $_REQUEST["shippingAddress1"]; 
                $txtCity                    =     $_REQUEST["shippingCity"]; 
                $txtState                   =     $_REQUEST["shippingState"]; 
                $txtZIP                     =     $_REQUEST["shippingZIP"]; 
                $txtEmail                   =     $_REQUEST["shippingEmail"]; 
                $ddlCountry                 =     $_REQUEST["shippingCountry"]; 
                $txtCCNumber                =     $_REQUEST["CCNumber"]; 
                $txtCVV2                    =     $_REQUEST["cvv2"]; 
                $txtMM                      =     $_REQUEST["exp_month"]; 
                $txtYY                      =     $_REQUEST["exp_year"]; 
                $totaltopay                 =     $_REQUEST["amount_to_pay"];   
                $shippingTotal              =     $_REQUEST["shipping_total"];   
                $taxTotal                   =     $_REQUEST["tax_total"]; 
               
                if($txtAuthorizeTestMode == "Y"){
                        $txtAuthorizeTestMode = "on";
                }else{
                        $txtAuthorizeTestMode = "off";
                }
                $referrer =  $_SERVER["HTTP_REFERER"];
                $qry1="select max(order_id)+1 as ordid from " . $tableprefix . "orders";
                $excqry1=mysql_query($qry1);
                $row1=mysql_fetch_array($excqry1);
                $Inv_id=$row1['ordid'];                
                $Cust_id = $_SESSION["sess_userid"];
                $Cust_ip = getClientIP();
                $Company = "-NA-";
                $Phone=$txtPhone;
                if($txtLastName=="")
                  $txtLastName="-NA-";

                require "../authorize.php";//process the card and return result. Comment this line and uncomment the two lines below to make payment test mode
                
                if($paymentsuccessful){// payment is made successfully
                    $trax_token = $transactionid;
                    $amountpaid = number_format($_REQUEST['amount_to_pay'], 2, ".", "");
                    $sql = "INSERT INTO  " . $tableprefix . "orders (
                                   user_id,
                                   billing_first_name,
                                   billing_last_name,
                                   billing_address1,
                                   billing_address2,
                                   billing_city,
                                   billing_state,
                                   billing_country,
                                   billing_zip,
                                   billing_fax,
                                   billing_email,
                                   billing_phone,
                                   shipping_first_name,
                                   shipping_last_name,
                                   shipping_address1,
                                   shipping_address2,
                                   shipping_city,
                                   shipping_state,
                                   shipping_country,
                                   shipping_zip,
                                   shipping_fax,
                                   shipping_email,
                                   shipping_phone,
                                   prefered_shippin_method,
                                   order_date,
                                   order_total_price,
                                   taxrate,
                                   order_status,
                                   transaction_id,
                                   vorder_currency,
                                   namount_paid,
                                   buyer_comments,
                                   vpayment_status
                                   ) VALUES(
                                   '" . addslashes($_REQUEST["user_id"]) . "',
                                   '" . addslashes($_REQUEST["billingFirstName"]) . "',
                                   '" . addslashes($_REQUEST["billingLastName"]) . "',
                                   '" . addslashes($_REQUEST["billingAddress1"]) . "',
                                   '" . addslashes($_REQUEST["billingAddress2"]) . "',
                                   '" . addslashes($_REQUEST["billingCity"]) . "',
                                   '" . addslashes($_REQUEST["billingState"]) . "',
                                   '" . addslashes($_REQUEST["billingCountry"]) . "',
                                   '" . addslashes($_REQUEST["billingZIP"]) . "',
                                   '" . addslashes($_REQUEST["billingFAX"]) . "',
                                   '" . addslashes($_REQUEST["billingEmail"]) . "',
                                   '" . addslashes($_REQUEST["billingPhone"]) . "',
                                   '" . addslashes($_REQUEST["shippingFirstName"]) . "',
                                   '" . addslashes($_REQUEST["shippingLastName"]) . "',
                                   '" . addslashes($_REQUEST["shippingAddress1"]) . "',
                                   '" . addslashes($_REQUEST["shippingAddress2"]) . "',
                                   '" . addslashes($_REQUEST["shippingCity"]) . "',
                                   '" . addslashes($_REQUEST["shippingState"]) . "',
                                   '" . addslashes($_REQUEST["shippingCountry"]) . "',
                                   '" . addslashes($_REQUEST["shippingZIP"]) . "',
                                   '" . addslashes($_REQUEST["shippingFAX"]) . "',
                                   '" . addslashes($_REQUEST["shippingEmail"]) . "',
                                   '" . addslashes($_REQUEST["shippingPhone"]) . "',
                                   '',
                                   now(),
                                   '" . addslashes($totaltopay) . "',
                                   '" . addslashes($_REQUEST["tax_total"]) . "',
                                   '1',
                                   '" . addslashes($trax_token) . "',
                                   '',
                                   '" . addslashes($amountpaid) . "',
                                   '',
                                   'C'
                                   )";

                    mysql_query($sql);
                    $orderid = mysql_insert_id();

                    $check_shipping_enable = checkShippingEnable();

                    if ($check_shipping_enable == "Y") {

                        /* ---------------inserting the shipping details---------------- */
                        $select_cart_products = "SELECT c.product_option_id,c.product_id,p.product_name,po.product_shipping_weight,p.product_artist_id FROM " . $tableprefix . "cart c
                                                        INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                        INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                        WHERE c.user_id = " . $userid;

                        $result_cart_products = mysql_query($select_cart_products) or die(mysql_error());

                        if (mysql_num_rows($result_cart_products) > 0) {
                            while ($cart_obj = mysql_fetch_object($result_cart_products)) {
                                $ship_opt = "shipping_option_" . $cart_obj->product_artist_id;
                                $shipVal = $selected_shipping->$ship_opt;

                                if (isset($shipVal)) {
                                    $product_name = $cart_obj->product_name;
                                    $optionVal = getProductOptionsName($cart_obj->product_option_id);
                                    $ship_dtls = explode("=>", $shipVal);
                                    $shipping_name = $ship_dtls[0];
                                    $shipping_cost = $ship_dtls[1];
                                    $product_shipping_weight = $cart_obj->product_shipping_weight;
                                    $ship_product_option_id = $cart_obj->product_option_id;
                                    $product_name .= $optionVal;
                                    $seller_id  = $cart_obj->product_artist_id;
                                    
                                        
                                    $insert_shipping = "INSERT INTO " . $tableprefix . "shipping_details
                                                                     (
                                                                     norder_id,
                                                                     vshipping_currency,
                                                                     dshipped_date,
                                                                     nshp_status,
                                                                     user_id,
                                                                     nshp_productid,
                                                                     nproduct_option_id,
                                                                     nshp_productname,
                                                                     vshipping_name,
                                                                     nshipping_cost,
                                                                     nshipping_weight,
                                                                     seller_id
                                                                     )
                                                                     VALUES
                                                                     (
                                                                     " . $orderid . ",
                                                                     '" . $currency_attributes[2] . "',
                                                                     now(),
                                                                     'C',
                                                                     '" . addslashes($userid) . "',
                                                                     " . $cart_obj->product_id . ",
                                                                     " . $ship_product_option_id . ",
                                                                     '" . addslashes($product_name) . "',
                                                                     '" . addslashes($shipping_name) . "',
                                                                     '" . $shipping_cost . "',
                                                                     '" . $product_shipping_weight . "',
                                                                     '" . $seller_id . "'    
                                                                      )
                                                                    ";                                    
                                    mysql_query($insert_shipping) or die(mysql_error());
                                }
                            } // end while
                        } // end 
                    } // end of shipping if
                    
                    /*         * ************************ Affilate payment block******************************************** */
                    $sql = "select * from  " . $tableprefix . "users where user_id='" . $userid . "'";
                    $result = mysql_query($sql);
                    $row = mysql_fetch_array($result);
                    if ($row["affiliate_id"] != "" && $row["affiliate_id"] != "0" && $row["vaff_type"] != "paid") {
                        $aid = $row['affiliate_id'];
                        $userid = $row['user_id'];
                        $txtUserName = $row['user_name'];
                        $txtFirstName = $row['first_name'];
                        $txtEmail = $row['email'];
                        $txtorderdamount = $totaltopay;
                        $sql1 = "SELECT * FROM " . $tableprefix . "settings ";
                        $result1 = mysql_query($sql1);
                        if (mysql_num_rows($result1) != 0) {
                            $row1 = mysql_fetch_array($result1);
                            /* referral charge calculation based on the currency type */
                            $txtReferralCharge = $row1["referral_charge"];
                        }
                        $var_aff_comm = ($txtorderdamount * $txtReferralCharge / 100);
                        $sql2 = "INSERT INTO " . $tableprefix . "affiliate_registrations (
                                                    affiliate_id,
                                                    user_id,
                                                    order_id,
                                                    user_name ,
                                                    user_first_name,
                                                    user_last_name,
                                                    user_email,
                                                    referral_charge,
                                                    registration_date,
                                                    user_totalpurchasedamount
                                                    ) VALUES (
                                                    '" . addslashes($aid) . "',
                                                    '" . addslashes($userid) . "',
                                                    '" . addslashes($orderid) . "',
                                                    '" . addslashes($txtUserName) . "',
                                                    '" . addslashes($txtFirstName) . "',
                                                    '" . addslashes($txtLastName) . "',
                                                    '" . addslashes($txtEmail) . "',
                                                    '" . addslashes($var_aff_comm) . "',
                                                    now(),'$totaltopay'
                                                    )";
                        mysql_query($sql2) or die(mysql_error());

                        $sql3 = " update " . $tableprefix . "users set vaff_type='paid' where user_id='" . $userid . "'";
                        $result3 = mysql_query($sql3);
                        sendReferralPurchaseMailtoAffliate($aid);
                        
                    } // end if Affiliate Registraion
                    /*         * ************************ Affilate payment block******************************************** */
                    $product_download_flag = 0;
                    $download_link = "";
                    $sql = "SELECT c.*,(p.product_price+po.additional_price) AS product_price,p.product_name,p.product_code,p.product_artist_id,po.discount,
                                                            p.vdigital_product,ar.commission
                                            FROM " . $tableprefix . "cart c
                                            INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                            INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                            INNER JOIN " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id
                                            WHERE c.user_id = '" . $userid . "' ";


                    $res = mysql_query($sql);
                    $product_commission_amt = 0;

                    $artists = array();
                    if (mysql_num_rows($res) != 0) {
                        $i = 0;
                        while ($row = mysql_fetch_array($res)) {
                            $productid = $row["product_id"];
                            $product_option_id = $row["product_option_id"];
                            $quantity = $row["quantity"];
                            /* product price is calculated based on currency type */
                            $converted_price = $row["product_price"];
                            $productprice = number_format($converted_price, 2, ".", "");
                            $productname = $row["product_name"];
                            $optionVal = getProductOptionsName($product_option_id);
                            $productname .= $optionVal;
                            $productcode = $row["product_code"];
                            $productdiscount = $row["discount"];
                            $artistid = $row["product_artist_id"];

                            if ($row['vdigital_product'] == "Y") {

                                $digital_product_id = $row["product_id"];
                                $select_product_digital_code = "SELECT vdigital_product_name,vdigital_product_code,ndownload_try,ndownload_expiry,ndownload_expiry_days
                                                                                            FROM " . $tableprefix . "digital_product
                                                                                            WHERE ndigital_productid = " . $row["product_id"] . " AND ndigital_orderid =0 ";
                                $result_product_digital_code = mysql_query($select_product_digital_code) or die(mysql_error());
                                if (mysql_num_rows($result_product_digital_code) > 0) {
                                    while ($product_digital_code_row = mysql_fetch_array($result_product_digital_code)) {
                                        /* --------------------creating random product download code and updating the database----------------------- */
                                        $digital_product_code = randomDigitalProduct();
                                        $expiry_days = $product_digital_code_row['ndownload_expiry_days'];
                                        $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));
                                        /* ---------selecting the download try and download expiry date----------- */
                                        $select_digital_product_details = "SELECT ndownload_try,ndownload_expiry FROM " . $tableprefix . "digital_product WHERE ndigital_productid = " . $productid;
                                        $result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());

                                        $digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);

                                        $product_download_try = $digital_product_details_row["ndownload_try"];
                                        $download_expiry_date = $digital_product_details_row["ndownload_expiry"];
                                        /* ---------selecting the download try and download expiry date----------- */

                                        $select_digital_count = "SELECT ndigital_id FROM " . $tableprefix . "digital_product WHERE ndigital_orderid = " . $orderid;
                                        $result_digital_count = mysql_query($select_digital_count) or die(mysql_error());
                                        for ($i = 1; $i <= $row["quantity"]; $i++) {
                                            /* -------Calculating the download expiry days---------- */
                                            $expiry_days = $product_digital_code_row['ndownload_expiry_days'];
                                            $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));
                                            /* -------Calculating the download expiry days---------- */
                                            $digital_product_code = randomDigitalProduct();
                                            $insert_product_digital_code = "INSERT INTO " . $tableprefix . "digital_product(vdigital_product_name,ndigital_productid,
                                                                                ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_expiry_days,
                                                                                ndownload_status)VALUES('" . addslashes($product_digital_code_row['vdigital_product_name']) . "',
                                                                                " . $row["product_id"] . ",
                                                                                " . $orderid . ",
                                                                                '" . $digital_product_code . "',
                                                                                " . $product_digital_code_row['ndownload_try'] . ",0,
                                                                                '" . $valid_date_upto . "'," . addslashes($product_digital_code_row['ndownload_expiry_days']) . ",0)";
                                            mysql_query($insert_product_digital_code) or die(mysql_error());
                                        } // end for loop
                                        //exit;
                                    } // end ehile
                                } // emd if number of rows check

                                $product_download_flag = 1;
                            } // end digital product check
                            /* ----------------------------------End check Digital Products-------------------------------------------------- */
                            // Product Based Commission Calculation
                            $ship_opt2 = "shipping_option_" . $artistid;
                            $shipVal2 = $selected_shipping->$ship_opt2;

                            if (isset($shipVal2)) {
                                $optionVal = getProductOptionsName($product_option_id);
                                $ship_dtls2 = explode("=>", $shipVal2);
                                $shipping_name = $ship_dtls2[0];
                                $shipping_cost = $ship_dtls2[1];
                            }
                            $enable_tax = getSettingsValue('enable_tax');
                            $default_tax_rate = getSettingsValue('defaulttax_rate');
                            $taxpercentage = $default_tax_rate;

                            $price_amt = $productprice * $quantity;
                            $product_commission_amt = ($price_amt * $row["commission"]) / 100;

                            if ($enable_tax == "1") {   // check taxrate activated for each state
                                if ($tbase == "Subtotal") {
                                    $product_tax = number_format($price_amt, 2, ".", "") * ($taxpercentage / 100);
                                }
                                if ($tbase == "Subtotal and Shipping") {
                                    $product_tax = (number_format($price_amt, 2, ".", "") + $shipping_cost) * ($taxpercentage / 100);
                                }
                            }
                            if ($enable_tax == "2") { // check default tax rate activated	
                                $product_tax = number_format(($price_amt * $taxpercentage / 100), 2, ".", "");
                            }

                            $price_amt = $productprice * $quantity;
                            $product_commission_amt = ($price_amt * $row["commission"]) / 100;
                            //********************Multicart3.0 Addiations to save product flags***************

                            $digital_product_flag   =  $row["digital_product_flag"];
                            $gift_product_flag      =  $row["gift_product_flag"];

                            $shipping_name  = $shipping_name;
                            $shipping_price = $shipping_cost;
                            if($shipping_cost==0 || $shipping_cost=='')
                                $freeShipping = "Y";
                            else
                                $freeShipping = "N";

                            //********************End**************                                

                            $sql = "INSERT INTO  " . $tableprefix . "order_details (
                                            order_id,
                                            product_id,
                                            product_name,
                                            product_code,
                                            product_price,
                                            product_quantity,
                                            product_discount,
                                            artist_id,
                                            item_status,
                                            artist_payment_status,
                                            product_tax,
                                            product_option_id,
                                            product_commission_amount,
                                            digital_product_flag,
                                            gift_product_flag,
                                            product_shipping_price,
                                            product_shipping_name,
                                            allow_free_shipping  
                                            )VALUES(
                                            '" . addslashes($orderid) . "',
                                            '" . addslashes($productid) . "',
                                            '" . addslashes($productname) . "',
                                            '" . addslashes($productcode) . "',
                                            '" . addslashes($productprice) . "',
                                            '" . addslashes($quantity) . "',
                                            '" . addslashes($productdiscount) . "',
                                            '" . addslashes($artistid) . "',
                                            '1',
                                            '0',
                                            '" . $product_tax . "',
                                            '" . $product_option_id . "',
                                            '" . $product_commission_amt . "',
                                            '".$digital_product_flag."',
                                            '".$gift_product_flag."',
                                             '".$shipping_price."',
                                            '".addslashes($shipping_name)."',
                                            '".addslashes($freeShipping)."'                                                  
                                            )";

                            mysql_query($sql) or die(mysql_error());
                            $artists[$i] = $artistid;
                            $i++;
                            $sql = "";

                            if ($product_download_flag == 1) {
                                $update_order_details = "UPDATE " . $tableprefix . "order_details
                                                        SET item_status = 4
                                                        WHERE order_id  = " . $orderid . " AND product_id = " . $digital_product_id;
                                mysql_query($update_order_details) or die(mysql_error());
                            }
                            $reorderlevelcheck = checkSellerStock($product_option_id, $quantity);

                            if ($reorderlevelcheck == 1) {
                                // Send Stock Reorder Mail To Seller
                                sendStockreordermail($product_option_id, $quantity);
                            }
                        } // end while
                    } // end number of rows

                    adjustStock($userid, "-");
                    emptyCart($userid);
                    if ($product_download_flag == 1) {
                        sendDigitalCertificateMail_Buyer($orderid, $userid, 'user');
                        sendDigitalCertificateMail_Seller($orderid, $userid);
                        sendDigitalCertificateMail_Admin($orderid, $userid);
                    } else {
                        sendBuyerEmail($orderid, $userid, 'user');
                        sendSellerEmail($orderid, $userid);
                        sendAdminEmail($orderid, $userid);
                    }
                    
                    $currentstatus['status'] = 1;
                    $currentstatus['data'] = "Your order has been successfully placed.";
                }else{
                $error = str_replace("Error<br>", "", $paymenterror);
                $error = str_replace("(TESTMODE)", "", $error);
                $currentstatus['status'] = 0;
                $currentstatus['data'] = $error;
                }
        
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
    }

    return($currentstatus);      
}

//-- Paypal success - order update API --//
function paypalSuccessAPI() {
    include "../includes/config.php";
    include_once('../classes/cls_products.php');
    include "apifunctions.php";
    $trax_token = $_REQUEST['transaction_id'];
    $userid   = $_REQUEST["user_id"];
    $taxTotal = $_REQUEST["tax_total"];     
    $selected_shipping = json_decode(stripslashes($_REQUEST['shipping_selected']));
    $currency_attributes = displayCurrencyType();
    if ($trax_token != NULL) {
        $amountpaid = number_format($_REQUEST['amount_paid'], 2, ".", "");
        $sql = "INSERT INTO  " . $tableprefix . "orders (
                       user_id,
                       billing_first_name,
                       billing_last_name,
                       billing_address1,
                       billing_address2,
                       billing_city,
                       billing_state,
                       billing_country,
                       billing_zip,
                       billing_fax,
                       billing_email,
                       billing_phone,
                       shipping_first_name,
                       shipping_last_name,
                       shipping_address1,
                       shipping_address2,
                       shipping_city,
                       shipping_state,
                       shipping_country,
                       shipping_zip,
                       shipping_fax,
                       shipping_email,
                       shipping_phone,
                       prefered_shippin_method,
                       order_date,
                       order_total_price,
                       taxrate,
                       order_status,
                       transaction_id,
                       vorder_currency,
                       namount_paid,
                       buyer_comments,
                       vpayment_status
                       ) VALUES(
                       '" . addslashes($_REQUEST["user_id"]) . "',
                       '" . addslashes($_REQUEST["billingFirstName"]) . "',
                       '" . addslashes($_REQUEST["billingLastName"]) . "',
                       '" . addslashes($_REQUEST["billingAddress1"]) . "',
                       '" . addslashes($_REQUEST["billingAddress2"]) . "',
                       '" . addslashes($_REQUEST["billingCity"]) . "',
                       '" . addslashes($_REQUEST["billingState"]) . "',
                       '" . addslashes($_REQUEST["billingCountry"]) . "',
                       '" . addslashes($_REQUEST["billingZIP"]) . "',
                       '" . addslashes($_REQUEST["billingFAX"]) . "',
                       '" . addslashes($_REQUEST["billingEmail"]) . "',
                       '" . addslashes($_REQUEST["billingPhone"]) . "',
                       '" . addslashes($_REQUEST["shippingFirstName"]) . "',
                       '" . addslashes($_REQUEST["shippingLastName"]) . "',
                       '" . addslashes($_REQUEST["shippingAddress1"]) . "',
                       '" . addslashes($_REQUEST["shippingAddress2"]) . "',
                       '" . addslashes($_REQUEST["shippingCity"]) . "',
                       '" . addslashes($_REQUEST["shippingState"]) . "',
                       '" . addslashes($_REQUEST["shippingCountry"]) . "',
                       '" . addslashes($_REQUEST["shippingZIP"]) . "',
                       '" . addslashes($_REQUEST["shippingFAX"]) . "',
                       '" . addslashes($_REQUEST["shippingEmail"]) . "',
                       '" . addslashes($_REQUEST["shippingPhone"]) . "',
                       '',
                       now(),
                       '" . addslashes($totaltopay) . "',
                       '" . addslashes($taxTotal) . "',
                       '1',
                       '" . addslashes($trax_token) . "',
                       '',
                       '" . addslashes($amountpaid) . "',
                       '',
                       'C'
                       )";
 
        mysql_query($sql);
        $orderid = mysql_insert_id();

        $check_shipping_enable = checkShippingEnable();

        if ($check_shipping_enable == "Y") {

            /* ---------------inserting the shipping details---------------- */
            $select_cart_products = "SELECT c.product_option_id,c.product_id,p.product_name,po.product_shipping_weight,p.product_artist_id FROM " . $tableprefix . "cart c
                                            INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                            INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                            WHERE c.user_id = " . $userid;

            $result_cart_products = mysql_query($select_cart_products) or die(mysql_error());

            if (mysql_num_rows($result_cart_products) > 0) {
                while ($cart_obj = mysql_fetch_object($result_cart_products)) {
                    $ship_opt = "shipping_option_" . $cart_obj->product_artist_id;
                    $shipVal = $selected_shipping->$ship_opt;

                    if (isset($shipVal)) {
                        $product_name = $cart_obj->product_name;
                        $optionVal = getProductOptionsName($cart_obj->product_option_id);
                        $ship_dtls = explode("=>", $shipVal);
                        $shipping_name = $ship_dtls[0];
                        $shipping_cost = $ship_dtls[1];
                        $product_shipping_weight = $cart_obj->product_shipping_weight;
                        $ship_product_option_id = $cart_obj->product_option_id;
                        $product_name .= $optionVal;
                        $seller_id  = $cart_obj->product_artist_id;
                        $insert_shipping = "INSERT INTO " . $tableprefix . "shipping_details
                                                         (
                                                         norder_id,
                                                         vshipping_currency,
                                                         dshipped_date,
                                                         nshp_status,
                                                         user_id,
                                                         nshp_productid,
                                                         nproduct_option_id,
                                                         nshp_productname,
                                                         vshipping_name,
                                                         nshipping_cost,
                                                         nshipping_weight,
                                                         seller_id
                                                         )
                                                         VALUES
                                                         (
                                                         " . $orderid . ",
                                                         '" . $currency_attributes[2] . "',
                                                         now(),
                                                         'C',
                                                         '" . addslashes($userid) . "',
                                                         " . $cart_obj->product_id . ",
                                                         " . $ship_product_option_id . ",
                                                         '" . addslashes($product_name) . "',
                                                         '" . addslashes($shipping_name) . "',
                                                         '" . $shipping_cost . "',
                                                         '" . $product_shipping_weight . "',
                                                         '" . $seller_id . "'    
                                                          )
                                                        ";
                        mysql_query($insert_shipping) or die(mysql_error());
                    }
                } // end while
            } // end 
        } // end of shipping if
        /*         * ************************ Affilate payment block******************************************** */
        $sql = "select * from  " . $tableprefix . "users where user_id='" . $userid . "'";
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);
        if ($row["affiliate_id"] != "" && $row["affiliate_id"] != "0" && $row["vaff_type"] != "paid") {
            $aid = $row['affiliate_id'];
            $userid = $row['user_id'];
            $txtUserName = $row['user_name'];
            $txtFirstName = $row['first_name'];
            $txtEmail = $row['email'];
            $txtorderdamount = $totaltopay;
            $sql1 = "SELECT * FROM " . $tableprefix . "settings ";
            $result1 = mysql_query($sql1);
            if (mysql_num_rows($result1) != 0) {
                $row1 = mysql_fetch_array($result1);
                /* referral charge calculation based on the currency type */
                $txtReferralCharge = $row1["referral_charge"];
            }
            $var_aff_comm = ($txtorderdamount * $txtReferralCharge / 100);
            $sql2 = "INSERT INTO " . $tableprefix . "affiliate_registrations (
                                        affiliate_id,
                                        user_id,
                                        order_id,
                                        user_name ,
                                        user_first_name,
                                        user_last_name,
                                        user_email,
                                        referral_charge,
                                        registration_date,
                                        user_totalpurchasedamount
                                        ) VALUES (
                                        '" . addslashes($aid) . "',
                                        '" . addslashes($userid) . "',
                                        '" . addslashes($orderid) . "',
                                        '" . addslashes($txtUserName) . "',
                                        '" . addslashes($txtFirstName) . "',
                                        '" . addslashes($txtLastName) . "',
                                        '" . addslashes($txtEmail) . "',
                                        '" . addslashes($var_aff_comm) . "',
                                        now(),'$totaltopay'
                                        )";
            mysql_query($sql2) or die(mysql_error());

            $sql3 = " update " . $tableprefix . "users set vaff_type='paid' where user_id='" . $userid . "'";
            $result3 = mysql_query($sql3);
            sendReferralPurchaseMailtoAffliate($aid);
        } // end if Affiliate Registraion
        /*         * ************************ Affilate payment block******************************************** */
        $product_download_flag = 0;
        $download_link = "";
        $sql = "SELECT c.*,(p.product_price+po.additional_price) AS product_price,p.product_name,p.product_code,p.product_artist_id,po.discount,
						p.vdigital_product,ar.commission
				FROM " . $tableprefix . "cart c
                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                INNER JOIN " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id
				WHERE c.user_id = '" . $userid . "' ";


        $res = mysql_query($sql);
        $product_commission_amt = 0;

        $artists = array();
        if (mysql_num_rows($res) != 0) {
            $i = 0;
            while ($row = mysql_fetch_array($res)) {
                $productid = $row["product_id"];
                $product_option_id = $row["product_option_id"];
                $quantity = $row["quantity"];
                /* product price is calculated based on currency type */
                $converted_price = $row["product_price"];
                $productprice = number_format($converted_price, 2, ".", "");
                $productname = $row["product_name"];
                $optionVal = getProductOptionsName($product_option_id);
                $productname .= $optionVal;
                $productcode = $row["product_code"];
                $productdiscount = $row["discount"];
                $artistid = $row["product_artist_id"];

                if ($row['vdigital_product'] == "Y") {

                    $digital_product_id = $row["product_id"];
                    $select_product_digital_code = "SELECT vdigital_product_name,vdigital_product_code,ndownload_try,ndownload_expiry,ndownload_expiry_days
										FROM " . $tableprefix . "digital_product
										WHERE ndigital_productid = " . $row["product_id"] . " AND ndigital_orderid =0 ";
                    $result_product_digital_code = mysql_query($select_product_digital_code) or die(mysql_error());
                    if (mysql_num_rows($result_product_digital_code) > 0) {
                        while ($product_digital_code_row = mysql_fetch_array($result_product_digital_code)) {
                            /* --------------------creating random product download code and updating the database----------------------- */
                            $digital_product_code = randomDigitalProduct();
                            $expiry_days = $product_digital_code_row['ndownload_expiry_days'];
                            $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));
                            /* ---------selecting the download try and download expiry date----------- */
                            $select_digital_product_details = "SELECT ndownload_try,ndownload_expiry FROM " . $tableprefix . "digital_product WHERE ndigital_productid = " . $productid;
                            $result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());

                            $digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);

                            $product_download_try = $digital_product_details_row["ndownload_try"];
                            $download_expiry_date = $digital_product_details_row["ndownload_expiry"];
                            /* ---------selecting the download try and download expiry date----------- */

                            $select_digital_count = "SELECT ndigital_id FROM " . $tableprefix . "digital_product WHERE ndigital_orderid = " . $orderid;
                            $result_digital_count = mysql_query($select_digital_count) or die(mysql_error());
                            for ($i = 1; $i <= $row["quantity"]; $i++) {
                                /* -------Calculating the download expiry days---------- */
                                $expiry_days = $product_digital_code_row['ndownload_expiry_days'];
                                $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));
                                /* -------Calculating the download expiry days---------- */
                                $digital_product_code = randomDigitalProduct();
                                $insert_product_digital_code = "INSERT INTO " . $tableprefix . "digital_product(vdigital_product_name,ndigital_productid,
                                                                    ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_expiry_days,
                                                                    ndownload_status)VALUES('" . addslashes($product_digital_code_row['vdigital_product_name']) . "',
                                                                    " . $row["product_id"] . ",
                                                                    " . $orderid . ",
                                                                    '" . $digital_product_code . "',
                                                                    " . $product_digital_code_row['ndownload_try'] . ",0,
                                                                    '" . $valid_date_upto . "'," . addslashes($product_digital_code_row['ndownload_expiry_days']) . ",0)";
                                mysql_query($insert_product_digital_code) or die(mysql_error());
                            } // end for loop
                            //exit;
                        } // end ehile
                    } // emd if number of rows check

                    $product_download_flag = 1;
                } // end digital product check
                /* ----------------------------------End check Digital Products-------------------------------------------------- */
                // Product Based Commission Calculation
                $ship_opt2 = "shipping_option_" . $artistid;
                $shipVal2 = $selected_shipping->$ship_opt2;

                if (isset($shipVal2)) {
                    $optionVal = getProductOptionsName($product_option_id);
                    $ship_dtls2 = explode("=>", $shipVal2);
                    $shipping_name = $ship_dtls2[0];
                    $shipping_cost = $ship_dtls2[1];
                }
                $enable_tax = getSettingsValue('enable_tax');
                $default_tax_rate = getSettingsValue('defaulttax_rate');
                $taxpercentage = $default_tax_rate;

                /*/*-----------------------------------
                if($enable_tax==1)
	        { // check enable tax
		   $sql="select * from ".$tableprefix."taxrate  WHERE (vState LIKE '%".$txtBillingState."%'
				 AND vtaxaddress = 'billing' AND vState!='1' AND vCountry LIKE '%".$billingCountry."%') OR (vState LIKE '%".$txtShippingState."%' AND vtaxaddress = 'shipping' AND vState!='1' AND vCountry LIKE '%".$shippingCountry."%')
				 OR (vCountry LIKE '%".$billingCountry."%' AND vtaxaddress = 'billing' AND vState='1' ) OR
				 (vCountry LIKE '%".$shippingCountry."%' AND vtaxaddress = 'shipping' AND vState='1') AND rate_enable='1' Limit 0,1";

                 $rs=mysql_query($sql) or die(mysql_error());
		if(mysql_num_rows($rs)>0)
		{
			$rr=mysql_fetch_array($rs);
			$taxpercentage=$rr['ntaxrate'];
			$tname=stripslashes($rr['taxname']);
			$tbase=$rr['vtaxbase'];

	        } // end row check
                } // end enbale tax
                //-----------------------------------------*/
                
                $price_amt = $productprice * $quantity;
                $product_commission_amt = ($price_amt * $row["commission"]) / 100;

                if ($enable_tax == "1") {   // check taxrate activated for each state
                    if ($tbase == "Subtotal") {
                        $product_tax = number_format($price_amt, 2, ".", "") * ($taxpercentage / 100);
                    }
                    if ($tbase == "Subtotal and Shipping") {
                        $product_tax = (number_format($price_amt, 2, ".", "") + $shipping_cost) * ($taxpercentage / 100);
                    }
                }
                if ($enable_tax == "2") { // check default tax rate activated	
                    $product_tax = number_format(($price_amt * $taxpercentage / 100), 2, ".", "");
                }

                $price_amt = $productprice * $quantity;
                $product_commission_amt = ($price_amt * $row["commission"]) / 100;
    
                //********************Multicart3.0 Addiations to save product flags***************

                $digital_product_flag   =  $row["digital_product_flag"];
                $gift_product_flag      =  $row["gift_product_flag"];

                $shipping_name  = $shipping_name;
                $shipping_price = $shipping_cost;
                if($shipping_cost==0 || $shipping_cost=='')
                    $freeShipping = "Y";
                else
                    $freeShipping = "N";

                //********************End**************                

                $sql = "INSERT INTO  " . $tableprefix . "order_details (
				order_id,
				product_id,
				product_name,
				product_code,
				product_price,
				product_quantity,
				product_discount,
				artist_id,
				item_status,
				artist_payment_status,
                                product_tax,
                                product_option_id,
                                product_commission_amount,
                                digital_product_flag,
                                gift_product_flag,
                                product_shipping_price,
                                product_shipping_name,
                                allow_free_shipping                                
				)VALUES(
				'" . addslashes($orderid) . "',
				'" . addslashes($productid) . "',
				'" . addslashes($productname) . "',
				'" . addslashes($productcode) . "',
				'" . addslashes($productprice) . "',
				'" . addslashes($quantity) . "',
				'" . addslashes($productdiscount) . "',
				'" . addslashes($artistid) . "',
				'1',
				'0',
                                '" . $product_tax . "',
                                '" . $product_option_id . "',
                                '" . $product_commission_amt . "',
                                '".$digital_product_flag."',
                                '".$gift_product_flag."',
                                 '".$shipping_price."',
                                '".addslashes($shipping_name)."',
                                '".addslashes($freeShipping)."'                                      
				)";

                mysql_query($sql) or die(mysql_error());
                $artists[$i] = $artistid;
                $i++;
                $sql = "";

                if ($product_download_flag == 1) {
                    $update_order_details = "UPDATE " . $tableprefix . "order_details
                                            SET item_status = 4
                                            WHERE order_id  = " . $orderid . " AND product_id = " . $digital_product_id;
                    mysql_query($update_order_details) or die(mysql_error());
                }
                $reorderlevelcheck = checkSellerStock($product_option_id, $quantity);

                if ($reorderlevelcheck == 1) {
                    // Send Stock Reorder Mail To Seller
                    sendStockreordermail($product_option_id, $quantity);
                }
            } // end while
        } // end number of rows

        adjustStock($userid, "-");
        emptyCart($userid);

        if ($product_download_flag == 1) {
            sendDigitalCertificateMail_Buyer($orderid, $userid, 'user');
            sendDigitalCertificateMail_Seller($orderid, $userid);
            sendDigitalCertificateMail_Admin($orderid, $userid);
        } else {
            sendBuyerEmail($orderid, $userid, 'user');
            sendSellerEmail($orderid, $userid);
            sendAdminEmail($orderid, $userid);
        }
        $currentstatus['status'] = 1;
        $currentstatus['data'] = "Your order has been successfully placed.";
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Insufficient Data.";
    }

    return($currentstatus);
}

//--Get billing address--//
function getBillingAddressAPI($userId=NULL){
    include "../includes/config.php";
    include "apifunctions.php";
    if(isset($userId)&&$userId!=NULL){
        $sql = "SELECT first_name,last_name,address1,address2,city,state,zip,fax,phone,email,country FROM ".$tableprefix."users 
			WHERE user_id=".addslashes($userId);          
            $result=mysql_query($sql) or die(mysql_error());			
            if(mysql_num_rows($result) > 0 )
            {                           
                $row = mysql_fetch_assoc($result);  
                $currentstatus['status'] = 1;
                $currentstatus['data']   = $row;
                $currentstatus['data']['country_code'] =  $row['country'];
                $currentstatus['data']['state_code']   =  $row['state'];
                $currentstatus['data']['country'] =  getCodeValue($row['country'],1);
                $currentstatus['data']['state']   = (getCodeValue($row['state'],2,$row['country'])!=NULL)?getCodeValue($row['state'],2,$row['country']):$row['state'];
                return($currentstatus);  
            } else {
                 $currentstatus['status'] = 0;
                 $currentstatus['data'] = "Invalid credentials.";
                 return($currentstatus); 
            }
            
    }else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "User Id missing.";
        return($currentstatus); 
    }
    
} 

//--- Update billing address---//
function updateBillingAddressAPI(){
    include "../includes/config.php";

    if (isset($_REQUEST['user_id']) && $_REQUEST['user_id'] != NULL) {
        
        $arrUser['user_id'] = stripslashes($_REQUEST['user_id']);
        $arrUser['first_name'] = stripslashes($_REQUEST['first_name']);
        $arrUser['last_name'] = stripslashes($_REQUEST['last_name']); 
        $arrUser['email'] = stripslashes($_REQUEST['email']);
        $arrUser['address1'] = stripslashes($_REQUEST['address1']);
        $arrUser['address2'] = stripslashes($_REQUEST['address2']);
        $arrUser['city'] = stripslashes($_REQUEST['city']);
        $arrUser['country'] = stripslashes($_REQUEST['country']);
        $arrUser['state'] = stripslashes($_REQUEST['state']);
        $arrUser['phone'] = stripslashes($_REQUEST['phone']);        
        $arrUser['fax'] = stripslashes($_REQUEST['fax']);
        $arrUser['zip'] = stripslashes($_REQUEST['zip']);        
        
        $qry2 = "select email from  " . $tableprefix . "users where email='" . $arrUser['email'] . "' AND user_id <> '".$arrUser['user_id']."' ";
        if (mysql_num_rows(mysql_query($qry2)) > 0) {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = EMAIL_ADDRESS_MSG;
            return($currentstatus);            
        } 
    
        // Primary Seller info
        $sql = "UPDATE  " . $tableprefix . "users SET
                    first_name = '" . addslashes($arrUser['first_name']) . "',
                    last_name = '" . addslashes($arrUser['last_name']) . "',
                    address1 = '" . addslashes($arrUser['address1']) . "',
                    address2 = '" . addslashes($arrUser['address2']) . "',	
                    city = '" . addslashes($arrUser['city']) . "',			
                    phone = '" . addslashes($arrUser['phone']) . "',			
                    email = '" . addslashes($arrUser['email']) . "',			    
                    fax = '" . addslashes($arrUser['fax']) . "',	
                    zip = '" . addslashes($arrUser['zip']) . "',	    
                    country = '" . addslashes($arrUser['country']) . "',    
                    state = '" . addslashes($arrUser['state']) . "'";                    
        $sql .=" WHERE user_id=" . $arrUser['user_id'];        
        mysql_query($sql) or die(mysql_error());

        $currentstatus['status'] = 1;
        $currentstatus['data'] = "User profile updated";
        return($currentstatus);
    }else{
    $currentstatus['status'] = 0;
    $currentstatus['data'] = "User ID is missing";
    return($currentstatus);
    }

    
}

// Function to get CMS content//
function aboutUsContentAPI(){
    include "../includes/config.php";
    include "apifunctions.php";
   
    $cms_content_terms = displayCMS('about_us');    
    if (!empty($cms_content_terms)) {
        $currentstatus['status'] = 1;
        $currentstatus['title'] = $cms_content_terms[0];
        $currentstatus['data']  = $cms_content_terms[1];
        return($currentstatus);
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Something went wrong";
        return($currentstatus);
    }
}

//--Fetch All from DB---//
function fetchAll($resultSet)
{
        $resultArray = array();
        while($obj = mysql_fetch_object($resultSet))
        {
        $resultArray[] = $obj;
        }
        if(empty($resultArray)) {
        return array();
        }
        return $resultArray;
}

function getOptionsFromCategory($catid) {
    $options_arr = array();
    include "../includes/config.php";
    //global $tableprefix;
    if($catid !="") {
        $query_cat_options = "SELECT o.option_id,o.option_name
                            FROM ".$tableprefix."options o
                                INNER JOIN ".$tableprefix."category_options co ON co.option_id = o.option_id AND co.category_id = '".$catid."' ORDER BY o.option_name";
        
        $cat_optionsQ = mysql_query($query_cat_options);

        while($optionsObj = mysql_fetch_object($cat_optionsQ)) {
            $options_arr[] = array("option_id"=>$optionsObj->option_id,"option_name"=>$optionsObj->option_name);

        }
    }
    return $options_arr;
}

function sendBuyerEmail($order_id,$user_id,$usertype='user') {

    include "../includes/config.php";  
    //include "apifunctions.php";

    $currency_attributes=displayCurrencyType();
    $adminCurrency	= GetAdminCurrency();
    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];

    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $mailContent = '
	<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>".MAIL_ORDER_TEXT_GIFT_COUPON_CODE." ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);
        $couponCodeDiscount=$orderObj->couponCodeDiscount;
        $productname.= $optionStr;


        // Shipping Cost
        if($orderDetailObj->nshipping_cost!=0) {
            $totalshippingcost += $orderDetailObj->nshipping_cost;
        }
        // Shipping Cost


        $converted_price = $orderDetailObj->product_price;

        $rate = number_format(($converted_price),2 ,".","" );
        // End currency Conversion
        /*------------Multicart 2.0 Upgradation------------*/

        $qty = $orderDetailObj->product_quantity;
        $price = $qty * $rate;
        $discountstr="";
        if($orderDetailObj->product_discount !="0") {
            $price=$price- ($price*$orderDetailObj->product_discount)/100;

            $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";
        }



        //$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");


        $itemTotal+=$price;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

        $inc++;

    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';

    $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';



    // Modified ON 22-07-2010 // Asha
    if($couponCodeDiscount>0) {
        //echo "sdhjsdhasd";
        //$priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
        $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
        $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

    }
    
    
    if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Discount Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }

    if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }
    


    $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_TAXT_RATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    if($totalshippingcost!=0) {
        //echo $orderObj->order_total_price;
        $mailContent .='<tr>
			<td width="40%">'.MAIL_ORDER_TEXT_SHIPPING_AND_HANDLING.' </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
    }



    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_ORDER_TOTAL.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$orderObj->taxrate,2,".","").'</td>
			</tr>';



    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_AMOUNT_PAID.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';

    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }
    if($giftCheckVal=="") {
        if($orderObj->shipping_address2) {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }else {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
    }


    $mailContent .='</table>';

    $mailcontent_buyer=readEmailTemplate('order_notification_buyer');

    if(stristr($mailcontent_buyer,"[buyer_first_name")) {
        $mailcontent_buyer=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_buyer);
    }
    if(stristr($mailcontent_buyer,"[buyer_last_name")) {
        $mailcontent_buyer=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_buyer);
    }


    $mailcontent_buyer=str_replace('[order_details]',$mailContent,$mailcontent_buyer);


     $mail_send_details_buyer ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_buyer.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>

</body>
</html>';

    //echo $mail_send_details_buyer;

    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
    $headers .= "Organization: ".SITE_NAME."\r\n";

    $ordersubject  = MAIL_ORDER_SUBJECT." ".SITE_NAME;
    $mailsent = mail($orderObj->billing_email,$ordersubject,$mail_send_details_buyer,$headers);
    
}

function sendSellerEmail($order_id,$user_id) {
    include "../includes/config.php";  
    //include "apifunctions.php";

    $adminCurrency	= GetAdminCurrency();

    $currencySymbol	=	$adminCurrency['currency_symbol'];

    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    
     $couponCodeDiscount=$orderObj->couponCodeDiscount;

    $queryOrderDetail_seller	 = "SELECT DISTINCT od.artist_id,s.*
  										FROM ".$tableprefix."order_details od
										INNER JOIN ".$tableprefix."artists s ON s.artist_id=od.artist_id
										WHERE od.order_id =".$order_id;
    $orderDetailQ_seller     = mysql_query($queryOrderDetail_seller);

    while($orderobjseller=mysql_fetch_object($orderDetailQ_seller)) {

        $mailContent = '
	<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>
		</tr>';


        $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id." AND od.artist_id=".$orderobjseller->artist_id." ";
        $orderDetailQ     = mysql_query($queryOrderDetail);
        $itemTotal =0;
        $inc = 1;
        $totalshippingcost=0;
        $taxTotal =0;
        $productlist_fillstock=array();
        while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
            $optionStr="";


            if($giftCheckVal) {
                $giftCertificateCode = "<font color='#ff0000'><br>".MAIL_ORDER_TEXT_GIFT_COUPON_CODE." ".$orderDetailObj->vgift_coupon_code."</font>";
            }
            $productname=stripslashes($orderDetailObj->product_name);
            $couponCodeDiscount=$orderObj->couponCodeDiscount;
            $productname.= $optionStr;


            // Shipping Cost
            if($orderDetailObj->nshipping_cost!=0) {
                $totalshippingcost += $orderDetailObj->nshipping_cost;
            }
            // Shipping Cost


            $converted_price = $orderDetailObj->product_price;

            $rate = number_format(($converted_price),2 ,".","" );
            // End currency Conversion
            /*------------Multicart 2.0 Upgradation------------*/

            $qty = $orderDetailObj->product_quantity;
            $price = $qty * $rate;
            $discountstr="";
            if($orderDetailObj->product_discount !="0") {
                $price=$price- ($price*$orderDetailObj->product_discount)/100;

                $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";
            }



            //$productPrice = number_format(($currency_attributes[1] * $productPrice),2,".","");


            $itemTotal+=$price;

            $taxTotal+=$orderDetailObj->product_tax;

            $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currencySymbol.'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currencySymbol.'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';
            $inc++;

        }
        $mailContent.='</table>
		</td>
		</tr>';

        $ItemTotalPrice=0;
        //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
        $ItemTotalPrice=$itemTotal;
        $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';

        $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp;'.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';

        // Modified ON 22-07-2010 // Asha
         if($couponCodeDiscount>0) {
       
                 $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
                $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

            }

	if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Discount Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
            }

     if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }
        $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_TAXT_RATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.$taxTotal.'</td>
		</tr>';

        if($totalshippingcost!=0) {
            //echo $orderObj->order_total_price;
            $mailContent .='<tr>
			<td width="40%">'.MAIL_ORDER_TEXT_SHIPPING_AND_HANDLING.' </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
        }

        $mailContent .='<tr>
			<td>Order Total Price:</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currencySymbol.' &nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$taxTotal,2,".","").'</td>
			</tr>';


        

        if($orderObj->billing_address2) {
            $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
        }else {
            $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
        if($giftCheckVal=="") {
            if($orderObj->shipping_address2) {
                $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
            }else {
                $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
            }
        }

        $mailContent .='</table>';

        $mailcontent_seller = readEmailTemplate('order_notification_mail_seller');

        //  echo $mailcontent_seller;

        $mailcontent_seller=str_replace('[order_details]',$mailContent,$mailcontent_seller);

       $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA" >
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td bgcolor="#EAEAEA" ><img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
			<tr>
			<td align="left"> '.MAIL_ORDER_TEXT_DEAR.' '.$orderobjseller->first_name.'&nbsp;'.$orderobjseller->last_name.', </td>
			<tr>
			<tr>
			<td align="left">'.MAIL_ORDER_TEXT_NEW_ORDER_PLACED_IN.' '.SITE_NAME.'. '.MAIL_ORDER_TEXT_THE_DETAILS_ARE_AS_FOLLOWS.'</td>
			</tr>

			<tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left">'.$mailcontent_seller.'</td>
                </tr>

              </table></td>
            </tr>

            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';


        $headers  = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
        $headers .= "Organization: ".SITE_NAME."\r\n";
        $ordersubject  = MAIL_ORDER_SUBJECT." ".SITE_NAME;
        $mailsent = mail($orderobjseller->email,$ordersubject,$mail_send_details_seller,$headers);

        // Send Stock reorder Mail

    } // end while loop of artists    
}

function sendAdminEmail($order_id,$user_id) {
    include "../includes/config.php";  
    //include "apifunctions.php";

    $adminCurrency	= GetAdminCurrency();
    $currency_attributes[0]=$adminCurrency['currency_symbol'];
    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $mailContent = '
	<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,sd.nshipping_cost
  						FROM ".$tableprefix."order_details od
						LEFT JOIN ".$tableprefix."shipping_details sd ON sd.nproduct_option_id=od.product_option_id AND sd.norder_id='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id;
    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        if($giftCheckVal) {
            $giftCertificateCode = "<font color='#ff0000'><br>".MAIL_ORDER_TEXT_GIFT_COUPON_CODE." ".$orderDetailObj->vgift_coupon_code."</font>";
        }
        $productname=stripslashes($orderDetailObj->product_name);
        $couponCodeDiscount=$orderObj->couponCodeDiscount;
        $productname.= $optionStr;

        // Shipping Cost
        if($orderDetailObj->nshipping_cost!=0) {
            $totalshippingcost += $orderDetailObj->nshipping_cost;
        }
        // Shipping Cost

        $converted_price = $orderDetailObj->product_price;

        $rate = number_format(($converted_price),2 ,".","" );
        // End currency Conversion
        /*------------Multicart 2.0 Upgradation------------*/
        $qty = $orderDetailObj->product_quantity;
        $price = $qty * $rate;
        $discountstr="";
        if($orderDetailObj->product_discount !="0") {
            $price=$price- ($price*$orderDetailObj->product_discount)/100;

            $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";
        }

        $itemTotal+=$price;
        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.' </td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($rate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($price,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';
        $inc++;
    }
    $mailContent.='</table>
		</td>
		</tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';

    $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';



    // Modified ON 22-07-2010 // Asha
    if($couponCodeDiscount>0) {
         $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
         $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

    }
     if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }
    
     if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }

    $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_TAXT_RATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    if($totalshippingcost!=0) {
        $mailContent .='<tr>
			<td width="40%">'.MAIL_ORDER_TEXT_SHIPPING_AND_HANDLING.' </td>
			<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($totalshippingcost,2,".","" ).'</td>
			</tr>';
    }


    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_ORDER_TOTAL.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice+$totalshippingcost+$orderObj->taxrate,2,".","").'</td>
			</tr>';
    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_AMOUNT_PAID.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';
    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }
    if($giftCheckVal=="") {
        if($orderObj->shipping_address2) {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_address2.'<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }else {
            $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_SHIPPING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">

		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->shipping_first_name.' '.$orderObj->shipping_last_name.'<br>
		'.$orderObj->shipping_address1.',<br>
		'.$orderObj->shipping_city.', '.$orderObj->shipping_state.', '.$orderObj->shipping_country.' '.$orderObj->shipping_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->shipping_phone.'<br>
		'.$orderObj->shipping_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }
    }

    $mailContent .='</table>';
    $mailcontent_admin=readEmailTemplate('order_notification_admin');
    $mailcontent_admin=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_admin);
    $mailcontent_admin=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_admin);
    $mailcontent_admin=str_replace('[order_details]',$mailContent,$mailcontent_admin);
   $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>
            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';

//echo $mail_send_details_buyer;
    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
    $headers .= "Organization: ".SITE_NAME."\r\n";
    $ordersubject  = MAIL_ORDER_SUBJECT." ".SITE_NAME;
    $adminemail	=getSettingsValue('site_email');
    $mailsent = mail($adminemail,$ordersubject,$mail_send_details_admin,$headers);

}

function sendDigitalCertificateMail_Buyer($order_id,$user_id,$usertype='') {
    include "../includes/config.php";  
    $mailContent ="";

    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $mailContent = '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>';

    $product_download_details ="";

    $product_download_details = "<font color='#FF0000'>Note: If you do not have pop-ups enabled on your browser, the product download may not work properly.So please enable pop-ups before downloading !!</font>";


    $mailContent .='<tr>
				<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
				<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
				<tr>
				<td align="left" valign="top">
					'.$product_download_details.'
				</td>
				</tr>
				<tr><td><b> <br>'.MAIL_DIGITAL_PRODUCT_MESSAGE.'</b></td></tr>

				</table></td></tr>';

    $mailContent .='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_DIGITAL_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>
		</tr>';

    $queryOrderDetail = "SELECT od.*,DATE_FORMAT(gc.ndownload_expiry,'%m-%d-%Y') as ndownload_expiry,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON od.product_id = gc.ndigital_productid AND od.order_id=gc.ndigital_orderid
						WHERE od.order_id =".$order_id." GROUP BY gc.ndigital_productid ";


    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        $productname=stripslashes($orderDetailObj->product_name);
        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

        $productPrice = number_format($converted_price,2,".","");


        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

        $product_download_try = $orderDetailObj->ndownload_try;

        $download_expiry_date = $orderDetailObj->ndownload_expiry;


        /*if($orderDetailObj->ndownload_expiry!='')
					{
						$download_expiry_date  	= dateFormat($orderDetailObj->ndownload_expiry, "Y-m-d", "m-d-Y");
					}

					$download_expiry_date  	= $orderDetailObj->ndownload_expiry;*/
        $expiry_days = 	$orderDetailObj->ndownload_expiry_days;

        /*if($orderDetailObj->ndownload_expiry_days!='')
			{
				   $expiry_days = 	dateFormat($orderDetailObj->ndownload_expiry_days, "Y-m-d", "m-d-Y");
			}*/

        $product_download_trydetails ="";


        $product_download_trydetails .= "<br><br>".MAIL_PRODUCT_DOWNLOAD_PRODUCT_DOWNLOAD_TRY ." - $product_download_try ".MAIL_PRODUCT_DOWNLOAD_TIMES."\r\n";
        $product_download_trydetails .= "<br><br>".MAIL_PRODUCT_DOWNLOAD_EXPIRY_DATE." - $download_expiry_date\r\n";

        $valid_date_upto = date("Y-m-d H:s:m",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$expiry_days,date("Y")));

        $mailContent .='<tr>
				<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6" width="100%">
				<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
				<tr>
				<td align="left" valign="top">
					'.$product_download_trydetails.'
				</td>
				</tr>

				</table></td></tr>';


        $queryOrderDetail_digital = "SELECT gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM  ".$tableprefix."digital_product gc where gc.ndigital_productid='".$orderDetailObj->product_id."' AND gc.ndigital_orderid='".addslashes($order_id)."' ";
        $rs_digital					=mysql_query($queryOrderDetail_digital)	or die(mysql_error());

        $product_download_details ="";

        $couponCodeDiscount=$orderObj->couponCodeDiscount;

        if(mysql_num_rows($rs_digital)>0) {
            $product_download_details_link = "";
            $download_link = "";

            $cnt	=1 ;

            while($orderDetailObjdigital=mysql_fetch_object($rs_digital)) {

                $download_link = "<a href='" . SITE_URL ."/digital_product_download.php?download_code=$orderDetailObjdigital->vdigital_product_code'><br><br>Download Link".$cnt."</a> ";
                //$download_link = " <br><br>Download Link  ".$cnt." - ".SITE_URL."/digital_product_download.php?download_code=$orderDetailObjdigital->vdigital_product_code\r\n";
                $product_download_details_link = $download_link;

                $mailContent .='<tr>
				<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " colspan="6">
				<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
				<tr>
				<td align="left" valign="top">
					'.$product_download_details_link.'
				</td>
				</tr></table></td></tr>';

                $cnt++;

            }



        }




        $inc++;




    }


    $mailContent .='</table></td></tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " width="100%">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';
     $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';
     
   
    
    if($couponCodeDiscount>0) {
        //echo "sdhjsdhasd";
        //$priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
        $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
        $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

    }
    if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Discount Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }
     if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }
    

    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_ORDER_TOTAL.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_AMOUNT_PAID.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';
//number_format($orderObj->namount_paid,2,".","")
    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr>';
    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }

    $mailContent .='</table>';


    $mailcontent_buyer= readEmailTemplate('digital_product');

    $mailcontent_buyer=str_replace('[buyer_first_name]',$orderObj->billing_first_name,$mailcontent_buyer);

    $mailcontent_buyer=str_replace('[buyer_last_name]',$orderObj->billing_last_name,$mailcontent_buyer);
    
    if(stristr($mailcontent_buyer,"[first_name")) {
        $mailcontent_buyer=str_replace('[first_name]',$orderObj->billing_first_name,$mailcontent_buyer);
    }
    if(stristr($mailcontent_buyer,"[last_name")) {
        $mailcontent_buyer=str_replace('[last_name]',$orderObj->billing_last_name,$mailcontent_buyer);
    }


    $mailcontent_buyer=str_replace('[order_details]',$mailContent,$mailcontent_buyer);

  $mail_send_details_buyer ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_buyer.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>

            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>
</body>
</html>';
    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
    $headers .= "Organization: ".SITE_NAME."\r\n";

    $ordersubject = MAIL_PRODUCT_DOWNLOAD_SUBJECT." ".SITE_NAME;

    $mailsent = mail($orderObj->billing_email,$ordersubject,$mail_send_details_buyer,$headers);

}

function sendDigitalCertificateMail_Seller($order_id,$user_id) {

    include "../includes/config.php";
    $adminCurrency	= GetAdminCurrency();
    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];

    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    $couponCodeDiscount=$orderObj->couponCodeDiscount;
    $queryOrderDetail_seller	 = "SELECT DISTINCT od.artist_id,s.*
  										FROM ".$tableprefix."order_details od
										INNER JOIN ".$tableprefix."artists s ON s.artist_id=od.artist_id
										WHERE od.order_id =".$order_id;
    $orderDetailQ_seller     = mysql_query($queryOrderDetail_seller);

    while($orderobjseller=mysql_fetch_object($orderDetailQ_seller)) {

        $mailContent = '
	<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
        $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		<tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_DIGITAL_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>
		</tr>';


        $queryOrderDetail = "SELECT od.*,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON gc.ndigital_productid=od.product_id  AND od.order_id=gc.ndigital_orderid
						WHERE od.order_id =".$order_id." AND od.artist_id=".$orderobjseller->artist_id." GROUP BY gc.ndigital_productid ";

        $orderDetailQ     = mysql_query($queryOrderDetail);
        $itemTotal =0;
        $taxTotal =0;
        $inc = 1;
        while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
            $optionStr="";


            $productname=stripslashes($orderDetailObj->product_name);
            $productRate	=	$orderDetailObj->product_price;
            $productPrice	=	$productRate*$orderDetailObj->product_quantity;
            $discountstr="";
            if($orderDetailObj->product_discount!=0) {
                $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
                $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";

            }



            $converted_price = $productPrice;

            $productPrice = number_format($converted_price,2,".","");

            $taxTotal+=$orderDetailObj->product_tax;

            $itemTotal+=$productPrice;

            $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';

            $inc++;
        }

        $mailContent.='</table>
		</td>
		</tr>';



        $ItemTotalPrice=0;
        //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
        $ItemTotalPrice=$itemTotal;



        $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';
                 $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';
            /* $mailContent .='<tr>
		<td>Tax Rate:</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$taxTotal.'</td>
		</tr>';*/

        
         if($couponCodeDiscount>0) {
       
                 $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        
                $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

            }

	if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> Gift Certificate Discount Amount :</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
            }

     if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }
        $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_ORDER_TOTAL.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice+$taxTotal,2,".","").'</td>
			</tr>';

        /*$mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_AMOUNT_PAID.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';*/
        $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
        if($orderObj->billing_address2) {
            $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
        }else {
            $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
        }

        $mailContent .='</table>';

        $mailcontent_seller= readEmailTemplate('digital_product_seller');

        $mailcontent_seller=str_replace('[first_name]',$orderObj->billing_first_name,$mailcontent_seller);

        $mailcontent_seller=str_replace('[last_name]',$orderObj->billing_last_name,$mailcontent_seller);

        $mailcontent_seller=str_replace('[order_details]',$mailContent,$mailcontent_seller);


        $mail_send_details_seller='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA" >
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td bgcolor="#EAEAEA" ><img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
			<tr>
			<td align="left"> '.MAIL_SALUTATION.' '.$orderobjseller->first_name.'&nbsp;'.$orderobjseller->last_name.', </td>
			<tr>

			<tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left">'.$mailcontent_seller.'</td>
                </tr>

              </table></td>
            </tr>

            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';

//echo "<br>".$mail_send_details_seller;

        $headers  = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
        $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
        $headers .= "Organization: ".SITE_NAME."\r\n";

        $ordersubject = MAIL_DIGITAL_PRODUCT_SUBJECT." ".SITE_NAME;

        //echo  "<br>".$mail_send_details_seller;
        //echo $ordersubject,$mail_send_details_seller;

        $mailsent = mail($orderobjseller->email,$ordersubject,$mail_send_details_seller,$headers);

        // Send Stock reorder Mail

    } // end while loop of artists

}

function sendDigitalCertificateMail_Admin($order_id,$user_id) {
    include "../includes/config.php";
    $adminCurrency	= GetAdminCurrency();
    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];


    $queryOrder="SELECT o.* ,DATE_FORMAT(o.order_date,'%m-%d-%Y') as order_dateF from ".$tableprefix."orders o  where order_id=".$order_id." ";
    $orderQ      = mysql_query($queryOrder);
    $orderObj    = mysql_fetch_object($orderQ);
    
    $couponCodeDiscount=$orderObj->couponCodeDiscount;
    
    $mailContent = '
	<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F5F5F5;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_ORDER_DETAILS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td width="40%">'.MAIL_ORDER_TEXT_STORE_NAME.'</td>
		<td width="60%" style="font-size:13px; color:#991818; font-weight:bold; ">'.SITE_NAME.'('.SITE_URL.')</td>
		</tr>';
    $mailContent .= '<tr>
		<td>'.MAIL_ORDER_TEXT_ORDER_ID.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_id.'</td>
		</tr>
		<tr>
		<tr>
		<td >'.MAIL_ORDER_TEXT_ORDER_DATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$orderObj->order_dateF.'</td>
		</tr>
		</table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_PRODUCTS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr style="background-color:#D2D2D2; font-weight:bold; ">
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_SL_NO.'</td>
		<td align="left" valign="top">'.MAIL_DIGITAL_PRODUCT_NAME.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRODUCT_CODE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_RATE.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_QUANTITY.'</td>
		<td align="left" valign="top">'.MAIL_ORDER_TEXT_PRICE.'</td>

		</tr>';
    $queryOrderDetail = "SELECT od.*,gc.vdigital_product_code,gc.ndownload_try,gc.ndownload_expiry,gc.ndownload_expiry_days
  						FROM ".$tableprefix."order_details od
						INNER JOIN ".$tableprefix."digital_product gc ON gc.ndigital_productid=od.product_id AND gc.ndigital_orderid='".addslashes($order_id)."'
						WHERE od.order_id =".$order_id." GROUP BY gc.ndigital_productid ";


    $orderDetailQ     = mysql_query($queryOrderDetail);
    $itemTotal =0;
    $inc = 1;
    while($orderDetailObj   = mysql_fetch_object($orderDetailQ)) {
        $optionStr="";

        $productname=stripslashes($orderDetailObj->product_name);
        $productRate	=	$orderDetailObj->product_price;
        $productPrice	=	$productRate*$orderDetailObj->product_quantity;
        $discountstr="";
        if($orderDetailObj->product_discount!=0) {
            $productPrice=$productPrice- ($productPrice*$orderDetailObj->product_discount)/100;
            $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$orderDetailObj->product_discount."%)";

        }


        $converted_price = $productPrice;

        $productPrice = number_format($converted_price,2,".","");

        $itemTotal+=$productPrice;

        $mailContent.='<tr>
		<td align="left" valign="top">'.$inc.'</td>
		<td align="left" valign="top">'.$productname.'</td>
		<td align="left" valign="top">'.$orderDetailObj->product_code.'</td>
		<td align="left" valign="top"> '.$currency_attributes[0].'&nbsp;'.number_format($productRate,2,".","").'</td>
		<td align="left" valign="top">&nbsp;'.$orderDetailObj->product_quantity.'</td>
		<td align="left" valign="top">'.$currency_attributes[0].'&nbsp;'.number_format($productPrice,2,".","").'&nbsp;&nbsp;'.$discountstr.'</td>
		</tr>';


        $inc++;



    }

    $mailContent .='</table></td></tr>';

    $ItemTotalPrice=0;
    //Modified ON 03-12-2010 // Remove Set Price Total from Total Price
    $ItemTotalPrice=$itemTotal;

    $mailContent.='<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_CHARGES.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; " width="100%">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">';
     $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_ITEM_PRICE_TOTAL.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($ItemTotalPrice,2,".","" ).'</td>
		</tr>';
         if($couponCodeDiscount>0) {
        //echo "sdhjsdhasd";
        //$priceafterdiscount=$ItemTotalPrice-($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
        //$ItemTotalPrice=$priceafterdiscount;
         $couponCodeDiscountAmount = ($ItemTotalPrice*$orderObj->couponCodeDiscount)/100;
         $mailContent.='<tr>
		<td style="font-size:14px; color:#FF0000; font-weight:bold;">'.MAIL_ORDER_TEXT_COUPON_CODE.' " '.$orderObj->couponCode.' " '.MAIL_ORDER_TEXT_DISCOUNT_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; "> '.$currency_attributes[0].'&nbsp; '.number_format($couponCodeDiscountAmount,2,".","").'&nbsp;&nbsp; ( '.($orderObj->couponCodeDiscount).' %  '.MAIL_ORDER_TEXT_OF_ITEM_PRICE_TOTAL.')</td>
		</tr>';

    }
     if($orderObj->vgiftcertificate_code!='' &&  $orderObj->nused_gift_amount >0) {
        
        $giftDiscountAmount           = $orderObj->nused_gift_amount;   
        $mailContent.='<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_CODE.' : </td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$orderObj->vgiftcertificate_code.'  </td>
		</tr>
		<tr>
		<td> '.MAIL_ORDER_TEXT_GIFT_CERTIFICATE_AMOUNT.'</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->nused_gift_amount,2,".","").' </td>
		</tr>';
    }
    
     if($orderObj->nused_gift_amount >0 || $couponCodeDiscount>0 ) {
        
        $TotalDiscount   = $giftDiscountAmount + $couponCodeDiscountAmount;
        
       $priceafterdiscount=$ItemTotalPrice-$TotalDiscount;
       
       $ItemTotalPrice=$priceafterdiscount;
       
        $mailContent.='<tr>
		<td>Item Total Cost After  Discount:</td>
		<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($priceafterdiscount,2,".","").'</td>
		</tr>';
    }

    $mailContent .='<tr>
		<td>'.MAIL_ORDER_TEXT_TAXT_RATE.'</td>
		<td  style="font-size:13px; color:#991818; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.$orderObj->taxrate.'</td>
		</tr>';

    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_ORDER_TOTAL.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp;'.number_format($ItemTotalPrice,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td>'.MAIL_ORDER_TEXT_AMOUNT_PAID.'</td>
			<td  style="font-size:16px; color:#FF0000; font-weight:bold; ">'.$currency_attributes[0].'&nbsp; '.number_format($orderObj->namount_paid,2,".","").'</td>
			</tr>';

    $mailContent .='<tr>
			<td colspan="2">&nbsp;</td>
			</tr></table></td></tr>';
    if($orderObj->billing_address2) {
        $mailContent .='<tr></table>
			</td>
			</tr>
			<tr>
			<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
			'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
			</td>
			</tr>
			<tr>
			<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
			<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
			<tr>
			<td align="left" valign="top">
			'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
			'.$orderObj->billing_address1.',<br>
			'.$orderObj->billing_address2.',<br>
			'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
			'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
			'.$orderObj->billing_email.'
			</td>
			</tr>
			</table>
			</td>
			</tr>';
    }else {
        $mailContent .='<tr></table>
		</td>
		</tr>
		<tr>
		<td style="font-weight:bold; color:#CE0221; font-size:14px; padding:15px 15px 5px 15px;" align="left" valign="top">
		'.MAIL_ORDER_TEXT_BILLING_ADDRESS.'
		</td>
		</tr>
		<tr>
		<td  align="left" valign="top" style="padding:5px 15px 15px 15px; ">
		<table width="100%" cellpadding="5" cellspacing="0" border="0" style="background-color:#FFFFFF; border:#D5D5D5 solid 1px;font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000000; ">
		<tr>
		<td align="left" valign="top">
		'.$orderObj->billing_first_name.' '.$orderObj->billing_last_name.'<br>
		'.$orderObj->billing_address1.',<br>
		'.$orderObj->billing_city.', '.$orderObj->billing_state.', '.$orderObj->billing_country.' '.$orderObj->billing_zip.'<br>
		'.MAIL_ORDER_TEXT_PHONE.' '.$orderObj->billing_phone.'<br>
		'.$orderObj->billing_email.'
		</td>
		</tr>
		</table>
		</td>
		</tr>';
    }


    $mailContent .='</table>';


    $mailcontent_admin= readEmailTemplate('digital_product_admin');

    $mailcontent_admin=str_replace('[first_name]',$orderObj->billing_first_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[last_name]',$orderObj->billing_last_name,$mailcontent_admin);

    $mailcontent_admin=str_replace('[order_details]',$mailContent,$mailcontent_admin);


    $mail_send_details_admin ='<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
  <link href="'.SITE_URL.'/style/template1-admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<table width="100%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
   <tr>
     <td align="center" valign="top">

         <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
            <tr>
               <td align="right" >
              </td>
            </tr>
            <tr>
               <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
                 <tr>
                   <td  bgcolor="#EAEAEA" > <img src='.SITE_URL.'/banners/'.getSettingsValue('site_logo').' width="125" height="60"/></td>
                 </tr>
               </table></td>
            </tr>
            <tr>
              <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td align="left"><p>'.$mailcontent_admin.'</p>
                  </td>
                </tr>
              </table></td>
            </tr>

            <tr>
               <td align="center" bgcolor="#EAEAEA" class="footer">
                  <p>&nbsp;</p>
              </td>
            </tr>
       </table>

     </td>
   </tr>
</table>


</body>
</html>';

//echo $mail_send_details_buyer;

    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "From: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Reply-To: ".SITE_NAME."<".SITE_EMAIL.">" . "\r\n";
    $headers .= "Return-Path: ".SITE_NAME."<noreply@".SITE_NAME.">" . "\r\n";
    $headers .= "Organization: ".SITE_NAME."\r\n";

    $ordersubject = MAIL_PRODUCT_DOWNLOAD_SUBJECT." ".SITE_NAME;

    $adminemail	=getSettingsValue('site_email');

    $mailsent = mail($adminemail,$ordersubject,$mail_send_details_admin,$headers);


}

/*function to display the active template*/


function displayTemplate() {
    
    include "../includes/config.php";
    $template_array = array();

    $select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
					    FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
    $result_template = mysql_query($select_template) or die(mysql_error());
    $template_row = mysql_fetch_assoc($result_template);

    array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);

    return $template_array;
}


function GetAdminCurrency() {
     include "../includes/config.php";

    $sql = "SELECT admin_currency FROM `" . $tableprefix . "settings` ";
    $result = mysql_query($sql);
    if (mysql_num_rows($result)>0) {

        $rsCurrencyObj	= mysql_fetch_object($result);

        switch($rsCurrencyObj->admin_currency) {
            case "USD": {
                    $adminCurrencySymbol	= '&#36;';
                    break;
                }
            case "EUR": {
                    $adminCurrencySymbol	= '€';
                    break;
                }
            case "GBP": {
                    $adminCurrencySymbol	= '£';
                    break;
                }
            case "INR": {
                    $adminCurrencySymbol	= 'INR';
                    break;
                }        
            default :
                $adminCurrencySymbol	= '&#36;';
                break;

        }

        $admin_currency= array("currency_code"=>$rsCurrencyObj->admin_currency,
                "currency_symbol"=>$adminCurrencySymbol);

        return  $admin_currency;

    }
}

/*------function to read the email templates-----------*/

function readEmailTemplate($template_name,$table_name="",$email_address="") {    
    include "../includes/config.php";
    $adminCurrency	= GetAdminCurrency();

    $currency_attributes[0]	=	$adminCurrency['currency_symbol'];

    $select_email_template = "SELECT vemail_body FROM ".$tableprefix."email_templates WHERE vtemplate_name = '".$template_name."'";

    $result_email_template = mysql_query($select_email_template) or die(mysql_error());

    if($email_address != "") {

        $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."users
								WHERE email = '".$email_address."'";

        $result_user_details = mysql_query($select_user_details) or die(mysql_error());

        if(mysql_num_rows($result_user_details) > 0) {

            $user_details_row = mysql_fetch_assoc($result_user_details);
            $txtFirstName = ucwords($user_details_row['first_name']);
            $txtLastName = ucwords($user_details_row['last_name']);
        }
    }
    if($table_name == "" && $email_address == "") {
        if($_SESSION["sess_userid"] != "") {
            $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."users
									WHERE user_id = ".$_SESSION["sess_userid"];

            $result_user_details = mysql_query($select_user_details) or die(mysql_error());

            if(mysql_num_rows($result_user_details) > 0) {
                $user_details_row = mysql_fetch_assoc($result_user_details);
                $txtFirstName = $user_details_row['first_name'];
                $txtLastName = $user_details_row['last_name'];
            }
        }
    }
    else {
        if($table_name == "artists") {
            if($_SESSION["sess_artistid"] != "") {
                $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."artists
										WHERE artist_id = ".$_SESSION["sess_artistid"];

                $result_user_details = mysql_query($select_user_details) or die(mysql_error());
                if(mysql_num_rows($result_user_details) > 0) {
                    $user_details_row = mysql_fetch_assoc($result_user_details);
                    $txtFirstName = $user_details_row['first_name'];
                    $txtLastName = $user_details_row['last_name'];
                }

            }

        }
        else if($table_name == "affiliates") {

            if($_SESSION["sess_affiliateid"] != "" || $_SESSION["sess_affiliateid_new"] != "") {

                if($_SESSION["sess_affiliateid_new"] != "") {
                    $UserId = $_SESSION["sess_affiliateid_new"];
                }
                if($_SESSION["sess_affiliateid"] != "") {
                    $UserId = $_SESSION["sess_affiliateid"];
                }
                $select_user_details = "SELECT first_name,last_name FROM ".$tableprefix."affiliates
										WHERE affiliate_id = ".$UserId;
                $result_user_details = mysql_query($select_user_details) or die(mysql_error());
                if(mysql_num_rows($result_user_details) > 0) {
                    $user_details_row = mysql_fetch_assoc($result_user_details);
                    $txtFirstName = $user_details_row['first_name'];
                    $txtLastName = $user_details_row['last_name'];
                }
            }

        }else if($table_name == "orders") {
            $order_sql = "select order_id,product_name,product_code,product_price,product_discount,product_quantity from ".$tableprefix."order_details
		                 where order_id = '".$_SESSION["orderid_new"]."' and artist_id = '".$_SESSION["artist_new"]."'";
            $order_rs  =  mysql_query($order_sql) or die(mysql_error());
            if(mysql_num_rows($order_rs) > 0) {
                $order_row    = mysql_fetch_assoc($order_rs);
                $txtOrdrId    = $order_row['order_id'];
                $txtPdtName   = stripslashes($order_row['product_name']);
                $txtPdtCode   = $order_row['product_code'];
                $rate = $order_row["product_price"];
                $qty = $order_row["product_quantity"];
                $price = $rate * $qty;
                if($order_row["product_discount"] !="0") {
                    $price=$price-($price*$order_row["product_discount"]/100);

                }
                $txtPdtPrice  = $currency_attributes[0].' '.$price;
                $txtPdtQty    = $order_row['product_quantity'];
            }

        }

    }
    if(mysql_num_rows($result_email_template) > 0) {

        $email_template_row = mysql_fetch_assoc($result_email_template);
        $email_body = $email_template_row['vemail_body'];



        if($txtFirstName)
            $email_body = str_replace('[first_name]',$txtFirstName,$email_body);
        if($txtLastName)
            $email_body = str_replace('[last_name]',$txtLastName,$email_body);
        if($template_name!='refund_registration_seller') {
            $email_body = str_replace('[seller_first_name]',$txtFirstName,$email_body);
            $email_body = str_replace('[seller_last_name]',$txtLastName,$email_body);
        }
        $email_body = str_replace('[site_name]',SITE_NAME,$email_body);
        if($txtOrdrId)
            $email_body = str_replace('[order_id]',$txtOrdrId,$email_body);
        if($txtPdtName)
            $email_body = str_replace('[product_name]',$txtPdtName,$email_body);
        if($txtPdtCode)
            $email_body = str_replace('[product_code]',$txtPdtCode,$email_body);
        if($txtPdtDiscount)
            $email_body = str_replace('[product_discount]',$txtPdtDiscount,$email_body);
        if($txtPdtPrice)
            $email_body = str_replace('[product_price]',$txtPdtPrice,$email_body);
        $email_body = str_replace('[product_qty]',$txtPdtQty,$email_body);
    }

    $email_body = str_replace("\r\n\r\n", '<br>', $email_body);
    return $email_body;
}

/*function to get the general site settings value*/

function getSettingsValue($field_name) {
    include "../includes/config.php";
    $select_settings_value = "SELECT ".$field_name." FROM ".$tableprefix."settings WHERE 1";
    $result_settings_value = mysql_query($select_settings_value) or die(mysql_error());

    $settings_row = mysql_fetch_assoc($result_settings_value);

    $settings_row[$field_name];
    return $settings_row[$field_name];
}

function displayCurrencyType() {
     include "../includes/config.php"; 

    $currency_array = array();

    $admin_currency = getSettingsValue('admin_currency');

    $select_currency_type = "SELECT vcurrency_symbol,nexchange_price,vcurrency_code FROM ".$tableprefix."currency_master
								 WHERE vactive = 'Y'
                                                                 AND vcurrency_code='" . $admin_currency . "'";

    $result_currency_type = mysql_query($select_currency_type) or die(mysql_error());

    $currency_row = mysql_fetch_assoc($result_currency_type);
    $currencySymbol=$currency_row['vcurrency_symbol'];

    array_push($currency_array,$currency_row['vcurrency_symbol'],$currency_row['nexchange_price'],$currency_row['vcurrency_code']);

    return $currency_array;
}


?>