<?php
if (!function_exists('getallheaders')) 
{
   function getallheaders() 
   {
      foreach ($_SERVER as $name => $value) 
      {
          if (substr($name, 0, 5) == 'HTTP_')
          {               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;

          }
      }
      return $headers;
   }
}
ini_set('display_errors', 0);
error_reporting(0);

$request_url =  'http://' . $_SERVER['HTTP_HOST'] .$_SERVER['REQUEST_URI']; 
$f = @fopen('requestlogs.txt', 'a+');
if ($f) {
  @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$request_url."\n");
  @fclose($f);
}
$result['status'] = 0;
if (isset($_GET['action_type'])) {
    
    /*
     * Access Token Checking
    */
    $accessToken  =  getAccessTokenValue();
   $validityCheck   = 0;
    if($_GET['action_type']!='login' && $_GET['seller_id']!=''){
       $validityCheck =  checkAccessTokenValid($_GET['seller_id'],$accessToken);
    } 
    /*
    * Access Token Checking End
    */

  // $validityCheck=0;

  

    if($validityCheck==0){
        switch ($_GET['action_type']) {

            case 'login': { 
                    $result = loginAPI($_GET['username'],$_GET['password'],$_GET['device_id'],$_GET['device_type']);
                    break;
                }
            case 'forgotpassword':{
                    $result = forgot($_GET['email']);
                break;
            }
            case 'productlist': { 
                    $result = productlistAPI($_GET['seller_id']);
                    break;
                }
            case 'productdetail': { 
                    $result = productDetailsAPI($_GET['product_id'],$_GET['seller_id']);
                    break;
                } 
            case 'orderlist': { 
                    $result = orderlistAPI($_GET['seller_id']);
                    break;
                }
            case 'orderdetails': { 
                    $result = orderDetailsAPI($_GET['order_id'],$_GET['seller_id']);
                    break;
                }   
            case 'paymentlist': { 
                    $result = paymentlistAPI($_GET['seller_id']);
                    break;
                }
            case 'requestforpaymentlist': { 
                    $result = requestForPaymentlistAPI($_GET['seller_id']);
                    break;
                }
            case 'filterpaymentlist': { 
                    $result = filterPaymentlistAPI($_GET['seller_id'],$_GET['status']);
                    break;
                }    
            case 'refundlist':{
                    $result = refundList($_GET['seller_id']);
                    break;
                }
            case 'filterRefundlist':{
                    $result = refundList($_GET['seller_id'],$_GET['refund_status']);
                    break;
                }
            case 'refundDetail':{
                    $result = refundDetailAPI($_GET['seller_id'],$_GET['refund_id']);
                    break;
                }            
            case 'updateproductdetail': {   
                    $result = productupdateAPI();
                    break;    
                }
            case 'reviewlist': { 
                    $result = reviewlistAPI($_GET['seller_id']);
                    break;
                }    
            case 'messagelist': { 
                    $result = messagelistAPI($_GET['seller_id']);
                    break;
                }
            case 'updateorderstatus': { 
                    $result = updateorderStatusAPI($_GET['order_id'],$_GET['status_id']);
                    break;
                }
            case 'changepassword': { 
                    $result = changepasswordAPI($_GET['artist_id'],$_GET['old_password'],$_GET['new_password']);
                    break;
                }
            case 'changeRefundStatus': { 
                    $result = changeRefundStatusAPI();
                    break;
                }
            case 'requestforpayment': { 
                    $result = requestForPaymentAPI($_GET['order_list'],$_GET['seller_id']);
                    break;
                }      
            case 'getUnreadCount': { 
                    $result = getUnreadCountAPI($_GET['seller_id']);
                    break;
                }
            case 'deleteProduct': { 
                    $result = deleteProductAPI($_GET['product_id']);
                    break;
                } 
            case 'deleteMessage': { 
                    $result = deleteSellerMessageAPI($_GET['message_id']);
                    break;
                }  
            case 'categoryList':{
                    $result = getCategoriesAPI();
                    break;
                }
            case 'subCategoryList':{
                    $result = getCategoriesAPI($_GET['category_id']);
                    break;
                }    
            case 'addProduct':{
                    $result = addProductAPI();
                    break;
                } 
            case 'sellerProfile':{
                $result = sellerProfileAPI($_GET['seller_id']);
                break;
            }           
            case 'editSellerProfile':{
                $result = editSellerProfileAPI();
                break;
            }        
            default: {
                    $result['status'] = 0;
                    $result['data'] = "Not a valid request";
                    break;
                }
        }
     }else{
          $result['status'] = 0;
          $result['data']   = "Invalid Access Token";
     }
} else {
    $result['status'] = 0;
    $result['data'] = "Not a valid request";
}
print_r(json_encode($result));


//---- Seller Forgot Password API ---//
function forgot($mail) 
{
   include "../includes/config.php";
   if (isset($mail))
   {
       include "../includes/config.php";
       $sql = "SELECT * FROM ".$tableprefix."artists WHERE email='".$mail."' AND deleted='N' AND vapproved='Y'";
       $queryResult = mysql_query($sql) or die (mysql_error());
       if(mysql_num_rows($queryResult) === 1)
       {
            $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            $passwordNew = '';
            for ($i = 0; $i < 6; $i++)
            {
                $passwordNew .= $characters[mt_rand(0, 61)];
            }
            
            $updateSql = "UPDATE ".$tableprefix."artists SET password='".  addslashes(md5($passwordNew))."' WHERE email='".$mail."'";
            mysql_query($updateSql);
            
           
            $subject = MAIL_ADMIN_FORGOT_PASSWORD_SUBJECT_1." ".htmlentities(stripslashes(SITE_NAME)) . " ".MAIL_ADMIN_FORGOT_PASSWORD_SUBJECT_2;
            $message = "<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><p>Dear recipient,<br/>We have recieved a request to reset your password.<br/>The new password is ".$passwordNew."<br/><br/>Thanks<br/>".SITE_NAME." Team. </p></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";
            mail($mail, $subject, $message,$headers);
            $currentstatus['status'] = 1;
            $currentstatus['data'] = "Password Reset. The new password sent to user email. ";
            
       }
       else
       {
           $currentstatus ['status'] = 0;
           $currentstatus ['data'] = "This email id is not registered";
       }
   }
   else
   {
       $currentstatus ['status'] = 0;
       $currentstatus ['data'] = "Email id is missing";
   }
   
   return $currentstatus;
}

//---- Seller Login API ---//
function loginAPI($username=NULL,$password=NULL,$deviceId=NULL,$deviceType=NULL) { 
    include "../includes/config.php";
    if (isset($username) && isset($password)) {
        
        $sql = "SELECT * FROM ".$tableprefix."artists 
			WHERE artist_name='".addslashes($username)."' 
			AND password = '".addslashes($password)."' AND deleted = 'N' AND vapproved='Y' ";
        
        
			$result=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result) > 0 )
			{                           
                            $row = mysql_fetch_assoc($result);   
                            $artist_id = $row['artist_id'];
                            //--- Update seller device ID or Insert Device Id ---//
                            if(isset($deviceId)){
                                  $sql_devices = "SELECT * FROM ".$tableprefix."artist_devices 
                                                    WHERE artist_id='".addslashes($artist_id)."' 
                                                    AND device_id like '".addslashes($deviceId)."%' AND device_type='".$deviceType."'";
                                 
                                 
                                  $result_devices = mysql_query($sql_devices) or die(mysql_error());
                                 
                                    if(mysql_num_rows($result_devices)==0){
                                         $sql = "INSERT INTO " . $tableprefix . "artist_devices (
                                                    artist_id ,
                                                    device_id ,
                                                    device_type,
                                                    date_added
                                                    ) VALUES (
                                                    '" . addslashes($artist_id) . "',
                                                    '" . addslashes($deviceId) . "',
                                                    '" . addslashes($deviceType) . "',
                                                    now()

                                                    )";
                                        
                                         mysql_query($sql) or die(mysql_error());
                                    }
                                
                               
                            }
                            $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);       
    }
   
}

//----- Product List for seller API ------//
function productlistAPI($sellerId=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($sellerId)) {
        
    $sql = "SELECT prd.product_id,prd.product_name,
           (prd.product_price+po.additional_price) AS product_price,
            prd.date_added,po.discount,cat.category_name,payment_status,po.product_stock,           
            CASE WHEN image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS product_image_small,  
            CASE WHEN image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS product_image_big,      
           (SELECT COUNT(pi.product_impression_id)
              FROM ".$tableprefix."product_impression pi
              WHERE pi.product_id = prd.product_id) AS impression_count
              FROM ".$tableprefix."products prd
                INNER JOIN ".$tableprefix."product_options po ON po.product_id = prd.product_id AND po.default_option = 'YES'
                INNER JOIN ".$tableprefix."categories cat ON prd.product_category = cat.category_id
		WHERE prd.product_artist_id = ".$sellerId. " AND cat.gift_certificate_flag !='Y' ORDER BY prd.product_id DESC";
             
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                {                           
                    $row = fetchAll($result);
                    foreach ($row as $value) {                      
                        //--- Update seller view status ---//
                        $sql = "UPDATE ".$tableprefix."products SET seller_viewed_status = 1 WHERE product_id = '".addslashes($value->product_id)."'";			
                        mysql_query($sql) or die (mysql_error());
                    }
                    $setting_sql = "SELECT product_listing_fee FROM ".$tableprefix."settings ";	        
                    $setting_result=mysql_query($setting_sql) or die(mysql_error());			
                    if(mysql_num_rows($setting_result) > 0 )
                    {                           
                        $settingVal = mysql_fetch_assoc($setting_result); 
                        $enableProductAdd = ($settingVal['product_listing_fee']==0)?1:0;        
                    }
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = $row;
                    $currentstatus['enableProductAdd'] = $enableProductAdd;
                    return($currentstatus);  
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "No products added.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID missing.";
        return($currentstatus);       
    }
    
}
//----- Product Details API ------//
function productDetailsAPI($productId=NULL,$artistId=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 *  FROM ".$tableprefix."products     
            WHERE ".$tableprefix."products.product_id= '".addslashes($productId)."' and ".$tableprefix."products.product_artist_id = '".addslashes($artistId)."'  ";
        
			$result1=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result1) > 0 )
			{                           
                            $row1 = mysql_fetch_assoc($result1);
                            $sql = "SELECT product_option_id,additional_price,product_stock,discount FROM ".$tableprefix."product_options Options
                            WHERE Options.product_id = '".addslashes($productId)."'";        
                            $result2=mysql_query($sql) or die(mysql_error());			
                            if(mysql_num_rows($result2) > 0 )
                            {
                                $row2 = fetchAll($result2);                                
                                $res = $row1;
                                $res['options'] = $row2; //$res  = array_merge($row1,$row2);
                                foreach ($res['options'] as $key => $value) {                                       
                                     $sql = "SELECT optionval.value as optionValue, opt_name.option_name as optionName FROM ".$tableprefix."product_option_values optionval
                                             LEFT JOIN ".$tableprefix."options opt_name ON opt_name.option_id = optionval.option_id
                                             WHERE optionval.product_option_id = '".$value->product_option_id."'";        
                                     $result3=mysql_query($sql) or die(mysql_error());
                                     $row3 = fetchAll($result3);   
                                     $res['options'][$key]->optionAttributes = $row3;
                                }
                            }
                            $currentstatus['status'] = 1;
                            $currentstatus['data']   = $res;
                            return($currentstatus);  
                        } else {
                             $currentstatus['status'] = 0;
                             $currentstatus['data'] = "Invalid productId/sellerId.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "ProductId/sellerId missing.";
        return($currentstatus);       
    }
}

//---- Get unread count of Products order  ----//
function getUnreadCountAPI($sellerId=NULL){
    include "../includes/config.php";        
    if (isset($sellerId)) {
        $sql = "SELECT * FROM
                (SELECT COUNT(product_id) as product_count FROM ". $tableprefix ."products WHERE seller_viewed_status = 0 AND product_artist_id = ".$sellerId.") as T1, 
                (SELECT COUNT(DISTINCT(o.order_id)) as order_count FROM ". $tableprefix ."orders o INNER JOIN ". $tableprefix ."order_details od ON o.order_id = od.order_id  WHERE o.seller_viewed_status = 0 AND od.artist_id = ".$sellerId.") as T2,
                (SELECT COUNT(artist_payment_id) as payment_count FROM ". $tableprefix ."artist_payments WHERE seller_viewed_status = 0 AND artist_id = ".$sellerId.") as T3,
                (SELECT COUNT(DISTINCT(p.product_artist_id)) as review_count FROM " . $tableprefix . "Review r LEFT JOIN " . $tableprefix . "products p ON r.nProdId=p.product_id WHERE r.seller_viewed_status = 0 AND p.product_artist_id=" . $sellerId.") as T4,
                (SELECT COUNT(DISTINCT(refund_id)) as refund_count FROM ". $tableprefix ."refunds WHERE seller_viewed_status = 0 AND seller_id = ".$sellerId.") as T5,
                (SELECT COUNT(message_to_seller_id) as message_count FROM ". $tableprefix ."message_to_seller WHERE seller_viewed_status = 0 AND artist_id = ".$sellerId.") as T6";              
                
                $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;
                     $setting_sql = "SELECT product_listing_fee FROM ".$tableprefix."settings ";	        
                        $setting_result=mysql_query($setting_sql) or die(mysql_error());			
                        if(mysql_num_rows($setting_result) > 0 )
                        {                           
                            $settingVal = mysql_fetch_assoc($setting_result); 
                            $enableProductAdd = ($settingVal['product_listing_fee']==0)?1:0;        
                        }
                        $currentstatus['data']['enableProductAdd'] = $enableProductAdd;
                     return($currentstatus);                      
                }else {
                    $currentstatus['status'] = 0;
                    $currentstatus['data'] = "Invalid seller ID.";
                    return($currentstatus); 
               }
    }else{
         $currentstatus['status'] = 0;
         $currentstatus['data']   = "Seller ID missing.";
         return($currentstatus);       
    }
}
//----- Seller Order List API ------//
function orderlistAPI($sellerId=NULL) {
    
    include "../includes/config.php";       
    include "../classes/cls_order.php";
    if (isset($sellerId)) {      
    $sql = "SELECT o.order_id, u.user_name,  u.email, od.product_discount,sum( (od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as total,sum(od.product_tax)as taxtotal,os.order_status
		FROM " . $tableprefix . "orders o 
		INNER JOIN " . $tableprefix . "users u ON o.user_id = u.user_id 
		INNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id 
                INNER JOIN " . $tableprefix . "order_status os ON od.item_status = os.order_status_id 
		WHERE od.artist_id = '" . addslashes($sellerId) . "'
		AND o.vpayment_status != 'P'";
    $sql.=" GROUP BY o.order_id ORDER BY o.order_date DESC ";
             
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                {                           
                    $row = fetchAll($result);                    
                    foreach ($row as $key=> $value) { 
                        $orderShippingCost = 0;  
                        //--- Update seller view status ---//
                        $sql = "UPDATE ".$tableprefix."orders SET seller_viewed_status = 1 WHERE order_id = '".addslashes($value->order_id)."'";			
                        mysql_query($sql) or die (mysql_error());
                        $sql2 = "SELECT order_id,product_option_id,product_id
                             FROM ".$tableprefix."order_details                             
                             WHERE order_id = ".$value->order_id;  
                        
                        $result2=mysql_query($sql2) or die(mysql_error());			
                        if (mysql_num_rows($result2) > 0) {
                            $row2 = fetchAll($result2);                       
                            foreach ($row2 as $key_detail => $detail_val) {

                                /*$sql3 = "SELECT nshipping_cost
                                               FROM  " . $tableprefix . "shipping_details                                              
                                               WHERE nproduct_option_id = '" . $detail_val->product_option_id . "'
                                               AND nshp_productid = ".$detail_val->product_id." AND norder_id = " . $detail_val->order_id;                                              

                                $result3 = mysql_query($sql3) or die(mysql_error());
                                $row3 = fetchAll($result3);                            
                                $orderShippingCost = $orderShippingCost+$row3[0]->nshipping_cost;*/
                                $orderShippingCost =    Order::orderShippingCost($detail_val->order_id,$sellerId);
                                
                            }
                       }   
                       $ord_total = $row[$key]->total+$row[$key]->taxtotal+$orderShippingCost;
                       $row[$key]->total = (string)$ord_total;
                    }                    
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = $row;
                    return($currentstatus);  
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "No orders received.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID missing.";
        return($currentstatus);       
    }
    
}

function refundList ($sellerId=NULL,$refund_status=NULL)
{
    if(isset($sellerId))
    {
        include "../includes/config.php";
        if(isset($refund_status))
        {
           $refundSql = "SELECT refund.refund_id, refund.buyer_id, refund.Additional_info, users.first_name, users.last_name, users.address1, users.address2, users.city, users.state, users.country, countries.country_name, users.email, refund.order_id, refund.product_id, products.product_name, products.product_price, refund.quantity, refund.return_reason, refund.Customer_Feedback, refund.Status, refund.reference_number, refund.refund_mode, orders.* FROM ".$tableprefix."refunds refund INNER JOIN ".$tableprefix."users users ON refund.buyer_id=users.user_id INNER JOIN ".$tableprefix."products products ON refund.product_id=products.product_id INNER JOIN ".$tableprefix."countries countries ON users.country=countries.country_iso_code_2 INNER JOIN ".$tableprefix."orders orders ON refund.order_id=orders.order_id WHERE refund.seller_id=".$sellerId." AND refund.Status LIKE '".$refund_status."'"; 
        }else{
           $refundSql = "SELECT refund.refund_id, refund.buyer_id, refund.Additional_info, users.first_name, users.last_name, users.address1, users.address2, users.city, users.state, users.country, countries.country_name, users.email, refund.order_id, refund.product_id, products.product_name, products.product_price, refund.quantity, refund.return_reason, refund.Customer_Feedback, refund.Status, refund.reference_number, refund.refund_mode, orders.* FROM ".$tableprefix."refunds refund INNER JOIN ".$tableprefix."users users ON refund.buyer_id=users.user_id INNER JOIN ".$tableprefix."products products ON refund.product_id=products.product_id INNER JOIN ".$tableprefix."countries countries ON users.country=countries.country_iso_code_2 INNER JOIN ".$tableprefix."orders orders ON refund.order_id=orders.order_id WHERE refund.seller_id=".$sellerId."";
        }
        $refundsList = mysql_query($refundSql);
        if (mysql_num_rows($refundsList)>0)
        {
            $row = fetchAll($refundsList);
            foreach ($row as $value) {                      
                //--- Update seller view status ---//
                $sql = "UPDATE ".$tableprefix."refunds SET seller_viewed_status = 1 WHERE refund_id = '".addslashes($value->refund_id)."'";			
                mysql_query($sql) or die (mysql_error());
            }
            $currentstatus ['status'] = 1;
            $currentstatus ['data'] = $row;
        }
        else
        {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No results found";
        }
    }
    else
    {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID missing.";
    }
    return $currentstatus;
}

// Refund Details
function refundDetailAPI ($sellerId=NULL,$refund_id=NULL)
{
    if(isset($refund_id))
    {
        include "../includes/config.php";
       
         $sql="select  o.billing_first_name,o.billing_last_name,o.billing_email,a.artist_name,od.product_name,r.status,r.*,sum(od.product_price * r.quantity) as refundamt,sum((od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as refundtotal
	 from ".$tableprefix."orders o ,".$tableprefix."artists a , ".$tableprefix."refunds r, ".$tableprefix."order_details od
	 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.seller_id=".$sellerId." and r.refund_id=".$refund_id." ";         
        
        $refundsDetail = mysql_query($sql);
        if (mysql_num_rows($refundsDetail)>0)
        {
            $row = mysql_fetch_assoc($refundsDetail);
            $currentstatus ['status'] = 1;
            $currentstatus ['data'] = $row;
        }
        else
        {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "No results found";
        }
    }
    else
    {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Refund ID missing.";
    }
    return $currentstatus;
}

//----- Order Details API ------//
function orderDetailsAPI($orderId=NULL,$artistId=NULL){
    include "../includes/config.php";    
    include "../classes/cls_order.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($orderId) && isset($artistId)) {
    $totalshippingAmount     =    Order::orderShippingCost($orderId,$artistId);
    $taxtotal                =    Order::getorderTaxTotal($orderId,$artistId); //enabled by me     
    $sql = "SELECT o.*, u.user_name as Orderedby, os.order_status,sum( (od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as Ordertotal,sum(od.product_tax)as taxtotal
		FROM ".$tableprefix."orders o
		INNER JOIN ".$tableprefix."users u ON o.user_id = u.user_id
		INNER JOIN ".$tableprefix."order_details od ON o.order_id = od.order_id
                INNER JOIN ".$tableprefix."order_status os ON od.item_status = os.order_status_id
		WHERE od.artist_id = '".addslashes($artistId)."'
                AND o.order_id = '".addslashes($orderId)."'
		AND o.vpayment_status != 'P'" . $qryopt1 . " GROUP BY o.order_id ORDER BY o.order_date,o.order_id DESC";
        
			$result1=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result1) > 0 )
			{ 
                           
                            $row1 = mysql_fetch_assoc($result1);                            
                            $row1['billing_state']  =  getCodeValue($row1['billing_state'], 2,$row1['billing_country'])!=''?getCodeValue($row1['billing_state'], 2,$row1['billing_country']):'-';
                            $row1['billing_country']=  getCodeValue($row1['billing_country'], 1)!=''?getCodeValue($row1['billing_country'], 1):'-';
                            $row1['shipping_state']  =  getCodeValue($row1['shipping_state'], 2,$row1['shipping_country'])!=''?getCodeValue($row1['shipping_state'], 2,$row1['shipping_country']):'-';
                            $row1['shipping_country']=  getCodeValue($row1['shipping_country'], 1)!=''?getCodeValue($row1['shipping_country'], 1):'-';
                            $row1['order_shippingTotal'] = $totalshippingAmount;
                            //$row1['order_taxtotal']      = $taxtotal;
                            
                            //added by me
                            $itemTotal              =    $row1["Ordertotal"];
                            if($row1['vgiftcertificate_code']!='' && $row1['nused_gift_amount']!=0 ){
                                                                    
                                          $giftCertificateAmount        =   $row1['nused_gift_amount'];  
                                          
                                          //$itemTotal                    =   $itemTotal - $row['nused_gift_amount'];
                                          
                                    }  
                                    
                                     if(($artistid==$row1['couponCodeSeller_Id']) && ($row1['couponCodeDiscount']>0))
                                        {
                                            $couponCodeDiscountAmount       =   $row1['couponCodeDiscount'];
                                            
                                            //$itemTotal                      = $itemTotal - $couponCodeDiscountAmount;
                                        } 
                                        
                                        
                                        $totalDiscountAmount                =   $giftCertificateAmount + $couponCodeDiscountAmount;
                                        
                                        if($totalDiscountAmount>0)
                                        {
                                            $newTotal   =   $itemTotal -  $totalDiscountAmount; 
                                        }else{
                                            $newTotal   =   $itemTotal;
                                        }
                                        $ordertotal = $newTotal + $taxtotal + $totalshippingAmount ;
                            $row1['order_total_price'] = (string)$ordertotal;
                            //----------------------
                            $sql = "SELECT order_detail_id
                             FROM ".$tableprefix."order_details                             
                             WHERE order_id = ".$orderId;        
                            
                            $result2=mysql_query($sql) or die(mysql_error());			
                            if(mysql_num_rows($result2) > 0 )
                            {                                
                                $row2 = fetchAll($result2);                                   
                                $res = $row1;
                                
   /*******************/                             
            foreach ($row2 as $value) {
                
                    $sql_1 = "SELECT od.product_id,od.product_name, od.product_code, od.product_quantity,od.product_price,od.product_discount,od.product_price * od.product_quantity as productTotal
                                            FROM " . $tableprefix . "order_details od                                            
                                            WHERE od.artist_id = '" . addslashes($artistId) . "'
                                            AND od.order_id = '" . addslashes($orderId) . "'
                                            AND od.order_detail_id = " . $value->order_detail_id;
                    $result_new = mysql_query($sql_1) or die(mysql_error());
                    $row_new = fetchAll($result_new);
                    if(!empty($row_new))
                    $arr_order_detail_id[] = $value->order_detail_id; //$res  = array_merge($row1,$row2);
                }
   /************************/   
                                
                                foreach ($arr_order_detail_id as $key => $value) {                                
                                    /* $sql = "SELECT od.product_id,od.product_name, od.product_code, od.product_quantity,od.product_price,od.product_discount,od.product_price * od.product_quantity as productTotal,sd.vshipping_name, sd.nshipping_cost,sd.nshp_productname
                                            FROM ".$tableprefix."order_details od
                                            INNER JOIN ".$tableprefix."shipping_details sd  ON (sd.nshp_productid = od.product_id AND sd.nproduct_option_id = od.product_option_id AND sd.norder_id=od.order_id)    
                                            WHERE od.artist_id = '".addslashes($artistId)."'
                                            AND od.order_id = '".addslashes($orderId)."'
                                            AND od.order_detail_id = ".$value->order_detail_id;  */
                                     //sd.vshipping_name, sd.nshipping_cost,sd.nshp_productname excluded
                                     $sql = "SELECT od.product_id,od.product_name, od.product_code, od.product_quantity,od.product_price,od.product_discount,(od.product_price * od.product_quantity)-(od.product_price * od.product_quantity*(od.product_discount/100)) as productTotal,sd.vshipping_name, sd.nshipping_cost
                                            FROM ".$tableprefix."order_details od        
                                            INNER JOIN ".$tableprefix."shipping_details sd  ON sd.norder_id=od.order_id      
                                            WHERE od.artist_id = '".addslashes($artistId)."'
                                            AND od.order_id = '".addslashes($orderId)."'
                                            AND od.order_detail_id = ".$value;                                       

                                     $result3=mysql_query($sql) or die(mysql_error());
                                     $row3 = fetchAll($result3); 
                                     /*if($row3[0]!=''){
                                     $row3[0]->vshipping_name="-";
                                     $row3[0]->nshipping_cost="-";
                                     $row3[0]->nshp_productname="-";
                                     }*/
                                     //var_dump($row3[0]);
                                     if($row3[0]==''||$row3[0]==NULL)
                                         {continue;/*unset ($res['orderDetails'][$key]);*/}
                                     else{   
                                     $res['orderDetails'][$key]->productDetail = ($row3[0]!='')?$row3[0]:array("nshipping_cost" =>"-",
                                                                                        "nshp_productname" => '-',
                                                                                        "productTotal" => '-',
                                                                                        "product_code" => '-',
                                                                                        "product_discount" => '-',
                                                                                        "product_id" => "-",
                                                                                        "product_name" => "-",
                                                                                        "product_price" => "-",
                                                                                        "product_quantity" => "-",
                                                                                        "vshipping_name" => "-");
                                      }
                                }
                                
                            }                             
                            
                            $currentstatus['status'] = 1;
                            $currentstatus['data']   = $res;
                            return($currentstatus);  
                        } else {
                             $currentstatus['status'] = 0;
                             $currentstatus['data'] = "Invalid orderId/sellerId.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "OrderId/sellerId missing.";
        return($currentstatus);       
    }
}

//---Payment List API ----//
function paymentlistAPI($artistid = NULL){ 
    include "../includes/config.php";        
    if (isset($artistid)) {
        
    $sql = "SELECT sp.*,s.artist_name FROM " . $tableprefix . "artist_payments sp
		INNER JOIN  " . $tableprefix . "artists s ON sp.artist_id = s.artist_id
                INNER JOIN  " . $tableprefix . "orders o ON o.order_id = sp.order_id
		WHERE sp.artist_id = '" . addslashes($artistid) . "' AND o.vpayment_status='C'
		order by sp.artist_payment_id DESC ";   
             
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                {                           
                    $row = fetchAll($result);
                    foreach ($row as $value) {                      
                        //--- Update seller view status ---//
                        $sql = "UPDATE ".$tableprefix."artist_payments SET seller_viewed_status = 1 WHERE artist_payment_id = '".addslashes($value->artist_payment_id)."'";			
                        mysql_query($sql) or die (mysql_error());
                    }
                    $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'] = "Seller ID missing.";
        return($currentstatus);       
    }
}

//---Request for Payment List API ----//
function requestForPaymentlistAPI($artistid = NULL){ 
    include "../includes/config.php";       
    include "../classes/cls_order.php";       
    if (isset($artistid)) {
        
    $sql = "SELECT o.*, u.user_name, u.email, od.product_discount,sum(((od.product_price-(od.product_price*product_discount/100)) * od.product_quantity)) as total ,sum(od.product_commission_amount)as adminamount,sum(od.product_tax) as taxtotal
        FROM " . $tableprefix . "orders o 
		INNER JOIN " . $tableprefix . "users u ON o.user_id = u.user_id 
		INNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id 
                
		WHERE od.artist_id = '" . addslashes($artistid) . "' 
		AND od.item_status = '4'
		AND od.artist_payment_status = '0' 
		GROUP BY o.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) {                        
                        $select_shipping_cost = "SELECT  sd.nshipping_cost,sd.nshp_productname
                                        FROM ".$tableprefix."shipping_details sd
                                        INNER JOIN ".$tableprefix."order_details  od ON (od.product_id=sd.nshp_productid AND od.product_option_id=sd.nproduct_option_id AND od.order_id=sd.norder_id)
                                        WHERE sd.norder_id = ".$value->order_id." AND od.artist_id = '".$artistid."' AND  sd.nshp_status = 'C' order by sd.nshp_productname";
          
                             
                            $result_shipping_cost = mysql_query($select_shipping_cost);
                            $totalshippingcost = 0;


                            $itemTotal       = $value->total;

                            if($value->vgiftcertificate_code!='' && $value->nused_gift_amount!=0 ){

                                  $giftCertificateAmount        =   $value->nused_gift_amount;  

                                  $itemTotal                    =   $itemTotal - $value->nused_gift_amount;

                            }                                    
                            $ordertotal = $itemTotal + $value->taxtotal;


                           /* if (mysql_num_rows($result_shipping_cost) > 0) {

                                while ($shipping_row = mysql_fetch_array($result_shipping_cost)) {                                    
                                    $totalshippingcost+=$shipping_row['nshipping_cost'];
                                }
                            }*/
                            $totalshippingcost      =    Order::orderShippingCost($value->order_id,$artistid);
                            $ordertotal+=$totalshippingcost;                            
                            $amountRecevable    = $ordertotal - $value->adminamount;
                            $row[$key]->order_total_price = (string)$ordertotal;
                            $row[$key]->seller_amt_recevable = (string)$amountRecevable;
                    }
                    
                    $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'] = "Seller ID missing.";
        return($currentstatus);       
    }
}

//---Filter Payment List ---//
function filterPaymentlistAPI($artistid = NULL,$status = NULL){
    include "../includes/config.php";        
    if (isset($artistid)) {
        
    $sql = "SELECT sp.*,s.artist_name FROM " . $tableprefix . "artist_payments sp
		INNER JOIN  " . $tableprefix . "artists s ON sp.artist_id = s.artist_id
                INNER JOIN  " . $tableprefix . "orders o ON o.order_id = sp.order_id
		WHERE sp.artist_id = '" . addslashes($artistid) . "' AND sp.payment_status = '" . addslashes($status) . "' AND o.vpayment_status='C'
		order by sp.artist_payment_id DESC ";   
             
                $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 records found.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID missing.";
        return($currentstatus);       
    }
}

//---Add a new product API---//
function addProductAPI(){
    include "../includes/config.php"; 
    include_once('../classes/cls_utils.php');
    include_once('../classes/cls_products.php');
    include_once('../includes/class.upload.php');
    include_once('../includes/S3.php');
    include "apifunctions.php";   
    
    $sql = "SELECT product_listing_fee FROM ".$tableprefix."settings ";	        
    $result=mysql_query($sql) or die(mysql_error());			
    if(mysql_num_rows($result) > 0 )
    {                           
        $row = mysql_fetch_assoc($result);   
        $ProductListingFee = $row['product_listing_fee'];        
    }
    
    if ($ProductListingFee == 0) {

        if (isset($_REQUEST['pName']) && $_REQUEST['pName'] != NULL) {
            
            //Generate Alias name for product
            $aliasname = Utils::generateAlias($tableprefix . "products", $_REQUEST['pName']);   
            
            $txtProductapproval = getSettingsValue('approve_products');
            
             if ($txtProductapproval == 1) {
            
                $vapproved = 'Y';
            } else {
                $vapproved = 'N';
            }
            
            $arrProduct['pName'] = stripslashes($_REQUEST['pName']);
            $arrProduct['pCode'] = stripslashes($_REQUEST['pCode']);
            $arrProduct['catId'] = stripslashes($_REQUEST['catId']);
            $arrProduct['des'] = stripslashes($_REQUEST['des']);
            $arrProduct['price'] = stripslashes($_REQUEST['price']);
            $arrProduct['stock'] = stripslashes($_REQUEST['stock']);
            $arrProduct['shipWeight'] = stripslashes($_REQUEST['shipWeight']);
            $arrProduct['length'] = stripslashes($_REQUEST['length']);
            $arrProduct['width'] = stripslashes($_REQUEST['width']);
            $arrProduct['height'] = stripslashes($_REQUEST['height']);
            $arrProduct['additionalPrice'] = stripslashes($_REQUEST['additionalPrice']);
            $arrProduct['discount'] = stripslashes($_REQUEST['discount']);
            $arrProduct['sellerId'] = stripslashes($_REQUEST['sellerId']);

            //$imgName = "productoriginal_" . rand(0,1000) . "_" . time() . ".jpeg";
            //move_uploaded_file($_FILES["image"]["tmp_name"], "../products/" . $imgName);

            $sql = "INSERT INTO " . $tableprefix . "products (
			product_name ,
			product_code ,
			product_description,
			product_price,
			vdigital_product,
			product_category,
			product_artist_id,
			date_added,
			vapproved,
                        payment_status,
                        seller_viewed_status,
                        alias,
                        publish_status,
                        default_stock,     
                        default_additional_price,
                        default_shipping_weight,
                        default_discount,
                        seller_vacation_mode
			) VALUES (
			'" . addslashes($arrProduct['pName']) . "',
			'" . addslashes($arrProduct['pCode']) . "',
			'" . addslashes($arrProduct['des']) . "',
			'" . addslashes($arrProduct['price']) . "',
			'N',
			'" . addslashes($arrProduct['catId']) . "',
			'" . addslashes($arrProduct['sellerId']) . "',
			now(),
                        '" . addslashes($vapproved) . "',
                        'COMPLETED',
                        1,
                        '$aliasname',
                        'Y',    
                        '" . addslashes($arrProduct['stock']) . "',			
                        '" . addslashes($arrProduct['additionalPrice']) . "',
                        '" . addslashes($arrProduct['shipWeight']) . "',
                        '" . addslashes($arrProduct['discount']) . "',
                        'N'    
			)";

            mysql_query($sql) or die(mysql_error());
            $product_insert_id = mysql_insert_id();
            
            //-------Image resize section-----------------------

            $picname = ReplaceArrayImage($_FILES['image']['name']);
            $dir_dest = "../products";
            $final_image_big = "";
            $final_image_small = "";

            if($picname != "")
            {
               $i=0;
               $picArr = explode('.', $picname);
               $cntCountParams = count($picArr);
               $name_with_out_extension = str_replace('.' . $picArr[$cntCountParams-1], '', $picname);
               $final_image_big = "productbig_" . $product_insert_id . "_" . $i . "_" . time() . $name_with_out_extension;
               $final_image_small = "productsmall_" . $product_insert_id . "_" . $i . "_" . time() . $name_with_out_extension;
            }
            $picbigname = $final_image_big;
            $picsmallname = $final_image_small;
            
            $handle = new Upload($_FILES['image']);
            if($handle->uploaded) {

                $handle->image_resize = true;
                $handle->image_ratio = true;
                
                $handle->image_x = 489;
                $handle->image_y = 328;
                $handle->file_new_name_body = $picbigname;
                $handle->process($dir_dest);
                $big_image_name_after_upload = $handle->file_dst_name;
                $imagepath             = "../products/".$big_image_name_after_upload;
                moveImageToCDN($imagepath,'products/'.$big_image_name_after_upload);

                $handle->image_resize = true;
                $handle->image_ratio = true;
                $handle->image_x = 387;
                $handle->image_y = 260;
                $handle->file_new_name_body = $picsmallname;
                $handle->process($dir_dest);
                $small_image_name_after_upload = $handle->file_dst_name;
                $imagepath             = "../products/".$small_image_name_after_upload;
                moveImageToCDN($imagepath,'products/'.$small_image_name_after_upload);

                $handle->image_resize = true;
                $handle->image_ratio = true;
                $big_file_name                  = "thumb_".$picbigname;
                $handle->file_new_name_body     = $big_file_name;
                $handle->image_x                = 82;
                $handle->image_y                = 79;
                $handle->process($dir_dest);
                $imagethumbpath  = "../products/".$big_file_name;
                moveImageToCDN($imagethumbpath,'products/'.$big_file_name);
            }


            //--------------------------------------------------

            $sellerName= Utils::getsellerName($arrProduct['sellerId']);            
            $sqlOptions = "INSERT INTO " . $tableprefix . "product_options (
			product_id,
			additional_price,
			product_stock,			
			product_shipping_weight,
                        image_small,
                        image_big,
                        discount,                      
                        product_length,
                        product_width,
                        product_height,
                        default_option

			) VALUES (
			'" . addslashes($product_insert_id) . "',
			'" . addslashes($arrProduct['additionalPrice']) . "',
			'" . addslashes($arrProduct['stock']) . "',			
			'" . addslashes($arrProduct['shipWeight']) . "',
			'" . addslashes($small_image_name_after_upload) . "',
			'" . addslashes($big_image_name_after_upload) . "',
			'" . addslashes($arrProduct['discount']) . "',			
                        '" . addslashes($arrProduct['length']) . "',
                        '" . addslashes($arrProduct['width']) . "',
                        '" . addslashes($arrProduct['height']) . "',
                        'YES'
			)";
            if (mysql_query($sqlOptions)) {
                        $product_option_id = mysql_insert_id();
                        $sql = "UPDATE  ".$tableprefix."products SET
			seller_name = '".addslashes($sellerName)."',
			default_option_id = '".addslashes($product_option_id)."'";			
                $sql .=" WHERE product_id = '".addslashes($product_insert_id)."' ";      
                
                mysql_query($sql) or die (mysql_error());

                        $sql = "UPDATE  ".$tableprefix."products SET
			default_image_small = '".addslashes($small_image_name_after_upload)."'";
                $sql .=" WHERE product_id = '".addslashes($product_insert_id)."' ";

                mysql_query($sql) or die (mysql_error());

                $currentstatus['status'] = 1;
                $currentstatus['data'] = "Product added";
                return($currentstatus);
            } else {
                $currentstatus['status'] = 0;
                $currentstatus['data'] = "Sorry, product not added..";
                return($currentstatus);
            }
        } else {
            $currentstatus['status'] = 0;
            $currentstatus['data'] = "Insufficient data.";
            return($currentstatus);
        }
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Site settings do not permit you to add product from the APP";
        return($currentstatus);
    }
   
    
}

//---Product Details Update API---//
function productupdateAPI(){
    include "../includes/config.php";
    
    
  $currentstatus['data'] = json_decode(stripslashes($_REQUEST['product']));
    
    $seller_id             = $currentstatus['data']->seller_id;
    $product_id            = $currentstatus['data']->product_id;    
    if (isset($product_id)) {
        
    $product_options = json_decode($currentstatus['data']->options);
        // Primary product details
        $sql = "UPDATE  ".$tableprefix."products SET
			product_name = '".addslashes($currentstatus['data']->product_name)."',
			product_code = '".addslashes($currentstatus['data']->product_code)."',			
			product_price = '".addslashes($currentstatus['data']->product_price)."'";
        $sql .=" WHERE product_id = '".addslashes($product_id)."' ";      
       
        mysql_query($sql) or die (mysql_error());
        
        foreach ($product_options as $key => $value) {             
            // product details options
            $sqlOptions = "UPDATE ".$tableprefix."product_options SET                            
                            additional_price = '".addslashes($value->additional_price)."',
                            product_stock = '".addslashes($value->product_stock)."',
                            discount = '".addslashes($value->discount)."'                       
                            WHERE product_option_id = ".$value->product_option_id;
            
             mysql_query($sqlOptions) or die(mysql_error()); 
             
             // get option value Ids
             $product_option_values = $value->optionsvalues;   
             foreach ($product_option_values as $key => $opt_value) { 
                  $opt_key = key($opt_value);
                  $sql = "SELECT option_id FROM ".$tableprefix."options 
                            WHERE option_name='".$opt_key."'"; 
                  $result=mysql_query($sql) or die(mysql_error());                  
                  
                if(mysql_num_rows($result) > 0 )
                {   
                   $res = mysql_fetch_assoc($result);                   
                   // option values
                   $sqlOptions = "UPDATE ".$tableprefix."product_option_values SET                            
                            value = '".$opt_value->$opt_key."'                                                 
                            WHERE product_option_id = '".$value->product_option_id."' AND option_id = ".$res['option_id'];
                   mysql_query($sqlOptions) or die(mysql_error());    
                    
                }
             }
           // update option value end               
             
        } 
            $sql = "SELECT * FROM " . $tableprefix . "product_options p
                                        WHERE p.product_id ='" . $product_id . "' AND default_option='YES'";

                  $result = mysql_query($sql);
             if (mysql_num_rows($result) != 0) {
                 
                 $objOptionVo = mysql_fetch_object($result);
                
                 
             }

            $objDefaultOptionVo->default_image_small = $objOptionVo->image_small;

            $objDefaultOptionVo->default_additional_price = $objOptionVo->additional_price;
            $objDefaultOptionVo->default_shipping_weight = $objOptionVo->product_shipping_weight;
            $objDefaultOptionVo->default_discount = $objOptionVo->discount;
            $objDefaultOptionVo->default_discount_description = $objOptionVo->discount_description;
            $objDefaultOptionVo->default_option_id = $objOptionVo->product_option_id;
            $objDefaultOptionVo->product_id = $product_id;

            // Save default option values to product table
           $sqlOptions = "UPDATE ".$tableprefix."products SET                            
                            default_additional_price = '".  mysql_real_escape_string($objOptionVo->additional_price)."',
                            default_discount = '".  mysql_real_escape_string($objOptionVo->discount)."',
                            default_option_id = '".mysql_real_escape_string($objOptionVo->product_option_id)."'
                            WHERE  product_id = ".$product_id;

           mysql_query($sqlOptions) or die(mysql_error());
    // update product options   
        $currentstatus['status'] = 1;
        $currentstatus['data']   = "Product updated";
        return($currentstatus);  
    }
   $currentstatus['status'] = 0;
   $currentstatus['data']   = "Invalid product ID";
   return($currentstatus); 
}

//---Review List API---//
function reviewlistAPI($artistid=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($artistid)) {
        $sql = "SELECT r.*,u.user_name,p.product_name,
              CASE WHEN image_small != ''  THEN CONCAT( '$path',image_small) ELSE '' END AS product_image_small,  
              CASE WHEN image_big != ''  THEN CONCAT( '$path',image_big) ELSE '' END AS product_image_big 
                                        FROM " . $tableprefix . "Review r 
                                        LEFT JOIN " . $tableprefix . "users u ON r.nUserId=u.user_id 
					LEFT JOIN " . $tableprefix . "products p ON r.nProdId=p.product_id 
                                        INNER JOIN ".$tableprefix."product_options po ON po.product_id = p.product_id AND po.default_option = 'YES' WHERE p.product_artist_id=" . $artistid;
            
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                {                           
                    $row = fetchAll($result);
                    foreach ($row as $value) {                      
                        //--- Update seller view status ---//
                        $sql = "UPDATE ".$tableprefix."Review SET seller_viewed_status = 1 WHERE nRId = '".addslashes($value->nRId)."'";			
                        mysql_query($sql) or die (mysql_error());
                    }
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = $row;
                    return($currentstatus);  
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "No Reviews Found.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID is missing.";
        return($currentstatus);       
    }       
    
    
}


//--- Mesage List API---//
function messagelistAPI($artistid=NULL) {
    
    include "../includes/config.php";        
    if (isset($artistid)) {
        $sql = "SELECT *
		FROM " . $tableprefix . "message_to_seller
                WHERE artist_id = " . $artistid . " 
                ORDER BY message_to_seller_id DESC" ;
             
                $result=mysql_query($sql) or die(mysql_error());			
                if(mysql_num_rows($result) > 0 )
                {                           
                    $row = fetchAll($result);
                    foreach ($row as $value) {                      
                        //--- Update seller view status ---//
                        $sql = "UPDATE ".$tableprefix."message_to_seller SET seller_viewed_status = 1 WHERE message_to_seller_id = '".addslashes($value->message_to_seller_id)."'";			
                        mysql_query($sql) or die (mysql_error());
                    }
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = $row;
                    return($currentstatus);  
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "No Messages Found.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID is missing.";
        return($currentstatus);       
    }       
    
    
}

// update order status
function updateorderStatusAPI($orderId=NULL,$status=NULL){
    include "../includes/config.php"; 
    
     if (isset($orderId)) {
            $sql ="UPDATE  ".$tableprefix."order_details SET
		item_status = '".addslashes($status)."'
		WHERE 	order_id = '".addslashes($orderId)."' AND artist_id='".$_GET['seller_id']."'";
		
            $res = mysql_query($sql);            
               		
                if($res)
                {                           
                    $row = fetchAll($result);
                    $currentstatus['status'] = 1;
                    $currentstatus['data']   = "Order status updated.";
                    return($currentstatus);  
                } else {
                     $currentstatus['status'] = 0;
                     $currentstatus['data'] = "Invalid order ID.";
                     return($currentstatus); 
                }
    
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Invalid order ID.";
        return($currentstatus);       
    }    
    
}

//---- Change Seller Password API ---//
function changepasswordAPI($artist_id=NULL,$old_password=NULL,$new_password=NULL) { 
    include "../includes/config.php";
    if (isset($artist_id) && isset($old_password)) {
        
        $sql = "SELECT * FROM ".$tableprefix."artists 
			WHERE artist_id='".$artist_id."' 
			AND password = '".addslashes($old_password)."' AND deleted = 'N' AND vapproved='Y' ";
       
			$result=mysql_query($sql) or die(mysql_error());			
			if(mysql_num_rows($result) > 0 )
			{   
                            // Update with new password
                            $sql ="UPDATE  ".$tableprefix."artists SET
                            password = '".$new_password."'
                            WHERE artist_id = '".$artist_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 seller ID.";
                                 return($currentstatus); 
                            }                           
                        } else {
                             $currentstatus['status'] = 0;
                             $currentstatus['data'] = "Old password is incorrect.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Old password/seller ID missing.";
        return($currentstatus);       
    }
   
}

//---- Change refund status API ---//
function changeRefundStatusAPI() { 
    include "../includes/config.php";
    $currentstatus['data']  = json_decode(stripslashes($_REQUEST['refund']));
    
    $refund_id              = $currentstatus['data']->refund_id;
    $status                 = $currentstatus['data']->status;  
    $feedback               = $currentstatus['data']->feedback;  
    $rmode                  = $currentstatus['data']->rmode;  
    $refno                  = $currentstatus['data']->referance_no;  
    
    if (isset($refund_id) && isset($status)) {        
         
             $sql = "UPDATE ".$tableprefix."refunds SET 
			Customer_Feedback = '".addslashes($feedback)."',
			Status='".addslashes($status)."',
			refund_mode='".addslashes($rmode)."',
			reference_number='".addslashes($refno)."'
			WHERE refund_id =  '".addslashes($refund_id)."' ";
            $res=mysql_query($sql);                     

            if($res)
            {  
                $currentstatus['status'] = 1;
                $currentstatus['data']   = "Refund status changed successfully.";
                return($currentstatus);  
            } else {
                 $currentstatus['status'] = 0;
                 $currentstatus['data'] = "Invalid refund ID.";
                 return($currentstatus); 
            }                           
                     
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Refund ID/status missing.";
        return($currentstatus);       
    }
   
}

//---Request for payment API ----//
function requestForPaymentAPI($chkorders=NULL,$artistid=NULL){
   
     include "../includes/config.php";
    
     if (isset($chkorders) && isset($artistid)) {         
        $orderlist = $chkorders;        
        $sql = "UPDATE " . $tableprefix . "order_details SET artist_payment_status = '1' WHERE order_id IN (" . addslashes($orderlist) . ") 
		AND artist_id = '" . addslashes($artistid) . "'";        
        mysql_query($sql) or die(mysql_error());
        $message = MSG_PAYMENT_SUC;
        $to = SITE_EMAIL;      
        /*************** Get Seller name ***************************** */
        $art_sql = "select first_name,last_name from " . $tableprefix . "artists where artist_id=$artistid";        
        $art_rs = mysql_query($art_sql) or die(mysql_error());
        $art_rw = mysql_fetch_array($art_rs);
        $seller_name = $art_rw["first_name"] . " " . $art_rw["last_name"]; 
        /*************** End get seller name ***************************** */
        $adminCurrency = GetAdminCurrency();      
        $order_list = explode(",", $orderlist); 
  
        foreach ($order_list as $rp) {
            /********************* [START]Send requesy payment to the administrator **********************/
            $subject = MAIL_RP_TEXT_REQUESTED_PAYMENT_PLACED_1." " . stripslashes(SITE_NAME) . " ".MAIL_RP_TEXT_REQUESTED_PAYMENT_PLACED_2;

            $b_sql = "select billing_first_name,billing_last_name,order_total_price,vorder_currency from " . $tableprefix . "orders where order_id=$rp";
            $b_rs = mysql_query($b_sql) or die(mysql_error());
            $b_rw = mysql_fetch_array($b_rs);
            $bfname = $b_rw["billing_first_name"];
            $blname = $b_rw["billing_last_name"];
            $p_sql = "SELECT sum((od.product_price-(od.product_price*od.product_discount/100)) *od.product_quantity) as total,sum(od.product_commission_amount)as adminamount,sum(od.product_tax) as taxtotal FROM " . $tableprefix . "order_details od
		            WHERE od.artist_id = '" . $artistid . "' AND od.artist_payment_status = '1' 
					and od.order_id IN (" . addslashes($rp) . ")";
               
            $p_rs = mysql_query($p_sql);
            $p_rw = mysql_fetch_array($p_rs);
                                   
             $ordertotalamt = $p_rw["total"] + $p_rw['taxtotal'];
             
               $select_shipping_cost = "SELECT  sd.nshipping_cost,sd.nshp_productname
                                        FROM ".$tableprefix."shipping_details sd
                                            INNER JOIN ".$tableprefix."order_details  od ON (od.product_id=sd.nshp_productid AND od.product_option_id=sd.nproduct_option_id AND od.order_id=sd.norder_id)
                                                WHERE sd.norder_id = ".$rp." AND od.artist_id = '".addslashes($artistid)."' AND  sd.nshp_status = 'C' order by sd.nshp_productname";
          
                                    
                                    $result_shipping_cost = mysql_query($select_shipping_cost);
                                    $totalshippingcost = 0;
                                    $ordertotal = $row["total"];
                                    if (mysql_num_rows($result_shipping_cost) > 0) {

                                        while ($shipping_row = mysql_fetch_array($result_shipping_cost)) {
                                            $totalshippingcost+=$shipping_row['nshipping_cost'];
                                        }
                                    }
                                    $ordertotalamt+=$totalshippingcost;
                                    
                                    
                                    $amountRecevable    = $ordertotalamt - $p_rw['adminamount'];

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

            $mailcontent = readEmailTemplate('request_payment_seller');              
            
            $mailcontent = str_replace('[seller_name]', $seller_name, $mailcontent);

            $orderdetails = "<p>".MAIL_RP_TEXT_ORDER_ID_ANNOTATED." $rp</p>";
            $orderdetails .= "<p>".MAIL_RP_TEXT_BUYER_NAME." " . $bfname . " " . $blname . "</p>";
            $orderdetails .= "<p>".MAIL_RP_TEXT_TOTAL_PURCHASE." " . $adminCurrency["currency_symbol"] . "  " . number_format($ordertotalamt, 2, '.', '') . "</p>";

            $orderdetails .= "<p>".MAIL_RP_TEXT_AMOUNT_RECEIVABLE." " . $adminCurrency["currency_symbol"] . "  " . number_format($amountRecevable, 2, '.', '') . "</p>";
            
            $mailcontent = str_replace('[order_details]', $orderdetails, $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";
            $headers .= "Reply-To: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
            $headers .= "Return-Path: " . SITE_NAME . "<noreply@" . SITE_EMAIL . ">" . "\r\n";

            $mailcontent = nl2br($mailcontent);
            $active_template = displayTemplate();

             $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, $subject, $mail_send_details, $headers);  
            /******************** [END]Send requesy payment to the administrator ********************* */            
        }
        $currentstatus['status'] = 1;
        $currentstatus['data'] = "Payment request send for the selected order(s)";
        return($currentstatus);
     } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Order ID/seller ID missing.";
        return($currentstatus);       
    }
}
//--Delete Seller Product--//
function deleteProductAPI($productId=NULL){
    include "../includes/config.php";
    
     if (isset($productId)&& $productId!= NULL) {   
         
        $select_product_images = "SELECT image_small,image_big
				  FROM ".$tableprefix."product_options WHERE product_id IN(".$productId.")";


        $result_product_images = mysql_query($select_product_images) or die(mysql_error());

        if(mysql_num_rows($result_product_images) > 0) {
            while($product_images_row = mysql_fetch_array($result_product_images)) {
                $imagesmall_thumb=$product_images_row['image_small'];

                $imagelarge_thumb=$product_images_row['image_big'];

                @unlink("../products/".$imagesmall_thumb);
                @unlink("../products/".$imagelarge_thumb);

            }
        }

    $select_product_images_more = "SELECT im.vimage_name
                                                                        FROM ".$tableprefix."product_view_images im  WHERE im.nimage_productid IN(".$productId.")";
    $rs_product_image_more		= mysql_query($select_product_images_more) or die(mysql_error());

    if(mysql_num_rows($rs_product_image_more)>0) {

        while($prows=mysql_fetch_array($rs_product_image_more)) {
            $moreimage	= $prows['vimage_name'];

            $moreimage_thumb	= "thumb_".$prows['vimage_name'];

            @unlink("../products/bulk_images/".$moreimage);

            @unlink("../products/bulk_images/".$moreimage_thumb);

        }
    }

    $delete_products = "DELETE FROM ".$tableprefix."products WHERE product_id IN(".$productId.")";

    mysql_query($delete_products) or die(mysql_error());

    $sql_options = "DELETE FROM ".$tableprefix."product_options WHERE product_id IN ($productId) ";
    $del_options = mysql_query($sql_options);
    $sql_product_images_more = "DELETE FROM ".$tableprefix."product_view_images WHERE nimage_productid IN ($productId) ";
    $del_product_images_more = mysql_query($sql_product_images_more);

    $delete_cart_products = "DELETE FROM " . $tableprefix . "cart WHERE product_id IN(" . $productId . ")";
    
    mysql_query($delete_cart_products) or die(mysql_error());
    
        $currentstatus['status'] = 1;
        $currentstatus['data'] = "Product deleted.";
        return($currentstatus);
     } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Product ID missing.";
        return($currentstatus);       
    }
    
}

//--Delete Seller Messages--//
function deleteSellerMessageAPI($messageId=NULL){
    include "../includes/config.php";
     
     if (isset($messageId)&& $messageId!= NULL) {   
         
        //$message_to_seller_ids = implode(',', $messageId);

        $deleteQ = "DELETE FROM " . $tableprefix . "message_to_seller WHERE message_to_seller_id = ". $messageId;

        mysql_query($deleteQ) or die(mysql_error());
    
        $currentstatus['status'] = 1;
        $currentstatus['data'] = "Message deleted.";
        return($currentstatus);
     } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Message ID missing.";
        return($currentstatus);       
    }
    
}

//---- Seller Profile API ---//
function sellerProfileAPI($sellerId=NULL) { 
    include "../includes/config.php";
    if (isset($sellerId) && $sellerId != NULL) {
        
        $sql = "SELECT * FROM ".$tableprefix."artists 
			WHERE artist_id=".$sellerId;
        
			$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 seller ID.";
                             return($currentstatus); 
                        }
       
    } else {
        $currentstatus['status'] = 0;
        $currentstatus['data'] = "Seller ID is missing.";
        return($currentstatus);       
    }
   
}


//---Seller Details Update API---//
function editSellerProfileAPI() {

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

    if (isset($_REQUEST['seller_id']) && $_REQUEST['seller_id'] != NULL) {

        $arrSeller['first_name'] = stripslashes($_REQUEST['first_name']);
        $arrSeller['last_name'] = stripslashes($_REQUEST['last_name']);
        $arrSeller['company'] = stripslashes($_REQUEST['company']);
        $arrSeller['address1'] = stripslashes($_REQUEST['address1']);
        $arrSeller['city'] = stripslashes($_REQUEST['city']);
        $arrSeller['phone'] = stripslashes($_REQUEST['phone']);
        $arrSeller['email'] = stripslashes($_REQUEST['email']);
        $arrSeller['paypalemail'] = stripslashes($_REQUEST['paypalemail']);
        $arrSeller['seller_id'] = stripslashes($_REQUEST['seller_id']);
    
        // Primary Seller info
        $sql = "UPDATE  " . $tableprefix . "artists SET
                    first_name = '" . addslashes($arrSeller['first_name']) . "',
                    last_name = '" . addslashes($arrSeller['last_name']) . "',			
                    company = '" . addslashes($arrSeller['company']) . "',			
                    address1 = '" . addslashes($arrSeller['address1']) . "',			
                    city = '" . addslashes($arrSeller['city']) . "',			
                    phone = '" . addslashes($arrSeller['phone']) . "',			
                    email = '" . addslashes($arrSeller['email']) . "',			    
                    paypalemail = '" . addslashes($arrSeller['paypalemail']) . "'";
        $sql .=" WHERE artist_id=" . $arrSeller['seller_id'];
        mysql_query($sql) or die(mysql_error());

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


//-- Category List --//
function getCategoriesAPI($catId=NULL){
    include "../includes/config.php";
    
     if (isset($catId)&& $catId!= NULL) {
         $sql = " select *  FROM  " . $tableprefix . "categories where parent_id='$catId' AND category_id != 1";
     }else{
         $sql = " select *  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);       
        }     
}

//--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 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 getAccessTokenValue(){
    $accessToken = array();
    
    foreach(getallheaders() as $name => $value) {
     
        if($name=="Acess-Token")
            $accessToken['device_id']   =  $value;
        if($name=="Device-Type")
            $accessToken['device_type']  = $value;
      }
      return $accessToken;
    
}
function checkAccessTokenValid($seller_id,$accessToken){
    
    include "../includes/config.php";
    
    $device_id       =  $accessToken['device_id'];
    $device_type     =  $accessToken['device_type'];
    
    $select_devices  = "SELECT artist_device_id FROM ".$tableprefix."artist_devices 
                               WHERE artist_id='".  addslashes($seller_id)."' AND device_id LIKE '".  addslashes($device_id)."%' 
                               AND device_type='".  addslashes($device_type)."'";
    
 
   
    $result_devices = mysql_query($select_devices) or die(mysql_error());
    if(mysql_num_rows($result_devices)>0){
        return 0;
    }else{
        return 1;
    }
    
}


?>