<!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'  ";
	 $customerRetriveQuery=$db ->query($customerRetriveSql);
	 $customerRetriveRow=$customerRetriveQuery ->fetch_array();
	 
	 $id_retrive=$customerRetriveRow['id'];
	 $retrive_date=$customerRetriveRow['date'];
	 $counterCurrency_retrive=$customerRetriveRow['counterCurrency'];
	 $counterAmount_retrive=$customerRetriveRow['counterAmount'];
	 $baseCurrency_retrive=$customerRetriveRow['baseCurrency'];
	 $rate_retrive=$customerRetriveRow['rate'];
	 $baseAmount_retrive=$customerRetriveRow['baseAmount'];
	 $dollarRate_retrive=$customerRetriveRow['dollarRate'];
	 $totalDollart_retrive=$customerRetriveRow['totalDollart'];
	 $descr_retrive=$customerRetriveRow['descr'];
		   
?>  
<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 dollarPrice(){
	    $('#dollarRate').hide();
		$.post('../retiveDollarrate.php', {
		   rateOfDollar:form.counterCurrency.value
		   },
			function(output){
				$('#dollarRate').html(output).fadeIn(10);
		})
	
	} 

//====================================================================================	
      function get_amount(){
	    $('#rate').hide();
		$.post('../retiveSalerrate.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(){
		 //currencyamount=document.getElementById('currencyPriec').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);		  
			  
		  }
		 
		   document.getElementById('baceAmount').value=FormatNumberBy3(pourCalculation*1) ;
		   //document.getElementById('baceAmount').value= take_Mode ;
		    
		
		}
		//====================================================================================	
	
	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;
		  
		  
		  /*   //نرخ جدید
		   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;
		  
		  //}  
		
		
		}
</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/banktransaction.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" >
							<div id='buyerAmount'><input type='text' id="baseAmount" class="filed"  ></div>							 
						</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)" value="<?php  echo $counterAmount_retrive ?>" 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()" onclick="get_amount();calculate();findCash()">
						<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='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' ></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_Rate" id='new_Rate' placeholder="نرخ جدید نسبت به دالر"  style='background: #ccffff;' class='filed'   onChange="calculate()" onclick="calculate()" > 
						</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 style="width:280px;">
							 
						 </td>
		    		</tr>
					 
					<!--<tr>
						<td style="width:190px">&nbsp;</td>
		    			<th style="width:150px">قیمت به دالر</th>
						<td style="width:250px" >-->
							<div id='dollarRate'><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='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:250px" >
							<textarea class="form-control" rows="3" 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="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:../banking.php");
}
if($_POST['save']){
     
	$counterCurrency_retrive=$customerRetriveRow['counterCurrency']; //ارز مورد معاوضه
	  
	$counterAmount_retrive=$customerRetriveRow['counterAmount'];     //مقدار ارز موردمعاوضه
	  
	  
	$baseCurrency_retrive=$customerRetriveRow['baseCurrency'];      //ارز پـایـه
	  
	$rate_retrive=$customerRetriveRow['rate'];                     // قیمت
	 
	$baseAmount_retrive=$customerRetriveRow['baseAmount'];         // ارزش به ارز پایه
	 
	$dollarRate_retrive=$customerRetriveRow['dollarRate'];        // مقدار به دالر
	
    $totalDollart_retrive=$customerRetriveRow['totalDollart'];    //مجموعه به دالر
      
//===============================================
    $date = $_POST['year']."-".$_POST['month']."-".$_POST['day'];
      
    $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);
    
   //============================================================================	
        
	     $baserateRow=$_POST['currencyPriec'];   //قیمت به پـــول پـــایه 
		 $baseRatePriceRowmix=split("/",$baserateRow);
		 $first_baseRatePrice =$baseRatePriceRowmix[0];
		 $second_baseRatePrice=$baseRatePriceRowmix[1]; 
		 
		/*  if($first_dollarRatePrice=='1'){
				  
				 $unit_dollarRate   =$first_dollarRatePrice; 	  
				 $dollarRatePrice = $second_dollarRatePrice;		  
		   }else{
				 
				 $unit_dollarRate=$second_dollarRatePrice;  
				 $dollarRatePrice= $first_dollarRatePrice;
			  
		   } */
		  $rate=($first_baseRatePrice/$second_baseRatePrice);
	//============================================================================	
	     $dollar_rateRow=$_POST['dollarRatePrice'];   //قیمت به دالر
         $dollarRatePriceRowmix=split("/",$dollar_rateRow);
		 $first_dollarRatePrice =$dollarRatePriceRowmix[0];
		 $second_dollarRatePrice=$dollarRatePriceRowmix[1]; 
		 
		/*  if($first_dollarRatePrice=='1'){
				  
				 $unit_dollarRate   =$first_dollarRatePrice; 	  
				 $dollarRatePrice = $second_dollarRatePrice;		  
		   }else{
				 
				 $unit_dollarRate=$second_dollarRatePrice;  
				 $dollarRatePrice= $first_dollarRatePrice;
			  
		   } */
		 $dollarRatePrice=($first_dollarRatePrice/$second_dollarRatePrice);
   //===================================================================================
     
   //============================================================================	
	     $new_rate_Row=$_POST['new_Rate'];   // قیمت به نرخ پایه جدید
         $new_RatePriceRowmix=split("/",$new_rate_Row);
		 $first_newRatePrice =$new_RatePriceRowmix[0];
		 $second_newRatePrice=$new_RatePriceRowmix[1]; 
		 
		 
		   $newRatePrice=($first_newRatePrice/$second_newRatePrice);  
   //===================================================================================
   
   
    $totalDollar_p=$_POST['totalDollar'];
    $totalDollar = preg_replace('/[^\d\.-]/', '', $totalDollar_p);//مجموع به دالر
   
  
	
    $desc=$_POST['desc'];   
    $calculateAsset=$balance+$baceAmount;
    if($newRatePrice!=0){
 
    $rate=$newRatePrice;
	
	
 }if($new_dollarRate==""){
 
    $rate=$rate;
 }
 
	 //=========================خروج پول خریداری شده از صندوق========================
	      $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-$totalDollart_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+$totalDollart_retrive;
		  
		    $backUpdateMoneySql="update assets set amount='$backcustomerSellAmount',dollarAmount='$backcustomerSellDollarAmount' where currencies_id='$baseCurrency_retrive'  ";
	        $backUpdateMoneyQuery=$db ->query($backUpdateMoneySql);
	  
	 //=========================End of Back Asset================================ 
/*----------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------*/
						/*وارد کردن به بانک بخش خریداری */
/*----------------------------------------------------------------------------------------*/
	       $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);
    }
	 
	 
   //========================/*مقدار ارزی که باید اضافه شود*/===============
    //echo "<br>===================================</br>";
        $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(isset($assetsellamount)){
	 
        $newcountercurrency=$assetsellamount+$counterAmount;
		$newDollarcountercurrency=$assetsellDollaramount+$totalDollar;
	    
        $updatecounterBankSql="update assets set amount='$newcountercurrency',dollarAmount='$newDollarcountercurrency' where currencies_id='$counterCurrency' ";
	    $updatecounterBankQuery= $db ->query($updatecounterBankSql);
    
	}
	 
	//====================================================================================
 						 /*مقدار ارزی که باید اضافه شود*/   
   //====================================================================================
      if(!isset($assetsellamount)){
	   
	  	    $insertSql="insert into `assets`(amount,currencies_id,dollarAmount) values ('$counterAmount','$counterCurrency','$totalDollar')";
	        $insertQuery= $db ->query($insertSql);
	 
	 }
    
		$updateBanking_Sql="update banking set 
		date='$date',counterCurrency='$counterCurrency',counterAmount='$counterAmount',baseCurrency='$basecurrency',rate='$rate',baseAmount='$baceAmount',dollarRate='$dollarRatePrice',totalDollart='$totalDollar',descr='$desc' where id='$get_id' ";
		
		$updateBanking_Query= $db ->query($updateBanking_Sql);
		
		header("location:../banking.php");
	 
   
  }

?>