<?php
ob_start();
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 1);

 include("db.php");
 include("../pdate.php");
 
   $get_id=$_GET['id'];
    
   $table=$_GET['table'];
   
    
   
     $customerRetriveSql="select * from `$table` where id='$get_id' ";
	 $customerRetriveQuery=$db ->query($customerRetriveSql);
	 $customerRetriveRow=$customerRetriveQuery ->fetch_array();
	 
	 $id_retrive=$customerRetriveRow['id'];
	 $dateretrive=$customerRetriveRow['date'];
	 $customerId_retrive=$customerRetriveRow['customerId'];
	
	 $counterCurrency_retrive=$customerRetriveRow['counterCurrency'];
	 $baseCurrency_retrive=$customerRetriveRow['baseAmount'];
	 $amount_retrive=$customerRetriveRow['amount'];
	 $sellRate_retrive=$customerRetriveRow['sellRate'];
	 $buyRate_retrive=$customerRetriveRow['buyRate'];
	 $baceCurrencyRate_retrive=$customerRetriveRow['baceCurrencyRate']; //قیمت ارزپایه نسبت به دالر
	 
	 $totalSell_retrive=$customerRetriveRow['totalSell'];
	 $totalBuy_retrive=$customerRetriveRow['totalBuy'];
	 $dollartotalsell_retrive=$customerRetriveRow['dollartotalsell'];
	 $dollartotalbuy_retrive=$customerRetriveRow['dollartotalbuy'];
	 $profit_retrive=$customerRetriveRow['profit'];
	 $dollarProfit_retrive=$customerRetriveRow['dollarProfit'];
	 $descr_retrive=$customerRetriveRow['descr'];
	 //===================Findeing  unit=========================
	      $unit_Sql="select unit from crrencyrate where counterCurrency='$counterCurrency_retrive' and baseCurrency='$baseCurrency_retrive' order by id limit 1";
	      $unit_Query = $db ->query($unit_Sql);
		  $unit_Row= $unit_Query ->fetch_array();
	      $unit=$unit_Row['unit'];
	 //===================Findeing  unit=========================
	 $dollar_retrive=$dollartotalsell_retrive/$amount_retrive;
	 $dollar_buy_retrive=$dollartotalbuy_retrive/$amount_retrive;
	 echo "<br>"; 
	 $retrive_Base_dollarAmount=$totalSell_retrive/$baceCurrencyRate_retrive; 
	 
	   
?> 
<!DOCTYPE HTML> 
<html>
<head>
	<title>ویـرایــش خــریــد و فـــروش</title>
	 
	<link rel="stylesheet" type="text/css" href="../css/style.css">
    
<!---==========================================================================-->
 
 <script type="text/javascript" src="../js/decimal.js"></script>
 <script type="text/javascript" src="../js/NumberFormat.js"></script>
<!---==========================================================================-->
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.autocomplete.pack.js"></script>
<script type="text/javascript" src="../js/script.js"></script>
<!---==========================================================================-->
<!--=========================================================-->
     <script src="js/jquery/jquery-1.4.1.minn.js" type="text/javascript"></script>
	 <script src="../js/validation.js"></script>
     <script src="../dist/sweetalert-dev.js"></script>
     <link rel="stylesheet" href="../dist/sweetalert.css">
     <link rel="stylesheet" href="../css/screen.css" type="text/css"   />
<!--=========================================================-->
<!--========================================================================-->
<script>
	     
									//Dollar Price
//====================================================================================
   function dollarPrice(){
	    $('#ghaymatdollar').hide();
		$.post('../retiveDollarrateforSall.php', {
		   rateOfDollar:form.counterCurrency.value
		   },
			function(output){
				$('#ghaymatdollar').html(output).fadeIn(10);
		})
	
	} 

//====================================================================================	
	   
   function findCash(){
	    $('#cash').hide();
		$.post('../estimateRate.php', {
		   currencyId:form.basecurrency.value
		   },
			function(output){
				$('#cash').html(output).fadeIn(10);
		})
	
	}  
	
	
	
	  function assetCash(){
	      $('#asset').hide();
		  $.post('../customerexictiongAmount.php', {
		  currencyId:form.basecurrency.value,
		  customerGetId:form.customerId.value,
		   },
			  function(output){
			  $('#asset').html(output).fadeIn(10);
		  })
	
	  }  
	
	function get_amount(){
	    $('#rate').hide();
		$.post('../retiverateforSell.php', {
		   bCurrency:form.basecurrency.value, 
		   cCurrency:form.counterCurrency.value
		   },
			function(output){
				$('#rate').html(output).fadeIn(10);
		})
	
	}  
	
	
	
	function findingCounterCurrency(){
	    $('#cCounter').hide();
		$.post('../estimateCounterRate.php', {
		   countercurrencyId:form.counterCurrency.value
		   },
			function(output){
				$('#cCounter').html(output).fadeIn(10);
		})
	
	}
	
	  
	 </script> 
	<script>
		  function findingcalculation(){
	     insertval=setInterval("zarb()",1);
	    }
		  function zarb(){
	       amount_p  =document.getElementById('counterAmount').value;
		  var decimalCharacter = ".",
          regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
          num_caldar=amount_p;
          var amount=+num_caldar.match(regex).join("");  
		  
		   take_Mode=document.getElementById('mode').value; 
		   
		    if(take_Mode=="mode_1"){
			
		  rate_mixData=document.getElementById('rate_mixData').value; 
		  mixData=document.getElementById('mixData').value; 
		  takeData=mixData.split('/');
		  mainrate=takeData[0];
		  unit=takeData[1];
		  
		  var exactresult=amount/unit;
		    row=(exactresult*1)*(rate_mixData*1);
		    
			pourCalculation=row.toFixed(2);			
			  
		  }
		  
		  if(take_Mode=="mode_2"){
	      
		  rate_mixData=document.getElementById('rate_mixData').value; 
		  mixData=document.getElementById('mixData').value; 
		  takeData=mixData.split('/');
		  mainrate=takeData[0];
		  unit=takeData[1];
		  
		  var exactresult=amount/rate_mixData;
		    row=(exactresult*1)*(mainrate*1);
		    
			pourCalculation=row.toFixed(2);		  
			  
		  }  
		  
		  //=======================================================================
		  
		     //نرخ جدید
		   
		   changeMixData  =document.getElementById('change_currencyPriec').value;
		  
		  
		  if(take_Mode=="mode_1"){
			
		 
		   oldemixData=document.getElementById('mixData').value; 
		   changetakeData =oldemixData.split('/');
		   changemainrate =changetakeData[0];
		   changeunit     =changetakeData[1];
		  
		  var changeexactresult=amount/changeunit;
		    row=(changeexactresult*1)*(changeMixData*1);
		    
			change_pourCalculation=row.toFixed(2);			
			  
		  }
		  
		 if(take_Mode=="mode_2"){
	      
		 
		   oldemixData=document.getElementById('mixData').value; 
		   changetakeData =oldemixData.split('/');
		   changemainrate =changetakeData[0];
		   changeunit     =changetakeData[1];
		  
		   var changeexactresult=amount/changeMixData;
		   row=(changeexactresult*1)*(changemainrate*1);
		    
			change_pourCalculation=row.toFixed(2);		  
			  
		  }    
		   
		   //===========================================================================
		   if(changeMixData!=""){
		  
		   document.getElementById('baceAmount').value=FormatNumberBy3(change_pourCalculation*1) ;
		   
		   }    
		   
		   if(changeMixData==""){
		    
		    document.getElementById('baceAmount').value=FormatNumberBy3(pourCalculation*1) ;
		     
		  }     
		   
		   }   
//====================================================================================	
	
	function calculateDollar(){
	     insertval=setInterval("multipalDollar()",1);
	    }
		function multipalDollar(){
	     //dollarRatePrice=document.getElementById('dollarRatePrice').value;
	    // newdollarRatePrice=document.getElementById('new_dollarRatePrice').value;
		  
		 var amount_p=document.getElementById("counterAmount").value;
         var decimalCharacter = ".",
         regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
         num_caldar=amount_p;
        var amount=+num_caldar.match(regex).join("");
		 
		// نرخ قدیم
		  dollarmixData=document.getElementById('dollarmixData').value; 
		  dollartakeData=dollarmixData.split('/');
		  dollarmainrate=dollartakeData[0];
		  dollarunit=dollartakeData[1];
		  
		  var dollarexactresult=amount/dollarunit;
		  
		  
		    //نرخ جدید
		    /* dollarchangeMixData  =document.getElementById('new_dollarRatePrice').value;
		   dollarchangetakeData=dollarchangeMixData.split('/');
		   dollarchangemainrate=dollarchangetakeData[0];
		   dollarchangeunit   =dollarchangetakeData[1];
		   
		   var dollarchangeexactresult=amount/dollarchangeunit;  
		   
		 if(dollarchangeMixData!=""){
		    totalDollar=(dollarchangemainrate*1)*(dollarchangeexactresult*1);
            findTotalDollar=totalDollar.toFixed(2);   
		    document.getElementById('totalDollar').value=findTotalDollar;
		  
		  }  */
		 // if(dollarchangeMixData==""){
		     totalDollar=(dollarmainrate*1)*(dollarexactresult*1);
             findTotalDollar=totalDollar.toFixed(2);   
		     document.getElementById('totalDollar').value=findTotalDollar;
		  
		 // }  
		
		}	
//===============الباقی حساب مشتر===============================		
		function customerBalance(){
	     insertval=setInterval("customerRemain()",1);
	    }
		function customerRemain(){
	     balanceP=document.getElementById('balance').value;  
	     var decimalCharacter = ".",
         regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
         num_price=balanceP;  
         var balance=+num_price.match(regex).join("");
	    
 		 baceAmountP  =document.getElementById('baceAmount').value;
		 var decimalCharacter = ".",
         regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
         num_price=baceAmountP;  
         var baceAmount=+num_price.match(regex).join("");
		 
		 document.getElementById('remainCustomer').value=FormatNumberBy3((balance*1)-(baceAmount*1));
		
		
		}
    function newrate(){
	   profe=document.getElementById('take').value;
	   finalResult=document.getElementById('currencyPriec').value=(profe*1);
	 }	
	 function buynewrate(){
	   profe=document.getElementById('take').value;
	   finalResult=document.getElementById('buyRate').value=(profe*1);
	 }
//====================================================================	 
	 function dollarsalenewrate(){
	   profe=document.getElementById('takeDollar').value;
	   finalResult=document.getElementById('dollarRatePrice').value=(profe*1);
	 }	
	 function dollarBuy_newrate(){
	   profe=document.getElementById('takeDollar').value;
	   finalResult=document.getElementById('buyRate_dollar').value=(profe*1);
	 }		
//===============الباقی حساب مشتر===============================			
	 </script>
   
</head>
<body onload="findingcalculation();assetCash();dollarPrice();get_amount();findingCounterCurrency();calculateDollar();customerBalance();findCash();calculate();">

	<div id="wrap">
		 
		<div id="contentt">
			 
			<div id="menu">
				 
			</div>
		    <div id="matlab" >
			<div id="title"><p>ویـرایــش خــریــد و فـــروش</p> </div>
			<div id="picture">
					<table border="0" width="400px">
						<tr>
							<td style="width:180px;"><img src="../img/buyPart.png" width="150px" height="120px">  </td>
							<td > </td>
						</tr>
					</table>
			   </div>
		    	<form method="post" action="" name="form">
               <table border="0"   id="rgistera_cart" width="800px" class="font">
		    		<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">تاریخ </th>
						<td style="width:250px" >
							<input type="text" name="date" id="newdate" placeholder="" class="form-control" value="<?php echo $dateretrive;?>"/>
							 
						</td>
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">ارز مورد معاوضه</th>
						<td style="width:250px" >
						<select name="counterCurrency"  id='counterCurrency'  style="width:100%" onchange="dollarPrice();get_amount();findingCounterCurrency();calculate()" onclick="get_amount();findingCounterCurrency();calculate();dollarPrice()">
						<option></option>	
							<?php
						 
							$sql="select * from currencies";
							$query=$db ->query($sql);
							while($row=$query ->fetch_array()){
							$id=$row['id'];
							$name=$row['name'];
							//echo "<option value='$id'>$name</option>";

                            if($counterCurrency_retrive == $row['id']){
								echo "<option value=$row[id] selected>$row[name] </option>";
								}else{
								    echo "<option value=$row[id]>$row[name]</option>";
								}


							
							}
							echo "</select>";
														
							?>
						 
						 </td>
						 
		    		</tr>
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">مقدار</th>
						<td style="width:250px" >
							<input type="text"   name="counterAmount" autocomplete="off" value="<?php echo $amount_retrive; ?>" onkeyup="addSeparator(this)" id="counterAmount"    placeholder="" class="form-control"  onChange="calculateDollar();" onclick="calculateDollar()"/>
						    <input type="hidden" name='customerId' id="customerId"       value="<?php echo $customerId_retrive; ?>">								
						</td>
						 
		    		</tr>
					 
					 
						<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px"> ارز پایه</th>
						<td style="width:250px" >
						<select name="basecurrency"  id='basecurrency' style="width:100%" onchange="findingcalculation();customerBalance();findCash();get_amount();calculate();assetCash()" onclick="findingcalculation();customerBalance();assetCash();findCash();get_amount();calculate()">
						<option></option>
							<?php
							 
							$sql="select * from currencies";
							$query=$db ->query($sql);
							while($row=$query ->fetch_array()){
							$id=$row['id'];
							$name=$row['name'];
							//echo "<option value='$id'>$name</option>";

                            if($baseCurrency_retrive == $row['id']){
								echo "<option value=$row[id] selected>$row[name] </option>";
								}else{
								    echo "<option value=$row[id]>$row[name]</option>";
								}


							
							}
							echo "</select>";
														
							?>
						 
						 </td>
						 
		    		</tr>
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">قیمت فروش</th>
						<td style="width:250px" >
							 <div id='rate'><input type="text" name="rateOfCurrency" id='rateOfCurrency' disabled  class='form-control' value="<?php echo $sellRate_retrive ?>"></div> 
														 
						</td>
														 
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">قیمت فروش جدید</th>
						<td style="width:250px" >
							   <input type="text" name="change_currencyPriec" id="change_currencyPriec" placeholder="در صورت تغییر قیمت فروش قیمت جدید را بنویسید"  style='background: #ccffff;'  class='form-control' value="<?php //echo $sellRate_retrive ?>"   >
																		 
						</td>
														 
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">قیمت خرید</th>
						<td style="width:250px" >
							 <input type="text" name="buyRate" id='buyRate' class='form-control' placeholder="نــرخ خــرید را وارد کنیــــد"  style='background: #ccffff;'> 
														 
						</td>
														 
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">ارزش به ارز پایه</th>
						<td style="width:250px" >
							<input type='text' name='baceAmount' id="baceAmount" class='form-control'   >
						</td>								
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					<tr>
						<!--<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">قیمت به دالر</th>
						<td style="width:250px" >-->
						  <div id='ghaymatdollar'><input type="hidden"   class='form-control' ></div>
														 
						<!--</td>
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">ارزش به دالر</th>
						<td style="width:250px" >-->
							<input type='hidden' name='totalDollar' id="totalDollar" class='form-control'   >
																					 
						<!--</td>
						<td style="width:280px;">
							 
						 </td>
		    		</tr>-->
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">توضیحـات</th>
						<td style="width:250px" >
							 <textarea name="desc"><?php echo $descr_retrive;?></textarea>													 
						</td>
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px"> </th>
						<td style="width:230px"> 
						    <input type="submit" id="submitbtn"   name="save"  value="ذخیره">
							<input type="submit"  id="back"   name="back"  value="انصراف">
							
						</td>
						<td style="width:300px;"> </td> 
		    		</tr>
                    
		    	</table>
		    	 
				</form>
		    </div>


		</div>
		 
	</div>
</body>
</html>
<?php
if($_POST['back']){
  header("location:../buy.php");
}
if($_POST['save']){
    
	$customerId_retrive;         //شماره شناسایی مشتری
    $counterCurrency_retrive;   //پــول مورد معاوضه قدیم
	 $counterAmount_retrive;     // مقدار پول معاوضه شده
	 $totalSell_retrive;          // مقدار ارز پایه
	
	 
	 $rate_retrive;              // نــرخ
	 $baseCurrency_retrive;      // ارز پـایه
	 $baseAmount_retrive;        // مقدار ارز پایه
	 $treatment_retrive ;        // نوعیت معامله خرید
	 $dollarRate_retrive;        //نرخ به دالر
	 $dollarTotal_retrive;       // مجموع به دالر
   
	 
	//==================================================
	  $customerId=$_POST['customerId'];
     $mode=$_POST['mode'];
    $date=$_POST['date'];
	 
	$counterCurrency=$_POST['counterCurrency'];//نام ارزی که مقدار آن باید اضافه شود
	 
	$counterAmountP=$_POST['counterAmount'];//  مقدار ارزی که باید اضافه شود
    $counterAmount = preg_replace('/[^\d\.-]/', '', $counterAmountP);
     
	$basecurrency=$_POST['basecurrency'];//  نام ارزی که مقدار آن باید کم شود 
	
	//=================پیدا کردن ارز پـایه نصبت به دالر==========================
	      $baseCurrencyRate_Sql="select rate from crrencyrate where baseCurrency='$basecurrency' and counterCurrency='1' order by id desc limit 1";
	      $baseCurrencyRate_Query= $db ->query($baseCurrencyRate_Sql);
		  $baseCurrencyRate_Row=$baseCurrencyRate_Query->fetch_array();
		  $baseCurrencyRate=$baseCurrencyRate_Row['rate'];
	      if(!isset($baseCurrencyRate)){
	       
		     echo "<script> alert('قیمت ارز پـایه را به دالر در قسمت نرخ دهی ثبت کنید')
			 
			     window.location = 'currencyRate.php';
			 
			 </script>";
		   
		   die;
		   }
	
	//=================پیدا کردن ارز پـایه نصبت به دالر==========================
	
	 
	$balanceP=$_POST['balance'];//  موجودی ارز پایه
    $balance = preg_replace('/[^\d\.-]/', '', $balanceP); 
 //=======================================================================================
	 
	$baceAmountP=$_POST['baceAmount'];    //  ارزش به ارز پایه(مقداری که باید کم شود)
    $baceAmount = preg_replace('/[^\d\.-]/', '', $baceAmountP);
	 
	$remainCustomerP=$_POST['remainCustomer'];    // الباقی حساب مشتری
    $remainCustomer = preg_replace('/[^\d\.-]/', '', $remainCustomerP);	
  //---------------------------------------------------------------------------- 
	$dollarmoadelBaceCurrency=$baceAmount/$baseCurrencyRate;
	 
//======================================================================================	 
//======================================================================================	 
//======================================================================================	 
	 $change_currencyPriecRow=$_POST['change_currencyPriec'];//  قیمت فروش جدی 
	 $rateRow=$_POST['currencyPriec'];        //به پـــول پــایـــه
     
	if($change_currencyPriecRow!=0){
	
	   
	   
	   if($mode=='mode_1'){
			$newCurrency=split("/",$rateRow);
	        $first_newCurrency=$newCurrency[0];
	        $second_newCurrency=$newCurrency[1];
            $salerate=($change_currencyPriecRow/$second_newCurrency);			
		  }
		  if($mode=='mode_2'){
			 
			$newCurrency=split("/",$rateRow);
	        $first_newCurrency=$newCurrency[0];
	        $second_newCurrency=$newCurrency[1]; 
			$salerate=($first_newCurrency/$change_currencyPriecRow);
		  }
	 
//=======================================================================================	 
	 $buyRateRow=$_POST['buyRate'];    //  قیمت خرید از ارز پایه
	 if($buyRateRow!=0){
     
	  if($mode=='mode_1'){
			 $buymix=split("/",$rateRow);
			 $first_buy=$buymix[0];
			 $second_buy=$buymix[1]; 
             $salerate=($change_currencyPriecRow/$second_newCurrency);
             $buyRate=($buyRateRow/$second_buy);			 
		  }
		  if($mode=='mode_2'){
			 
			 $buymix=split("/",$rateRow);
			 $first_buy=$buymix[0];
			 $second_buy=$buymix[1]; 
			 $buyRate=($first_buy/$buyRateRow);	
		  }
	 
	       $resultTotalBuy=($buyRate*1)*$counterAmount; //مجموع معامله بر اساس قیمت خرید
	  
	}
	 
	 
 
    //-------------------------------------------------------------------------
 
	$buyRate_dollarRow=$_POST['buyRate_dollar'];// قیمت خرید به دالر
	$buyRate_dollarRowwmix=split("/",$buyRate_dollarRow);
	$first_buyRate_dollar =$buyRate_dollarRowwmix[0];
	$second_buyRate_dollar=$buyRate_dollarRowwmix[1]; 
	  
	 
	 
	//========================
	/*  if($change_currencyPriecRow!="" and $first_NewdollarPrice==""){
	   
	    echo' <script>
					sweetAlert("هشــدار...", "متانسب با تغییر قیمت فروش باید قیمت به دالر را هم تغییر دهید !", "error");
			   </script>'; 
		 echo '<meta http-equiv="refresh" content ="2; url=customerBuySell.php" >';
         die;
	 } */
	 
	//========================
	     $resultTotalSale=($salerate)*$counterAmount; //مجموع به مقدار فروخته شده
		//$resulttotlaDollar_sale=($first_NewdollarPrice/$second_NewdollarPrice)*$counterAmount;  //ارزش به دلار بابت فروش
	     
		//$salerate=($first_newCurrency/$second_newCurrency);
	
	} //if($change_currencyPriecRow!=0){
	//===================================================================================
	//===================================================================================
	//===================================================================================
					/*در صــــورتی که قیمت جدیــــد وجـــود نـــداشتــــه باشــــد*/
	
	     
		$salerateRow=$_POST['currencyPriec'];//  قیمت فروش ارز پایه
		 
		if($change_currencyPriecRow==0){
		
		   $oldCurrency=split("/",$salerateRow);
		   $first=$oldCurrency[0];
		   $second=$oldCurrency[1]; 
		   /* if($second=='1000' || $second=='1'){
			  
			   $unit_Sale=$second;
					   
			   $salerate= $first;		  
		   }else{
			   $unit_Sale=$first; 		  
			   $salerate= $second;
			  
		}  */
		    
		    $resultTotalSale=($first/$second)*$counterAmount; //مجمــوع بــه مقــدار خـــریداری شده
			//$resulttotlaDollar_sale=($first_dollarRatePrice/$secno_dollarRatePrice)*$counterAmount;  //ارزش به دالر به مقدار خریداری شده
			$salerate=($first/$second);
		}
 //=======================================================================================    
 //=======================================================================================    
	 
	 
	//------------------------------------------------------------------------
    
    $totalDollar=$_POST['totalDollar'];    // ارزش به دالر 	
	$unit=$_POST['unit'];
 
	//===========================================================
    
     $description=$_POST['desc'];    // توضیحات
     $profitCurrency=$resultTotalSale-$resultTotalBuy;  //محاسبه سود بعد از کم کردن قیمت خرید ارز پایه 
     
     //$dollarBuy=($first_buyRate_dollar/$second_buyRate_dollar)*$counterAmount; //ارزش به دلار بابت خرید
	 $dolarProfit=$totalDollar-$counterAmount;
   
   
   
    
    
 //=============================================قیمت خرید========================
 //==================================کم و اضافه کردن به حسابات مشتری==============
   //کم شدن از حسابی که باید کم شود
        $back_decreasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId_retrive' and currencyId='$counterCurrency_retrive' ";
	    $back_decreasecustomerQuery= $db ->query($back_decreasecustomerSql);
        $back_decreasecustomerRow=$back_decreasecustomerQuery ->fetch_array();
		
		$back_decreaseamount=$back_decreasecustomerRow['amount']; 
		$back_decreasedollarAmount=$back_decreasecustomerRow['dollarAmount'];
		 
        //echo "<br>==================================</br>";
		//======new amount
		$back_newDecreaseAmoun=$back_decreaseamount-$amount_retrive;
		$back_newDecreaseDollarAmoun=$back_decreasedollarAmount-$dollartotalbuy_retrive;
  
		$back_updateDecreaseCustomerSql="update customerbalance set amount='$back_newDecreaseAmoun',dollarAmount='$back_newDecreaseDollarAmoun'  where customerId='$customerId_retrive' and currencyId='$counterCurrency_retrive'";
        $back_updateDecreaseCustomerQuery= $db ->query($back_updateDecreaseCustomerSql);
	   
	 
	//-------------------------------------------------------------------------------------
								/* اضافه شده به حساب مشتری و برگشت به حالت اول*/
	//-------------------------------------------------------------------------------------
        
	    $back_increasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId_retrive' and currencyId='$baseCurrency_retrive' ";
        $back_increasecustomerQuery= $db ->query($back_increasecustomerSql);
        $back_increasecustomerRow=$back_increasecustomerQuery ->fetch_array();
	     
		$back_amount=$back_increasecustomerRow['amount']; 
		  
		$back_dollarAmount=$back_increasecustomerRow['dollarAmount'];
		
	
        //echo "<br>================================</br>";
        $back_newincreaseAmoun=$back_amount+$totalSell_retrive;
		$back_newincreaseDollarAmoun=$back_dollarAmount+$retrive_Base_dollarAmount;
        
        $back_updateIncreaseCustomerSql="update customerbalance set amount='$back_newincreaseAmoun',dollarAmount='$back_newincreaseDollarAmoun'  where customerId='$customerId_retrive' and currencyId='$baseCurrency_retrive'";
        $back_updateIncreaseCustomerQuery= $db ->query($back_updateIncreaseCustomerSql);		
        
//==========================================================================================
										/* پایان برگشت به عقب*/		
//==========================================================================================		
//****************************************************************************************		
//****************************************************************************************		
//****************************************************************************************		
//==================================کم و اضافه کردن به حسابات مشتری==============
   //کم شدن از حسابی که باید کم شود
        $decreasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId' and currencyId='$basecurrency' ";
		$decreasecustomerQuery= $db ->query($decreasecustomerSql);
        $decreasecustomerRow=$decreasecustomerQuery ->fetch_array();
		$decreaseamount=$decreasecustomerRow['amount'];
		$decreasedollarAmount=$decreasecustomerRow['dollarAmount'];
		 
        //======new amount
		$newDecreaseAmoun=$decreaseamount-$baceAmount;
		$newDecreaseDollarAmoun=$decreasedollarAmount-$dollarmoadelBaceCurrency;
        $updateDecreaseCustomerSql="update customerbalance set amount='$newDecreaseAmoun',dollarAmount='$newDecreaseDollarAmoun'  where customerId='$customerId' and currencyId='$basecurrency'";
        $updateDecreaseCustomerQuery= $db ->query($updateDecreaseCustomerSql);
         
  //=========== اضافه شدن به حساب مشتری
   
        $increasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId' and currencyId='$counterCurrency' ";
        $increasecustomerQuery= $db ->query($increasecustomerSql);
        $increasecustomerRow=$increasecustomerQuery ->fetch_array();
	    $amount=$increasecustomerRow['amount'];
		 
		$dollarAmount=$increasecustomerRow['dollarAmount'];
		if($amount==""){
		    $amount=0;
			$dollarAmount=0;
			 $newDecreaseAmoun=$amount+$counterAmount;
			 $newDecreaseDollarAmoun=$dollarAmount+$totalDollar;
		     
			 $insertcustomerSql="insert into customerbalance (customerId,currencyId,amount,dollarAmount)
             values('$customerId','$counterCurrency','$counterAmount','$newDecreaseDollarAmoun')";
		    $insertcustomerQuery=$db ->query($insertcustomerSql); 
		      
		}
		 
		 
		   if(isset($amount)){
		    $newDecreaseAmoun=$amount+$counterAmount;
		    $newDecreaseDollarAmoun=$dollarAmount+$totalDollar;
      
		   $updateincreaseCustomerSql="update customerbalance set amount='$newDecreaseAmoun',dollarAmount='$newDecreaseDollarAmoun'  where customerId='$customerId' and currencyId='$counterCurrency'";
           $updateincreaseCustomerQuery= $db ->query($updateincreaseCustomerSql);
             
		
		}
       

	   $updateCustomer_sell="update `customerssell` set
   	   customerId='$customerId',date='$date',counterCurrency='$counterCurrency',baseAmount='$basecurrency',amount='$counterAmount',sellRate='$salerate',buyRate='$buyRate',totalSell='$resultTotalSale',totalBuy='$resultTotalBuy',
	   baceCurrencyRate='$baseCurrencyRate',dollartotalbuy='$totalDollar',profit='$profitCurrency',descr='$description' where id='$get_id'";
	   
      $updateCustomer_buy_query=$db ->query($updateCustomer_sell);  
 
	   //---------------Customer SALLE-----
	    $update_customerPaymentSell_sql="update customerpayment set
	   date='$date',transactCurrency='$basecurrency',customerasset='$decreaseamount',amount='$baceAmount',
	   customerRemain='$remainCustomer',dollarRate='$dollarRatePrice',dollarTotal='$totalDollar',description='$description' where transacttype='2' and customersell_id='$get_id'";
	   $update_customerPaymentSell_query=$db ->query($update_customerPaymentSell_sql);
	   //---------------Customer BAY-----
	    
	   $update_customerPaymentBuy_sql="update customerpayment set
	   date='$date',transactCurrency='$counterCurrency',customerasset='$amount',amount='$counterAmount',
	   customerRemain='$newDecreaseAmoun',dollarRate='$dollarRatePrice',dollarTotal='$totalDollar',description='$description' where transacttype='1' and customersell_id='$get_id'";
	  
       $update_customerPaymentBuy_Query=$db ->query($update_customerPaymentBuy_sql);
 //============================ انتها کم و اضافه کردن به حسابات مشتری==============
 
 
		   
   echo "<script> window.close(); </script>";
		//header("location:../buy.php");		

}



?>