<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<?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['editID'];
    
   $table=$_GET['table'];
   
    
   
     $customerRetriveSql="select * from `$table` where id='$get_id' and treatment='2'  ";
	 $customerRetriveQuery=$db ->query($customerRetriveSql);
	 $customerRetriveRow=$customerRetriveQuery ->fetch_array();
	 $id_retrive=$customerRetriveRow['id'];
	 
	 $retrive_date=$customerRetriveRow['date'];
	 
	 $counterCurrency_retrive=$customerRetriveRow['counterCurrency'];
	 $counterAmount_retrive=$customerRetriveRow['counterAmount'];
	 $rate_retrive=$customerRetriveRow['rate'];
	 $baseCurrency_retrive=$customerRetriveRow['baseCurrency'];
	 $baseAmount_retrive=$customerRetriveRow['baseAmount'];
	 $dollarRate_retrive=$customerRetriveRow['dollarRate'];
	 $dollarTotal_retrive=$customerRetriveRow['dollarTotal'];
	 $treatment_retrive=$customerRetriveRow['treatment'];
	 
	 
	  
	  
	 
	   
?>  
<html>
<head>
	<title>ویــرایــش فـــروشـــات</title>
	 
	<link rel="stylesheet" type="text/css" href="../css/style.css">
   <script src="dist/sweetalert-dev.js"></script>
  <link rel="stylesheet" href="dist/sweetalert.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>
  function bayerAmount(){
	    $('#buyerAmount').hide();
		$.post('../retrivebuyeramount.php', {bCurrencyA:form.counterCurrency.value},
			function(output){
				$('#buyerAmount').html(output).fadeIn(10);
		})
	
	}	      
	   
   
      function get_amount(){
	    $('#rate').hide();
		$.post('../retiverate.php', {
		   bCurrency:form.basecurrency.value, 
		   cCurrency:form.counterCurrency.value
		   },
			function(output){
				$('#rate').html(output).fadeIn(10);
		})
	
	}  
	   
    function findCash(){
	    $('#cash').hide();
		$.post('../retiveCash.php', {
		   currencyId:form.basecurrency.value
		   },
			function(output){
				$('#cash').html(output).fadeIn(10);
		})
	
	} 
//====================================================================================
								//Dollar Price
//====================================================================================
   function dollarPrice(){
	    $('#dollarPrice').hide();
		$.post('../retiveDollarrate.php', {
		   rateOfDollar:form.counterCurrency.value
		   },
			function(output){
				$('#dollarPrice').html(output).fadeIn(10);
		})
	
	} 

//====================================================================================	
	
	function calculate(){
	     insertval=setInterval("multipal()",1);
	    }
		function multipal(){
		
		  taraz_amount=document.getElementById('taraz_amount').value;
		  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);		  
			  
		  }
		  
		  
		  
		   if(taraz_amount==null){document.getElementById('taraz_amount').value=0;}
		   pourCalculation=(pourCalculation*1)+(taraz_amount*1);
		   document.getElementById('baceAmount').value=FormatNumberBy3(pourCalculation*1) ;
		   
		
		}
		//====================================================================================	
	
	function calculateDollar(){
	     insertval=setInterval("multipalDollar()",1);
	    }
		function multipalDollar(){
		 //dollarRatePrice=document.getElementById('dollarRatePrice').value;
		 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;
		  
		  totalDollar=(dollarexactresult*1)*(dollarmainrate*1);
		  findTotalDollar=totalDollar.toFixed(2); 
		  
		  document.getElementById('totalDollar').value=FormatNumberBy3(findTotalDollar);
		 
		/*  totalDollar=(dollarRatePrice*1)*(amount*1);
         findTotalDollar=totalDollar.toFixed(2);	  
		 document.getElementById('totalDollar').value=FormatNumberBy3(findTotalDollar*1);
		 */
		
		}
</script>
</head>
<body onload="bayerAmount();dollarPrice();findCash();get_amount();calculate();calculateDollar()">

	<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/sellRegister.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" >
						 <?php include("datepicker.php"); ?>
							<input type="hidden" name="customerId" id="customerId"   class="form-control" value="<?php echo $customerId_retrive  ;?>"/>
						</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%" onClick="bayerAmount();dollarPrice()" onChange="bayerAmount();dollarPrice()">
		                   <?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" autocomplete="off" onkeyup="addSeparator(this)" name="counterAmount" id="counterAmount"  value="<?php echo number_format($counterAmount_retrive); ?>" class="filed"  onChange="calculateDollar();nazari();"  onclick="calculateDollar();nazari()"/>
						</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="findCash();get_amount();calculate()" onclick="get_amount();calculate();findCash()">
															 
							<?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='cash'><input type="text" class='filed'></div>
						</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='rate'>
							<input type="text" name="rateOfCurrency" id='rateOfCurrency'  class='filed' value="<?php echo number_format($rate_retrive,2) ?>"> </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="taraz_amount" id='taraz_amount'     class='filed'  onChange="calculateDollar()" onclick="calculateDollar()" > 
						</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='filed'   >
							<input type='hidden' name='buyAmount' id="buyAmount"   >
							 
						 </td>
		    		</tr>
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<!--<th style="width:150px">قیمت به دالر</th>-->
						<td style="width:250px" >
						    <div id='dollarPrice'><input type="hidden"   class='filed' ></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="new_dollarRatePrice" id='new_dollarRatePrice' placeholder="نرخ جدید نسبت به دالر"  style='background: #ccffff;' class='filed'  onChange="calculateDollar()" onclick="calculateDollar()" > 
						</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='filed'   >
													 
						</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="save"   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:../dailyTransactionsale.php");
}
if($_POST['save']){
    $counterCurrency_retrive;   //پــول مورد معاوضه قدیم
	 
	$counterAmount_retrive;     // مقدار پول معاوضه شده
	
    $baseCurrency_retrive;      // ارز پـایه
     	
	 
	$rate_retrive;              // نــرخ
     	
	$baseAmount_retrive;        // مقدار ارز پایه
	 
	$treatment_retrive ;        // نوعیت معامله خرید
	 
	$dollarRate_retrive;        //نرخ به دالر
	 
	$dollarTotal_retrive;       // مجموع به دالر
    
	$dateretrive;
//===============================================
  $mode=$_POST['mode'];
    $date = $_POST['year']."-".$_POST['month']."-".$_POST['day'];
   echo "<br>";
    $counterCurrency=$_POST['counterCurrency'];  //ارزی که باید کم شود
    
   
    $counterAmount_p=$_POST['counterAmount']; //مقدار ارز معاوضه فروخته شده که باید کم شود 
    $counterAmount = preg_replace('/[^\d\.-]/', '', $counterAmount_p);
   
    $retrivebuyeramount_p=$_POST['retrivebuyeramount'];
    $retrivebuyeramount = preg_replace('/[^\d\.-]/', '', $retrivebuyeramount_p);
  
    $retrivebuyerafn_p=$_POST['retrivebuyerafn'];  //موجودی ارز مورد معاوضه 
    $retrivebuyerafn = preg_replace('/[^\d\.-]/', '', $retrivebuyerafn_p); 
    $basecurrency=$_POST['basecurrency']; //نوع ارز پایه 
         
	 
    $baceAmount_p=$_POST['baceAmount']; //مقدار فروخته شده به ارزش پایه
    $baceAmount = preg_replace('/[^\d\.-]/', '', $baceAmount_p);
    
   
    $balance_p=$_POST['balance']; //موجودی ارز پایه
    $balance = preg_replace('/[^\d\.-]/', '', $balance_p);
    
    //echo $rate=$_POST['rate'];
    $dollarRatePrice=$_POST['dollarRatePrice'];
    
       $totalDollar_p=$_POST['totalDollar'];
       $totalDollar = preg_replace('/[^\d\.-]/', '', $totalDollar_p);
     
	   $rate_gorss=$_POST['rate_currencyPriec'];// قیمت ارز 
	   $rate = preg_replace('/[^\d\.-]/', '', $rate_gorss);
//============================================================================	
        
	     $rate_currencyPriec=$_POST['rate_currencyPriec'];   //قیمت به پـــول پـــایه 
		 $rateRow=$_POST['currencyPriec'];        //به پـــول پــایـــه
         
	   //============================================================================	
        
	     $dollar_rateRow=$_POST['dollarRatePrice'];   //قیمت به دالر
         $dollarRatePriceRowmix=split("/",$dollar_rateRow);
		 $first_dollarRatePrice =$dollarRatePriceRowmix[0];
		 $second_dollarRatePrice=$dollarRatePriceRowmix[1]; 
		 
		 
		   $dollarrate=($first_dollarRatePrice/$second_dollarRatePrice);
	   
	   
	   
	   
//======قیمت فروش===================================
        $counterSql="select unit,rate from crrencyrate where counterCurrency='$counterCurrency' and baseCurrency='$basecurrency'  ORDER BY id desc  LIMIT 1";
		$counterQuery= $db ->query($counterSql);
		$counterRow= $counterQuery ->fetch_array();
		//echo "<br>======================================</br>";
		$counterRate=$counterRow['rate'];
		$unit=$counterRow['unit'];
        //$buyPrice=$counterRate/$unit;
		
		
		 
//===================================================
    
    $calculateAsset=$balance+$baceAmount;
if(strlen(trim($counterCurrency))==0 or strlen(trim($basecurrency))==0 or strlen(trim($baceAmount))==0){
		echo' <script>
					 sweetAlert("اخطا ر... ", "لطفا جاهای خالی را پرکنید !", "error");
				  </script>';

         echo '<meta http-equiv="refresh" content ="1; url=dailyTransactionsale.php" >';
		die;


}
   
  //====Delete Extra===========================
      $transatiionDelete_Sql="delete from transaction where id='$get_id' ";
      $transatiionDelete_Query= $db ->query($transatiionDelete_Sql);
  
     
	   if(isset($transatiionDelete_Query)){
	   
	     $extratSql="delete from transaction where extra='$get_id' ";
         $extratQuery= $db ->query($extratSql);
	   
	     //delete journal ===========================================================================
		  $delet_jouranlSql ="delete from journal where reference_id ='$get_id' and reference = 'فروش'";
		  $deletJournal = $db->query($delet_jouranlSql);
		  
		//journal deleted =====================================================================================

	   
	   }
	   
  //====Delete Extra===========================
  
    
  
     
	 //============================برگشت پول فروخته شده به صندوق=====================
	      $oldBuymoneySql="select * from assets where currencies_id='$counterCurrency_retrive'";
		  $oldBuymoneyQuery= $db ->query($oldBuymoneySql);
		  $oldBuymoneyRow=$oldBuymoneyQuery ->fetch_array();
		  $oldAmount=$oldBuymoneyRow['amount'];
		  $oldDollarAmount=$oldBuymoneyRow['dollarAmount'];
		  
		   
		  $backAmount      =$oldAmount+$counterAmount_retrive;
		  $backDollarAmount=$oldDollarAmount+$dollarTotal_retrive;
		 
		  $backUpdateMoneySql="update assets set amount='$backAmount',dollarAmount='$backDollarAmount' where currencies_id='$counterCurrency_retrive'";
	      $backUpdateCustomerBaseMoneyQuery=$db ->query($backUpdateMoneySql);
           
       
//==========================================================================================	   
//==========================================================================================	   
	//=========================خروج پول خریداری شده از صندوق========================  
	       
		  $oldSellmoneySql="select * from assets where currencies_id='$baseCurrency_retrive'";
		  $oldSellmoneyQuery= $db ->query($oldSellmoneySql);
		  $oldSuymoneyRow=$oldSellmoneyQuery ->fetch_array();
		  $oldSellAmount=$oldSuymoneyRow['amount'];
		  $oldSellDollarAmount=$oldSuymoneyRow['dollarAmount'];
		   
		  $backcustomerSellAmount=$oldSellAmount-$baseAmount_retrive;
		  $backcustomerSellDollarAmount=$oldSellDollarAmount-$dollarTotal_retrive;
	       
		  $backUpdateMoneySql="update assets set amount='$backcustomerSellAmount',dollarAmount='$backcustomerSellDollarAmount' where currencies_id='$baseCurrency_retrive'  ";
		  $backUpdateMoneyQuery=$db ->query($backUpdateMoneySql);
	  
	  if(isset($backUpdateMoneyQuery)){
	     $updatTransaction_Zero_Sql="update transaction set counterAmount='0' , baseAmount='0' where id='$get_id'";
	     $updatTransaction_Zero_query= $db ->query($updatTransaction_Zero_Sql);
		 
		 
		 
	  }
	  
	 //=========================End of Back Asset================================ 
/*----------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------*/
    //==============ارزی که باید از موجودی کم شود(Basecurrency)=========================
    $assetsell_sql="select currencies_id,amount,dollarAmount  from assets where currencies_id='$counterCurrency' ";
    $assetsellQuery= $db ->query($assetsell_sql);
    $assetsellRow=$assetsellQuery ->fetch_array();
	
	$assetsellamount=$assetsellRow['amount'];
	
    $assetsellDollaramount=$assetsellRow['dollarAmount']; 
   
	//فروش بیشتر از سرمایه نباشد
	   if( $counterAmount>$assetsellamount){
		    
		    echo' <script>
					 sweetAlert("اخطا ر... ", "شما پول کافی برای فروش ندارید!", "error");
				  </script>';
				echo '<meta http-equiv="refresh" content ="1; url=../dailyTransactionsale.php" >';
           			
	   die;
	   }  
	
	  //=========================================================================================
							/*عملیات اضافه شدن و کم شدن از صندوقها*/
	 //=========================================================================================
	  //echo "<br>فروشات که از صندوق کم شد</br>";
        $newcountercurrency=$assetsellamount-$counterAmount;
	    $newDollarcountercurrency=$assetsellDollaramount-$totalDollar;
     
	    $updatecounterBankSql="update assets set amount='$newcountercurrency',dollarAmount='$newDollarcountercurrency' where currencies_id='$counterCurrency' ";
	    $updatecounterBankQuery= $db ->query($updatecounterBankSql);
	     
	   //echo "<br>پول حاصل از فروش که باید اضافه شود</br>";
	  if($updatecounterBankQuery){
	
	 //======به صندوقی که باید اضافه شود 
		  $baseBankSql="select amount,dollarAmount from assets where currencies_id='$basecurrency'";
		  $baseBankQuery=$db ->query($baseBankSql);
		  $baseBankRow=$baseBankQuery ->fetch_array();
		 
		  $baseBank=$baseBankRow['amount']; 	
		  $basedollarAmountBank=$baseBankRow['dollarAmount'];
	  
		   if(isset($baseBank)){
			
			$newBasecurrency=$baseBank+$baceAmount;
			$newDollarBasecurrency=$basedollarAmountBank+$totalDollar;
			 
			$updateBaseBankSql="update assets set amount='$newBasecurrency',dollarAmount='$newDollarBasecurrency' where currencies_id='$basecurrency' ";
			$updateBaseQuery= $db ->query($updateBaseBankSql);
		   }//if(isset($baseBank)){
		   if(!isset($baseBank)){
	
			$insertSql="insert into `assets`(amount,currencies_id,dollarAmount) values ('$baceAmount','$basecurrency','$totalDollar')";
			$insertQuery= $db ->query($insertSql);
		
		   }// if(!isset($baseBank)){
		   
	 
 //=========================================================================================
							/*پایان عملیات بر روی صندوقها*/
 //========================================================================================
	

    //پیدا کردن مقدار خریداری های روز
   $totalBuySql="select sum(counterAmount) from transaction where counterCurrency='$counterCurrency' and baseCurrency='$basecurrency' and treatment='1' and date='$date'";
   $totalBuyQuery= $db ->query($totalBuySql);
   $totalBuyRow=$totalBuyQuery ->fetch_array(); 
   $totalBuy=$totalBuyRow['sum(counterAmount)'];
    
   //پیدا کردن مقدار فروشات های روز
   $totalSellSql="select sum(counterAmount) from transaction where counterCurrency='$counterCurrency' and baseCurrency='$basecurrency' and treatment='2' and date='$date'";
   $totalSellQuery= $db ->query($totalSellSql);
   $totalSellRow=$totalSellQuery ->fetch_array();
   $totalSell=$totalSellRow['sum(counterAmount)'];
    
    //پایان  فروشات روز
	 //مجموع فروشات=مجموع فروشات انجام شده+فروشات جدید
    $newTotalSell=$totalSell+$counterAmount;
    //تفاضل خریداری ها از فروشات=مجموع خریداریها-مجموع فروشات
    $resultTransaction=$totalBuy-$newTotalSell;
    
    if($resultTransaction<0   ){
   
          $resultTransaction=-$resultTransaction;
		   
         //====در صورتی که موجودی بانک ما کمتر بود
		 //if(مقداری که باید کم شود از موجودی بانک همان پول بیشتر باشد)

		// if(-$resultTransaction<$assetsellamount){
		    
		include("../lastRateBuy.php");
		include("../lastRateBuy_dollar.php");
		$rate_extra=$first_oldRate/$second_oldRate;
		$dollarrate_extra=$first/$second;
 
		//============فروش
		  
		$insertSql="INSERT INTO `transaction` (`date` ,`counterCurrency`,`counterAmount`,`rate`,`baseCurrency`,`baseAmount`,`treatment`,`dollarRate`,`dollarTotal`) 
	    VALUES ('$date','$counterCurrency','$counterAmount','$rate','$basecurrency','$baceAmount','2','$dollarrate','$totalDollar')";
	    $insertQuery = $db ->query($insertSql);
		  	
			//------------select last entry
	    $lastEntry_Sql="select id from `transaction` order by id desc limit 1 ";
		$lastEntry_Query= $db ->query($lastEntry_Sql);
		$lastEntry_Row=$lastEntry_Query ->fetch_array();
		$lastEntry=$lastEntry_Row['id'];
		
		//بــــــــــــــــــــــــــــــــــــه جورنال ثبتــــــــــــــــــــــــ کـــــــــــــــــــــــــــــــن

		  
		// به جورنال ثبت شد
		//journal out
		  $date=$date;
		  $namePart="فروش";
		  $reference="فروش";
		  $lastID=$lastEntry;
		  $currency=$counterCurrency;
		  $threadment="فروش";
		  $amount=$counterAmount;
		  $dr_cr=2;
		  include("../entery_journal_majul.php");
		  //End of Journal OUT
		  //journal IN
		  $date=$date;
		  $namePart="فروش";
		  $reference="فروش";
		  $lastID=$lastEntry;
		  $currency=$basecurrency;
		  $threadment="فروش";
		  $amount=$baceAmount;
		  $dr_cr=1;
		  include("../entery_journal_majul.php");
		  //End of Journal IN
		//------------select last entry
		
	    $baceAmountBuy=$resultTransaction*$rate_extra;
	    $dollar_total_extra=$dollarrate_extra*$resultTransaction;
		$insertbuySql="INSERT INTO `transaction` (`date` ,`counterCurrency`,`counterAmount`,`rate`,`baseCurrency`,`baseAmount`,`treatment`,`dollarRate`,`dollarTotal`,`extra`) 
	    VALUES ('$date','$counterCurrency','$resultTransaction','$rate_extra','$basecurrency','$baceAmountBuy','1','$dollarrate_extra','$dollar_total_extra','$lastEntry')";
	    
		$insertbuyQuery = $db ->query($insertbuySql);
		echo' <script>
					 
					
				   swal("ذخیره موفق!", "اطلاعات وارده با موفقیت ثبت سیستم شد", "success")
				</script>';
	    echo '<meta http-equiv="refresh" content ="1; url=../dailyTransactionsale.php" >';		
		  
      
   die;
   }

    else{
	
	    $insertSql="INSERT INTO `transaction` (`date` ,`counterCurrency`,`counterAmount`,`rate`,`baseCurrency`,`baseAmount`,`treatment`,`dollarRate`,`dollarTotal`) 
	    VALUES ('$date','$counterCurrency','$counterAmount','$rate','$basecurrency','$baceAmount','2','$dollarrate','$totalDollar')";
	    $insertQuery = $db ->query($insertSql);	
		
		//------------select last entry
	    $lastEntry_Sql="select id from `transaction` order by id desc limit 1 ";
		$lastEntry_Query= $db ->query($lastEntry_Sql);
		$lastEntry_Row=$lastEntry_Query ->fetch_array();
		$lastEntry=$lastEntry_Row['id'];
		
		//بــــــــــــــــــــــــــــــــــــه جورنال ثبتــــــــــــــــــــــــ کـــــــــــــــــــــــــــــــن

		 //journal out
		  $date=$date;
		  $namePart="فروش";
		  $reference="فروش";
		  $lastID=$lastEntry;
		  $currency=$counterCurrency;
		  $threadment="فروش";
		  $amount=$counterAmount;
		  $dr_cr=2;
		  include("../entery_journal_majul.php");
		  //End of Journal OUT
		  //journal IN
		  $date=$date;
		  $namePart="فروش";
		  $reference="فروش";
		  $lastID=$lastEntry;
		  $currency=$basecurrency;
		  $threadment="فروش";
		  $amount=$baceAmount;
		  $dr_cr=1;
		  include("../entery_journal_majul.php");
		  //End of Journal IN
		
		//header("location:sell.php");
		 echo' <script>
					 
					
				   swal("ذخیره موفق!", "اطلاعات وارده با موفقیت ثبت سیستم شد", "success")
				</script>';
	   echo '<meta http-equiv="refresh" content ="1; url=../dailyTransactionsale.php" >';
	 }  
	
	 } //if($updatecounterBankQuery){
    
   
  
   
} 
 