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

 include("db.php");
   $get_id=$_GET['editID'];
    
   $table=$_GET['table'];
   
  $information_sql="select * from `$table` where id='$get_id'";
  $information_query= $db->query($information_sql);
  $information_row=$information_query->fetch_array();
  
  $retrive_date=$information_row['date'];
  $expensesId_retrive=$information_row['expensesId'];
  $currencyId_retrive=$information_row['currencyId'];
  $currencyAsset_retrive=$information_row['currencyAsset'];
  $amount_retrive=$information_row['amount'];
  $dollarRate_retrive=$information_row['dollarRate'];
  $dollarTotal_retrive=$information_row['dollarTotal'];
  $description_retrive=$information_row['description'];
  ?> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<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 asset(){
	    $('#cash').hide();
		$.post('../expensesestimateRate.php', {
		   currencyId:form.counterCurrency.value
		   },
			function(output){
				$('#cash').html(output).fadeIn(10);
		})
	
	}  
	
	function findingCounterCurrency(){
	    $('#cCounter').hide();
		$.post('../retiveDollarrateforSall.php', {
		   rateOfDollar:form.counterCurrency.value
		   },
			function(output){
				$('#cCounter').html(output).fadeIn(10);
		})
	
	}
	 
	   
	 function calculate(){
	     insertval=setInterval("multipal()",1);
	    }
		function multipal(){
		 expensesAmount_p=document.getElementById('expensesAmount').value;
		 var decimalCharacter = ".",
         regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
         num_caldar=expensesAmount_p;
         var expensesAmount=+num_caldar.match(regex).join("");
		 
		 // نرخ قدیم
		  dollarmixData=document.getElementById('dollarmixData').value; 
		  dollartakeData=dollarmixData.split('/');
		  dollarmainrate=dollartakeData[0];
		  dollarunit=dollartakeData[1];
		  
		  var dollarexactresult=expensesAmount/dollarunit;
		 
		 
		 
		 
		 
		 //dollarRate  =document.getElementById('dollarRate').value;
		 total=(dollarexactresult*1)*(dollarmainrate*1);
		 resultcalculat=total.toFixed(4);
		 document.getElementById('result').value=(resultcalculat*1);
		
		
		}  
	 </script>   
</head>
<body onload="findingCounterCurrency();asset();calculate()">

	<div id="wrap">
		 
		<div id="contentt">
			 
			<div id="menu">
				<?php  //include("menu.php") ;   ?>
			</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/expensesDefeniation.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:280px" >
						<?php include("datepicker.php"); ?>
						</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="expensesName"  id='expensesName' style="width:100%"    >
								<option></option>
								<?php
								//include("config/views/db_const.php");
								$sql="select * from expensesname where remove='0'";
								$query=$db ->query($sql);
								while($row=$query ->fetch_array()){
								$id=$row['id'];
								$name=$row['name'];
								 
								if($expensesId_retrive == $row['id']){
								echo "<option value=$row[id] selected>$row[name] </option>";
								}else{
								    echo "<option value=$row[id]>$row[name]</option>";
								}
								
								}
								echo "</select>";
								?>
						</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();asset()" onclick="findingCounterCurrency();asset()">
							<option></option>
							<?php
							$sql="select * from currencies";
							$query=$db ->query($sql);
							while($row=$query ->fetch_array()){
							$id=$row['id'];
							$name=$row['name'];
							 
							 if($currencyId_retrive == $row['id']){
								echo "<option value=$row[id] selected>$row[name] </option>";
								}else{
								    echo "<option value=$row[id]>$row[name]</option>";
								}

							
							
							}
							echo "</select>";
							?>
						
						</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='cash'><input type="text" id="asetcash"  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="expensesAmount" value=<?php echo $amount_retrive  ?>  class="filed" id="expensesAmount" 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" >
						  <textarea  rows="3"  cols="3" name="desc" ><?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:250px" >-->
						    <div id='cCounter'><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="result" class="filed" id="result" onclick="calculate()">
						</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:../defineExpenses.php");
}
if($_POST['save']){

//====================================
  $date_retrive;
  $expensesId_retrive;
  $currencyId_retrive;
  $currencyAsset_retrive;
  $amount_retrive;
  $dollarRate_retrive;
  $dollarTotal_retrive;
//====================================

    $date = $_POST['year']."-".$_POST['month']."-".$_POST['day'];

	
  $expensesId=$_POST['expensesName'];       // نام مصرف
  $moneyId=$_POST['counterCurrency'];      // نوعیت پــول 
  $asetcash=$_POST['asetcash'];               // مـــــوجـــودی
  $expensesAmount=$_POST['expensesAmount'];   // مقدار مصرف
  $desc=$_POST['desc'];   // مقدار مصرف
  //==========================================================================
   $dollarRateRow=$_POST['dollarRatePrice'];           //قیمـــت بـــه دالــــر  
   $dollarRatePriceRowmix=split("/",$dollarRateRow);
	 $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;
		  
	   }
  
    $dollarRate=($unit_dollarRate/$dollarRatePrice);
   
 
  
  $result=$_POST['result'];              //مجمــوع بـــه دالـــر
  $assetCurrencyc=$_POST['assetCurrencyc'];
		 if(strlen(trim($expensesId))==0 or strlen(trim($moneyId))==0 or strlen(trim($expensesAmount))==0){
		echo' <script>
					 sweetAlert("اخطا ر... ", "لطفا جاهای خالی را پرکنید !", "error");
				  </script>';

         echo '<meta http-equiv="refresh" content ="1; url=defineExpenses.php" >';
		die;
		}
	    
//============================
	   echo "<br>----------------</br>";
	   $backAsset_Sql="select amount,dollarAmount from assets where currencies_id='$currencyId_retrive'";
	   $backAsset_Query= $db ->query($backAsset_Sql);
	   $backAsset_Row=$backAsset_Query ->fetch_array();
	   
	   $backAsset_Amount=$backAsset_Row['amount'];
	   $backAsset_DollarAmount=$backAsset_Row['dollarAmount'];
	   
	   $updateBackAmoun=$backAsset_Amount+$amount_retrive;
	   $updateBackdollarAmoun=$backAsset_DollarAmount+$dollarTotal_retrive;
	   
	   $update_Asset_Sql="update assets set  amount='$updateBackAmoun',dollarAmount='$updateBackdollarAmoun' where currencies_id='$currencyId_retrive'";
	   $update_Asset_Query= $db ->query($update_Asset_Sql);
//=======================================================================================
//=======================================================================================
										/*new Insertion */
//=======================================================================================
//=======================================================================================
	   
	    $assetBalanceSql="select amount,dollarAmount from assets where currencies_id='$moneyId' ";
        $assetBalanceQuery= $db ->query($assetBalanceSql);
		$assetBalanceRow=$assetBalanceQuery ->fetch_array();
		  
		$assetBalanceAmount=$assetBalanceRow['amount'];
		$assetBalancedollarAmount=$assetBalanceRow['dollarAmount'];
   
        $newAssetAmount=$assetBalanceAmount - $expensesAmount;
        $newAssetDollarAmount=$assetBalancedollarAmount - $result;
      
	    $updateSql="update assets set amount='$newAssetAmount',dollarAmount='$newAssetDollarAmount' where currencies_id='$moneyId'";
        $updateQuery =$db ->query($updateSql);
	   
	    if($updateQuery){
		   
		      $update_other_Sql="update others set description='$desc',date='$date',expensesId='$expensesId',currencyId='$moneyId',currencyAsset='$assetCurrencyc',amount='$expensesAmount',dollarRate='$dollarRate',dollarTotal='$result' where id='$get_id'";
		      $update_other_Query= $db ->query($update_other_Sql);
			  
			  // update journal ==============================================
			  $selectCustomer = "select name from expensesname where id =$expensesId";
			  $selectCusetomerQeury = $db->query($selectCustomer);
			  $selectCustomerRow = $selectCusetomerQeury->fetch_array();
			  $customerName = $selectCustomerRow['name'];
			  
			  $update_journal_Sql="update journal set name ='$customerName',date='$date',amount='$expensesAmount',currency='$moneyId' where reference_id='$get_id' and reference='مصرف'";
		      $update_journal_Query= $db ->query($update_journal_Sql);
			  
			  //end update journal ===================================
			  
		 echo' <script>
					 
					
				   swal("ذخیره موفق!", "اطلاعات وارده با موفقیت ثبت سیستم شد", "success")
				</script>';
	   echo '<meta http-equiv="refresh" content ="1; url=../defineExpenses.php" >';
	   echo  "<span style='color: green'>ذخیره سازی با موفقیت انجام شد</span>";
	   die;
		
		}
	   
		 
}



?>