<!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='1'  ";
	 $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'];
	 
	 if($baseCurrency_retrive==1){
	    $counterAmount_retrive;
		 
		$rate_retrive;
		
		$reusltCalculation=($counterAmount_retrive/$rate_retrive);
	 }
	 if($baseCurrency_retrive!=1){
	     $reusltCalculation=($counterAmount_retrive*$rate_retrive);
	 
	 }
	 
	  
	  
	 
?>  
<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 get_amount(){
	    $('#rate').hide();
		$.post('../retiverate.php', {
		   bCurrency:form.basecurrency.value, 
		   cCurrency:form.counterCurrency.value
		   },
			function(output){
				$('#rate').html(output).fadeIn(10);
		})
	
	}       
									//Dollar Price
//====================================================================================
   function dollarPrice(){
	    $('#ghaimat_be_dollar').hide();
		$.post('../retiveDollarrate.php', {
		   rateOfDollar:form.counterCurrency.value,
		   bCurrency:form.basecurrency.value, 
		   },
			function(output){
				$('#ghaimat_be_dollar').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('../retiveCash.php', {
		  currencyId:form.basecurrency.value
		   },
			  function(output){
			  $('#asset').html(output).fadeIn(10);
		  })
	
	  }
	
	
	
	
	
	function findingCounterCurrency(){
	    $('#cCounter').hide();
		$.post('../estimateCounterRate.php', {
		   countercurrencyId:form.counterCurrency.value
		   },
			function(output){
				$('#cCounter').html(output).fadeIn(10);
		})
	
	}
	
	 
	 
	 
	   function calculate(){
	     insertval=setInterval("multipal()",1);
	    }
		function multipal(){
		 firstCurrency=document.getElementById('firstCurrency').value;
		 secondCurrency  =document.getElementById('secondCurrency').value;
		 total=(firstCurrency*1)/(secondCurrency*1);
		 calculat=total.toFixed(4);
		 document.getElementById('result').value=(calculat*1);
		
		
		}  
	 </script> 
	 <script>
		  function findingcalculation(){
	           insertval=setInterval("zarb()",1);
	       }
		  function zarb(){
		  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);
		
		
		}	 
	 </script>
   
</head>
<body onload="findingCounterCurrency();calculate();dollarPrice();findingcalculation();findCash();get_amount();assetCash();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/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" >
						<?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%" onchange="findingCounterCurrency();calculate();dollarPrice();get_amount()" onclick="findingCounterCurrency();calculate();dollarPrice();get_amount()">
							<?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" required  value="<?php echo number_format($counterAmount_retrive) ?>" onkeyup="addSeparator(this)" name="counterAmount" id="counterAmount"    class="filed"  onChange="calculateDollar()" onclick="calculateDollar()"/> 
						</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();findingcalculation();assetCash()" onclick="findingcalculation();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='asset'><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' onclick="findingcalculation()"  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' value="<?php echo number_format($reusltCalculation) ?>"  >						 
						<td style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					<tr>
						<td style="width:190px">&nbsp;</td>
		    			<!--<th style="width:150px">قیمت به دالر</th>-->
						<td style="width:250px" >
							<div id='ghaimat_be_dollar'><input type="hidden" id="ghaymatDollar"   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:../dailyTransaction.php");
}
if($_POST['save']){
     $counterCurrency_retrive;   //پــول مورد معاوضه قدیم
	 echo "<br>";
	 $counterAmount_retrive;     // مقدار پول معاوضه شده
	 
	 $rate_retrive;              // نــرخ
	  
	 $baseCurrency_retrive;      // ارز پـایه
	  
	 $baseAmount_retrive;        // مقدار ارز پایه
	 $treatment_retrive ;        // نوعیت معامله خرید
	 $dollarRate_retrive;        //نرخ به دالر
	 $dollarTotal_retrive;       // مجموع به دالر
  
//===============================================
    $mode=$_POST['mode'];

         $rate_gross=$_POST['rate_currencyPriec'];// قیمت ارز 
	     $rate = preg_replace('/[^\d\.-]/', '', $rate_gross);
	 
    $baceAmount=$_POST['baceAmount'];// مقدار تبدیلی
	
    $counterCurrency=$_POST['counterCurrency'];// ارزی که باید اضافه شود
    
    $counterAmountP=$_POST['counterAmount'];    //مقدار ارزی که باید اضافه شود
    $counterAmount = preg_replace('/[^\d\.-]/', '', $counterAmountP);
    
    $bacecurrency=$_POST['basecurrency'];     //ارزی که باید کم شود
    
    $baceAmountP=$_POST['baceAmount'];   //مقداری که باید کم شود
    $baceAmount = preg_replace('/[^\d\.-]/', '', $baceAmountP);
  
    $balance_p=$_POST['balance'];
    $balance = preg_replace('/[^\d\.-]/', '', $balance_p); //موجودی اولیه 
	 
 //===================================================================================
         $rate_currencyPriec=$_POST['rate_currencyPriec'];   //قیمت به پـــول پـــایه 
		 $rateRow=$_POST['currencyPriec'];        //به پـــول پــایـــه
        //========================================================================
		
		
		
        //========================================================================
		 
	
 //==================================================================================
 //===================================================================================
         $dollarrateRow=$_POST['dollarRatePrice'];        //بــه دلار
         $dollarRatePriceRowmix=split("/",$dollarrateRow);
		 $first_dollarRatePrice =$dollarRatePriceRowmix[0];
		 $second_dollarRatePrice=$dollarRatePriceRowmix[1]; 
		 
		 $dollar_rate=($first_dollarRatePrice/$second_dollarRatePrice);
		 
		   
 //==================================================================================
 
 
 
 
    $date = $_POST['year']."-".$_POST['month']."-".$_POST['day'];
    $totalDollarP=$_POST['totalDollar'];
    $totalDollar = preg_replace('/[^\d\.-]/', '', $totalDollarP);
 
 
 if(strlen(trim($counterCurrency))==0 or strlen(trim($bacecurrency))==0 or strlen(trim($baceAmount))==0){
		echo' <script>
					 sweetAlert("اخطا ر... ", "لطفا جاهای خالی را پرکنید !", "error");
				  </script>';

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


}
 
  
	 //=========================کم شدن پول اضافه شده به صندوق========================
	      
		 $oldBuymoneySql="select * from assets where currencies_id='$counterCurrency_retrive'";
          
		  $oldBuymoneyQuery= $db ->query($oldBuymoneySql);
		  $oldBuymoneyRow=$oldBuymoneyQuery ->fetch_array();
		   
		  $oldAmount=$oldBuymoneyRow['amount'];
		   
		  $counterAmount_retrive;
		   
		  $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;
		   
		  
        
		   $backUpdateMoneySql="update assets set amount='$backcustomerSellAmount',dollarAmount='$backcustomerSellDollarAmount' where currencies_id='$baseCurrency_retrive'  ";
	       $backUpdateMoneyQuery=$db ->query($backUpdateMoneySql);
		   
		   $delete_JournalEntery_sql="delete from journal where reference='خرید' and reference_id='$get_id'";
           $delete_JournalEntery_query = $db ->query($delete_JournalEntery_sql);
	//=========================End of Back Asset================================ 
          
/*----------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------*/
						/*وارد کردن به بانک بخش خریداری */
/*----------------------------------------------------------------------------------------*/
	//خریداری پول و اضافه شدن به صندوق
	      $newBuymoneySql="select * from assets where currencies_id='$counterCurrency'";
		  $newBuymoneyQuery= $db ->query($newBuymoneySql);
		  $newBuymoneyRow=$newBuymoneyQuery ->fetch_array();
		  
		  $newAmount=$newBuymoneyRow['amount'];
		   
		  $newDollarAmount=$newBuymoneyRow['dollarAmount'];
        
		 if(isset($newAmount)){ 
		       
			   $newBuyAmount        =$newAmount+$counterAmount;
			   $newBuyDollarAmount  =$newDollarAmount+$totalDollar;
			   $newBuyUpdateMoneySql="update assets set amount='$newBuyAmount',dollarAmount='$newBuyDollarAmount' where currencies_id='$counterCurrency'  ";
			   $newBuyUpdateMoneyQuery=$db ->query($newBuyUpdateMoneySql);
                
		  }
          
         if(!isset($newAmount)){
	        
	  	      $insertSql="insert into `assets`(amount,currencies_id,dollarAmount) values ('$counterAmount','$counterCurrency','$totalDollar')";
	          $insertQuery= $db ->query($insertSql);
	     }
   //======================فروش از پول و کم شدن از صندوق 
          $newSellmoneySql="select * from assets where currencies_id='$bacecurrency'";
		  $newSellmoneyQuery= $db ->query($newSellmoneySql);
		  $newSellmoneyRow=$newSellmoneyQuery ->fetch_array();
           		 
		  $newSellAmount=$newSellmoneyRow['amount'];
		   
		  $newSellDollarAmount=$newSellmoneyRow['dollarAmount'];
		  
		  $newCalculateSellAmount =$newSellAmount-$baceAmount;
		   
		  $newCalculatSellDollarAmount  =$newSellDollarAmount-$totalDollar;
		  
		  $newSellUpdateMoneySql="update assets set amount='$newCalculateSellAmount',dollarAmount='$newCalculatSellDollarAmount' where currencies_id='$bacecurrency'  ";
	      
		  $newSellUpdateMoneyQuery=$db ->query($newSellUpdateMoneySql);
		   
		  if($newSellUpdateMoneyQuery){
		  
		    $updateTransaction_Sql="update transaction 
								set  
			date='$date',counterCurrency='$counterCurrency',counterAmount='$counterAmount',rate='$rate',baseCurrency='$bacecurrency',baseAmount='$baceAmount',dollarRate='$dollar_rate',dollarTotal='$totalDollar' where id='$get_id'";
		    
			$updateTransaction_Query= $db ->query($updateTransaction_Sql);
			
			//ویـــرایـش جورنــــــــــــــــــــــال
			
		  //journal out
		  $date=$date;
		  $namePart="خرید";
		  $reference="خرید";
		  $lastID=$get_id;
		  $currency=$bacecurrency;
		  $threadment="خرید";
		  $amount=$baceAmount;
		  $dr_cr=2;
		  include("../entery_journal_majul.php");
		  //End of Journal OUT
		  //journal IN
		  $date=$date;
		  $namePart="خرید";
		  $reference="خرید";
		  $lastID=$get_id;
		  $currency=$counterCurrency;
		  $threadment="خرید";
		  $amount=$counterAmount;
		  $dr_cr=1;
		  include("../entery_journal_majul.php");
		  //End of Journal IN
		 }
          
        header("location:../dailyTransaction.php");		

}



?>