<?php
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";
include_once('api/pemfile/iphonepush.php');
if(isset( $_SESSION["sess_userid"]) and $_SESSION["sess_userid"]!= "")
{
		$userid = $_SESSION["sess_userid"];
}
else
{
	header("Location:login.php");
	exit;
	
}

$productid	= $_POST['productid'];

$review		= addslashes($_POST['review']);


$StartRateProductid		= $_POST['hidProductid'];

$clickedStarVal		        = $_POST['clickedStarVal'];

$sellerid			= $_POST['sellerid'];

$hidSellerPostId		= $_POST['hidSellerPostId'];

$sellerreview			= $_POST['sellerreview'];

$sellerRatingval		= $_POST['sellerRatingval'];


if($productid != '' and $review !='')
{
	$psql=mysql_query("select *  from ".$tableprefix."Review where nUserId='".$_SESSION["sess_userid"]."' and nProdId='".$productid."'") or die(mysql_error());
	
	$numRows	= mysql_num_rows($psql);
	if($numRows>0)
	{
		$data = array('duplicate' => 1);
		echo json_encode($data);
		exit;	
	}
	else
	{
		
			
		switch(getSettingsValue('vReview'))
		{
			case "automatic":
				$aActive='1';
			break;
			
			default:
				$aActive='0';
			break;
		}//end switch
		
		$sql_2 = "SELECT vReview FROM ".$tableprefix."settings";
		$res_2 = mysql_query($sql_2);
                $reviewapproval1 = '';
		if(mysql_num_rows($res_2)!= 0){
			$rw_2 = mysql_fetch_array($res_2);
			$reviewapproval1=$rw_2["vReview"];
		}
               $reviewapproval="vendors";
		
		mysql_query("insert into ".$tableprefix."Review (nUserId,nProdId,vDes,vActive) values ('".$_SESSION["sess_userid"]."',
						'".$productid."','".$review."','".$aActive."')") or die(mysql_error());
		
		if($reviewapproval=="admin" || $reviewapproval=="vendors")
		{
		/************* Get Product details *************/
		$p_sql  = "select * from ".$tableprefix."products where product_id = \"".$productid."\"";
		$p_rs   = mysql_query($p_sql) or die(mysql_error());
		$p_row	= mysql_fetch_array($p_rs);
                
                // Send push notification                                
                $devicesql = "Select device_id from " . $tableprefix . "artists where artist_id ='$sellerid'"; //Get seller device ID           
                $result = mysql_query($devicesql);
                $device_row = mysql_fetch_assoc($result);
                $msg = "New review posted for product ".$p_row["product_name"]." at ".SITE_NAME.", please check.";
                send_push_nofication($msg,SITE_NAME,"armia",$device_row['device_id'],"Review","order");//Message,From,passphrase,device token,type-->product,order...
                //-------------------------//
		
		/************* Get email of the seller ***********************/
		if($reviewapproval=="vendors")
		{
		  $seller_sql  = "select email from ".$tableprefix."artists where artist_id = ".$p_row["product_artist_id"];
		  $seller_rs   = mysql_query($seller_sql);
		  $seller_rw   = mysql_fetch_array($seller_rs);
		  $seller_email= $seller_rw["email"];
		}
		/***************** End fetching product details **********/
		// Send mail to admin
			
		/*---------Multicart 2.0 Upgradation------------*/		
		$subject = MAIL_NEW_PRODUCT_REVIEW_POSTED_SUBJECT." ".stripslashes(SITE_NAME);
		$mailcontent = readEmailTemplate('product_review');

		if($reviewapproval=="admin")
                    $to      = SITE_EMAIL;
		elseif($reviewapproval=="vendors")
		{
                    $to     = $seller_email;
                    $mailcontent = str_replace('Administrator',"Seller",$mailcontent);	
		}
		
		$link    = "<a href='".SITE_URL."/productdetails.php?productid=".$productid."' target='_blank'>".MAIL_SELLER_PRODUCT_REVIEW_TEXT_CLICK_HERE."</a>";
		
		/*-------Email Template Reading Fuction Call--------*/				
				
				
		$mailcontent = str_replace('[site_name]',SITE_NAME,$mailcontent);					
		$mailcontent = str_replace('[product_name]',$p_row["product_name"],$mailcontent);		
		$mailcontent = str_replace('[link]',$link,$mailcontent);
                
                
		
		/*--------------- End email template section-------------------*/			
		
		/******* Send Email ************************************************/
		
		$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"; 
		//$headers .= "Organization: ".SITE_NAME."\r\n"; 
		
		
		$mailcontent = nl2br($mailcontent);
				

		//$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>".$mailcontent."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";
		 $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);
            if($reviewapproval1=="admin"){
                $subject = MAIL_NEW_PRODUCT_REVIEW_POSTED_SUBJECT." ".stripslashes(SITE_NAME);
		$mailcontent = readEmailTemplate('product_review');
                $mailcontent = str_replace('[site_name]',SITE_NAME,$mailcontent);					
		$mailcontent = str_replace('[product_name]',$p_row["product_name"],$mailcontent);		
		$mailcontent = str_replace('[link]',$link,$mailcontent);
                
                /*--------------- End email template section-------------------*/			
		
		/******* Send Email to admin ************************************************/
		
		$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"; 
		//$headers .= "Organization: ".SITE_NAME."\r\n"; 
		
		
		$mailcontent = nl2br($mailcontent);
				

		//$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>".$mailcontent."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";
		 $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>';
                  $to      = SITE_EMAIL;
                  $mailsent = mail($to, $subject, $mail_send_details, $headers);
            }
                

/*********************** End email section ***********************************/
		}
		
		
		$data = array('success' => 1,'comment'=>stripslashes($review));
                echo json_encode($data);
                exit;		
	
	
	}

}

// Product Star Rating Code Starts Here ----------------------------//
if($StartRateProductid !=0 && $clickedStarVal!=0)
{

	$ip = $_SERVER['REMOTE_ADDR'];
	

	$select_rating = "SELECT ntotal_ratings FROM ".$tableprefix."record_ratings WHERE nrseller_id = '$StartRateProductid' AND vType='p'
												AND nruser_id = ".$_SESSION["sess_userid"];

    $result_rating = mysql_query($select_rating);
	
			if(mysql_num_rows($result_rating) == 0)
			
			{
			
				$total_count = 1;
				 $record_rating = "INSERT INTO ".$tableprefix."record_ratings(nrating_id,nruser_id,nrseller_id,ntotal_ratings,vType)
			
								  VALUES(".$clickedStarVal.",".$_SESSION["sess_userid"].",".$StartRateProductid.",1,'p')";
				$rs_rating		=mysql_query($record_rating) or die(mysql_error());
				
				$inSertId	=mysql_affected_rows();
				
				if($inSertId>0)
				{
						
						$data = array('success' => 1);
						  echo json_encode($data);
						  exit;		
		
				}	 
				else
				{
						$data = array('error' => 1);
					    echo json_encode($data);
					    exit;	
					
				} 
				//echo $record_rating; 				  
			}
			
			else
			{
					$data = array('duplicate' => 1);
						echo json_encode($data);
						exit;	
			}
	

}

// Product Star Rating Code End  Here ----------------------------//


// Seller  Star Rating Code Starts Here ----------------------------//

if($hidSellerPostId!='' && $sellerreview!='' && $sellerRatingval!='')
{
	
		$select_seller_rating = "SELECT rating  FROM ".$tableprefix."artist_feedbacks WHERE artist_id = '$hidSellerPostId' 
												AND user_id = ".$_SESSION["sess_userid"];


	   $result_seller_rating = mysql_query($select_seller_rating);
	   
	   if(mysql_num_rows($result_seller_rating)==0)
	   {
	   		
			 $sql_seller_rating = "INSERT INTO ".$tableprefix."artist_feedbacks (
				feedback_content,
				rating,
				user_id,
				artist_id,
				date_added,
				published

				) VALUES (
				'".addslashes($sellerreview)."',
				'".addslashes($sellerRatingval)."',
				'".addslashes($_SESSION["sess_userid"])."',
				'".addslashes($hidSellerPostId)."',
				now(),
				'N')
				";
				
			$rs_seller_rating	=mysql_query($sql_seller_rating) or die(mysql_error());
			
			$inSertId	=mysql_affected_rows();
			
			if($inSertId>0)
			{
				$data = array('success' => 1,'comment'=>stripslashes($sellerreview));
						  echo json_encode($data);
						  exit;	
			}
			else
			{
					$data = array('error' => 1);
					 echo json_encode($data);
				    exit;	
			}
				
			
	   }
	   else
			{
					$data = array('duplicate' => 1);
						echo json_encode($data);
						exit;	
			}
}

// Product Star Rating Code End  Here ----------------------------//

?>