<!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'];
   
   $customerId_retrive=$_GET['customerId'];
   
     $customerRetriveSql="select * from `$table` where id='$get_id'   ";
	 $customerRetriveQuery=$db ->query($customerRetriveSql);
	 $customerRetriveRow=$customerRetriveQuery ->fetch_array();
	 $id_retrive=$customerRetriveRow['id'];
	 $dateretrive=$customerRetriveRow['date'];
	 $counterCurrency_retrive=$customerRetriveRow['counterCurrency'];
	 $baseCurrency_retrive=$customerRetriveRow['baseAmount'];
	 $amount_retrive=$customerRetriveRow['amount'];
	 $sellRate_retrive=$customerRetriveRow['sellRate'];
	 $buyRate_retrive=$customerRetriveRow['buyRate'];
	 $totalSell_retrive=$customerRetriveRow['totalSell'];
	 $totalBuy_retrive=$customerRetriveRow['totalBuy'];
	 $dollartotalsell_retrive=$customerRetriveRow['dollartotalsell'];
	 $dollartotalbuy_retrive=$customerRetriveRow['dollartotalbuy'];
	 $profit_retrive=$customerRetriveRow['profit'];
	 $description_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>
	     
									//Dollar Price
//====================================================================================
   function dollarPrice(){
	    $('#dollarRate').hide();
		$.post('../retiveDollarrateforSall.php', {
		   rateOfDollar:form.counterCurrency.value
		   },
			function(output){
				$('#dollarRate').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("");
		  
		  mainrate  =document.getElementById('currencyPriec').value;
		  total=(mainrate*1)*(amount*1);   
		  document.getElementById('baceAmount').value=FormatNumberBy3(total*1) ;
		  
		
		}   
//====================================================================================	
	
	function calculateDollar(){
	     insertval=setInterval("multipalDollar()",1);
	    }
		function multipalDollar(){
	     dollarRatePrice=document.getElementById('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("");
		 
		 
		 totalDollar=(dollarRatePrice*1)*(amount*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("");
		/* totalDollar=(dollarRatePrice*1)*(amount*1);
         findTotalDollar=totalDollar.toFixed(2); */   
		 document.getElementById('remainCustomer').value=FormatNumberBy3((balance*1)-(baceAmount*1));
		
		
		}	
//===============الباقی حساب مشتر===============================			
	 </script>
   
</head>
<body onload="assetCash();dollarPrice();calculateDollar();findingcalculation();customerBalance();findCash();get_amount();calculate();assetCash()">

	<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/treat.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;?>"/>
							<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="dollarPrice();get_amount();findingCounterCurrency();calculate()" onclick="get_amount();findingCounterCurrency();calculate();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" name="counterAmount" autocomplete="off" onkeyup="addSeparator(this)" id="counterAmount"   value="<?php echo $amount_retrive ?>" class="form-control"  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="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='asset'><input type="text" 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" >
							<div id='rate'><input type="text" name="rateOfCurrency" id='rateOfCurrency' 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='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" >
							<input type='text' name='remainCustomer' id="remainCustomer" 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='dollarRate'><input type="text"   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='text' 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 rows="3" cols="23"  name="description"  ><?php echo $description_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:../report/customerPaymentReport.php");
}
if($_POST['save']){
  $amount_retrive;//مقدار پول خریداری شده 
  $counterCurrency_retrive;// نوعیت پولی مورد خریداری شده
  
  $baseCurrency_retrive;//نوعیت پول پایه یا پول برداشته شده
  $totalSell_retrive;// مقدار فرخته شده از پول پایه
  $customerId_retrive;// شماره شناسایی مشتری
  $dollartotalbuy_retrive;// پول خریداری شده بر حسب دالر
  
//===============================================
   $date=$_POST['date'];
  
  $customerId=$_POST['customerId'];
  $counterCurrency=$_POST['counterCurrency'];//پول خریداری شده 
  $basecurrency=$_POST['basecurrency'];     // پول فروخته شده 
  $counterAmount=$_POST['counterAmount'];     // مقدار پول خریداری شده 
  $baceAmount=$_POST['baceAmount'];     // مقدارپول براساس ارز پایه 
  $totalDollar=$_POST['totalDollar'];     // مجموع به دالر 
  $remainCustomer=$_POST['remainCustomer'];     // باقی حساب مشتری 
  $dollarRatePrice=$_POST['dollarRatePrice']; //  قیمت به دلار
  $description=$_POST['description'];        //   توضیحات
  $buyrate=$_POST['currencyPriec'];         //  قیمت فروش ارز پایه 
  $saleRate=$_POST['buyRate'];    //  قیمت خرید از ارز پایه
  
    echo $resultTotalSale=$buyrate*$counterAmount; //مجموع به مقدار فروخته شده
    echo"<br>"; 
    echo $resultTotalBuy=$saleRate*$counterAmount;
    echo "<br>=============</br>";
    $profitCurrency=$resultTotalSale-$resultTotalBuy;
	
 //=============================================قیمت خرید========================
 
 $counterSql="select rate from crrencyrate where counterCurrency='$counterCurrency' and type='1'    ORDER BY id desc  LIMIT 1";
 $counterQuery= $db ->query($counterSql);
 $counterRow= $counterQuery ->fetch_array();
 $counterRate=$counterRow['rate'];
   
 $result=number_format(1/$counterRate,6);

 $dollarRatePrice*$counterAmount;
 
 $result*$counterAmount;
  
 $dollarBuy=$result*$counterAmount;
 
 $dolarProfit=$totalDollar-$dollarBuy;
 //==================================================================================== 
  
		/* if(strlen(trim($customerName))==0   ){
		echo' <script>
					sweetAlert("اخطار...", "لطفا نام را وارد کنید", "error");
			   </script>'; 
		die;


		} */
	 //=========================خروج پول خریداری شده از صندوق========================
	      $oldBuycustomermoneySql="select * from customerbalance where currencyId='$counterCurrency_retrive' and customerId='$customerId_retrive'";
		  $oldBuycustomermoneyQuery= $db ->query($oldBuycustomermoneySql);
		  $oldBuycustomermoneyRow=$oldBuycustomermoneyQuery ->fetch_array();
		  $oldcustomerAmount=$oldBuycustomermoneyRow['amount'];
		  echo "<br>";
		  $oldcustomerDollarAmount=$oldBuycustomermoneyRow['dollarAmount'];
		  //echo"<br>-------------</br>";
		  $backcustomerbaseAmount=$oldcustomerAmount-$amount_retrive;
		  $backcustomerbaseDollarAmount=$oldcustomerDollarAmount-$dollartotalbuy_retrive;
		  
		   $backUpdateCustomerBaseMoneySql="update customerbalance set amount='$backcustomerbaseAmount',dollarAmount='$backcustomerbaseDollarAmount' where currencyId='$counterCurrency_retrive' and customerId='$customerId_retrive'";
	       $backUpdateCustomerBaseMoneyQuery=$db ->query($backUpdateCustomerBaseMoneySql);
          
		  
		   
	//=========================برگشت پول فروخته شده به صندوق========================  
	      $oldSellcustomermoneySql="select * from customerbalance where currencyId='$baseCurrency_retrive' and customerId='$customerId_retrive'";
		  $oldSellcustomermoneyQuery= $db ->query($oldSellcustomermoneySql);
		  $oldSuycustomermoneyRow=$oldSellcustomermoneyQuery ->fetch_array();
		  $oldcustomerSellAmount=$oldSuycustomermoneyRow['amount'];
		   
		  $oldcustomerSellDollarAmount=$oldSuycustomermoneyRow['dollarAmount'];
		   
		  //echo"<br>-------------</br>";
		  $backcustomerSellAmount=$oldcustomerSellAmount+$totalSell_retrive;
		  $backcustomerSellDollarAmount=$oldcustomerSellDollarAmount+$dollartotalbuy_retrive;
		  
		  $backUpdateCustomerBaseMoneySql="update customerbalance set amount='$backcustomerSellAmount',dollarAmount='$backcustomerSellDollarAmount' where currencyId='$baseCurrency_retrive' and customerId='$customerId_retrive'";
	      $backUpdateCustomerBaseMoneyQuery=$db ->query($backUpdateCustomerBaseMoneySql);
         
	 
	 //=========================End of Back Asset================================ 
	 /*-------------------------------------------------------------------------------*/
	 /*-------------------------------------------------------------------------------*/
	 //=========================SEllCurrency=======================================
	          /*بخـــــــــــش خـــــــــــــــــــــریـــــــــداری پــــــــــول*/
	 //=========================End SEllCurrency===================================
	      $newBuycustomermoneySql="select * from customerbalance where currencyId='$counterCurrency' and customerId='$customerId_retrive'";
		  $newBuycustomermoneyQuery= $db ->query($newBuycustomermoneySql);
		  $newBuycustomermoneyRow=$newBuycustomermoneyQuery ->fetch_array();
		  $newcustomerAmount=$newBuycustomermoneyRow['amount'];
		  $newcustomerDollarAmount=$newBuycustomermoneyRow['dollarAmount'];
		  //echo"<br>-------------</br>";
		  /*ورود پول خریداری شده به صندوق*/
		  $newcustomerbaseAmount=$newcustomerAmount+$counterAmount;
		  $newcustomerbaseDollarAmount=$newcustomerDollarAmount+$totalDollar;
		  
		   $newbuyCustomerBaseMoneySql="update customerbalance set amount='$newcustomerbaseAmount',dollarAmount='$newcustomerbaseDollarAmount' where currencyId='$counterCurrency' and customerId='$customerId_retrive'";
	       $newbuyCustomerBaseMoneyQuery=$db ->query($newbuyCustomerBaseMoneySql);
              
	 //=========================SEllCurrency======================================= 
	          /*بخــــش فـــــــــــروش پــــــــــــــولـــــــــــــــــــی*/
	 //=========================End SEllCurrency===================================
	      /*خروج پول فروخته شده از صندوق*/
          $newSellcustomermoneySql="select * from customerbalance where currencyId='$basecurrency' and customerId='$customerId_retrive'";
		  $newSellcustomermoneyQuery= $db ->query($newSellcustomermoneySql);
		  $newSuycustomermoneyRow=$newSellcustomermoneyQuery ->fetch_array();
		  
		  $newcustomerSellAmount=$newSuycustomermoneyRow['amount'];
		  $newcustomerSellDollarAmount=$newSuycustomermoneyRow['dollarAmount'];
		   
		   
		  $newcustomerSellAmountbasecurency=$newcustomerSellAmount-$baceAmount;
		  $newcustomerSellDollarAmountbasecurency=$newcustomerSellDollarAmount-$totalDollar;
		   
		  $newSallCustomerBaseMoneySql="update customerbalance set amount='$newcustomerSellAmountbasecurency',dollarAmount='$newcustomerSellDollarAmountbasecurency' where currencyId='$basecurrency' and customerId='$customerId_retrive'";
	      $newSallCustomerBaseMoneyQuery=$db ->query($newSallCustomerBaseMoneySql);
          
		 	 
				 
	 //=================================================================================
	 //=================================================================================
					/*آپدیت پرداختــــــــی هـــــــای مشـــتــــــری*/
	 //=================================================================================
          //==========بخش فروش
		$updateoldsellcustomer_Sql="update customerpayment set 
		transactCurrency='$basecurrency',amount='$baceAmount',customerRemain='$remainCustomer',dollarRate='$dollarRatePrice',dollarTotal='$totalDollar',description='$description' where transacttype='2' and customersell_id='$id_retrive'";
		$updateoldsellcustomer_Query=$db ->query($updateoldsellcustomer_Sql);		 
	    //==========بخش خرید
		$updateoldBuycustomer_Sql="update customerpayment set 
		transactCurrency='$counterCurrency',amount='$counterAmount',customerRemain='$newcustomerbaseAmount',dollarRate='$dollarRatePrice',dollarTotal='$totalDollar',description='$description' where transacttype='1' and customersell_id='$id_retrive'";
		$updateoldBuycustomer_Query=$db ->query($updateoldBuycustomer_Sql);		 
				 
	 //===============================================================
     //=================================================================================
					/* آپـدیـــت بخــــش فروشـــــــــات بـــــه مشـتـــــــــری*/
	 //=================================================================================
      
 	    $updateCustomerSell_Sql="update customerssell set 
counterCurrency='$counterCurrency',baseAmount='$basecurrency',amount='$counterAmount',sellRate='$saleRate',buyRate='$buyrate',totalSell='$resultTotalSale',totalBuy='$resultTotalBuy',dollartotalsell='$dollarBuy',dollartotalbuy='$totalDollar',profit='$profitCurrency',dollarProfit='$dolarProfit',descr='$description' where id='$get_id'";
		$updateCustomerSell_Query=$db ->query($updateCustomerSell_Sql);	

     header("location:../report/customerSealsgeneralreport.php");		

}



?>