<!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");
   $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();
  
  $customerId_retrive=$information_row['customerId'];
  $currencyId_retrive=$information_row['currencyId'];
  $amount_retrive=$information_row['amount'];
  $rate_retrive	=$information_row['rate'];
  $retrive_date=$information_row['date'];

  $dollarAmount_retrive=$information_row['dollarAmount'];
  
  if($amount_retrive<0){
       $status = "2";
	   $other_openingBalance_retrive=-$amount_retrive; 
	    
  }
  if($amount_retrive>0){
       
	   $status = "1";
	   $other_openingBalance_retrive=$amount_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>
<!---==========================================================================-->
<script type="text/javascript" src="../js/jquery-1.5.2.min.js"></script>
<!---==========================================================================-->
<script>
   
function myconfirm()
{
    if(confirm('آیا اطلاعات را می خواهید به طور دائم پاک کنید؟'))
        return true;
    return false;
}
      
	   
 function dollarPrice(){
	    $('#dollarRate').hide();
		$.post('../retiveDollarrate.php', {
		   rateOfDollar:form.basecurrency.value
		   },
			function(output){
				$('#dollarRate').html(output).fadeIn(10);
		})
	
	} 
	   
	 </script> 
	 <script>
		  function findingcalculation(){
	     insertval=setInterval("zarb()",1);
	    }
		  function zarb(){
	      openingBalanceP=document.getElementById('openingBalance').value; // مقدار ارز مورد معاوضه
		  var decimalCharacter = ".",
          regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
          num_caldar=openingBalanceP;
          var openingBalance=+num_caldar.match(regex).join("");  

          // نرخ قدیم
		  dollarmixData=document.getElementById('dollarmixData').value; 
		  dollartakeData=dollarmixData.split('/');
		  dollarmainrate=dollartakeData[0];
		  dollarunit=dollartakeData[1];
		  
		  var dollarexactresult=openingBalance/dollarunit;

		  totalDollar=(dollarmainrate*1)*(dollarexactresult*1);
          findTotalDollar=totalDollar.toFixed(2);   
		  document.getElementById('totalDollar').value=findTotalDollar;
		  
		
		}   
	 
	 </script>  
</head>
<body onload="dollarPrice();findingcalculation()">

	<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/openingBalance.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" placeholder="" 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="basecurrency"  id='basecurrency' style="width:100%" onClick="dollarPrice()" onchange="dollarPrice()" >
							<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" > 
						  <select name="transactType" id="transactType"  style="width: 100%" onchange="dollarsRate()" onclick="dollarsRate()">
							<option value="1" <?php if($status == "1"){ echo"selected"; } ?>>رسیدگی</option>
			                <option value="2" <?php if($status == "2"){ echo"selected"; } ?>>بردگی</option>
						  </select>
						
						</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"  class="filed" autocomplete="off" onkeyup="addSeparator(this)" id="openingBalance" name="openingBalance" value="<?php echo number_format($other_openingBalance_retrive,2); ?>" onChange="findingcalculation()" onclick="findingcalculation()"/>
							
						</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="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='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:../openingBalance.php");
}
if($_POST['save']){

  $customerId_retrive; // نمبر شناسایی مشتری
  $currencyId_retrive; // نوعیت پــول
  $amount_retrive;     // مقدار پول
  $dollarAmount_retrive; //مقدار به دلار
  
   $date = $_POST['year']."-".$_POST['month']."-".$_POST['day'];
   
  //================================================
	 
	$transactType=$_POST['transactType']; //نوعیت حساب
    
	$currencyId=$_POST['basecurrency'];
     
    $openingBalanceP=$_POST['openingBalance'];  // بلانس افتتاحیه
    $openingBalance = preg_replace('/[^\d\.-]/', '', $openingBalanceP);
    echo "<br>";
			
 
	//======================================================		
	 $dollarRatePriceRow=$_POST['dollarRatePrice'];
	 $dollarRatePriceRowmix=split("/",$dollarRatePriceRow);
	 $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=($unit_dollarRate*1)/($dollarRatePrice);
	//=====================================================
	 
	$totalDollarP=$_POST['totalDollar'];         // مجـــموع به دالر
    $totalDollar = preg_replace('/[^\d\.-]/', '', $totalDollarP);
     
     if($transactType=='1'){
	        $openingBalance; 
           	$customerStatment_OP=$openingBalance;	  
	        $totalDollar;
	 }
	 if($transactType=='2'){
	        $openingBalance=-$openingBalance;  
	         
			$totalDollar=-$totalDollar;
	        $customerStatment_OP=-$openingBalance;
	 }
	 
/*  if(strlen(trim($customerName))==0   ){
		echo' <script>
					sweetAlert("اخطار...", "لطفا نام را وارد کنید", "error");
			   </script>'; 
		die;


		} */
	   //.....................................................Estimate
	  
       $checking_Sql="select * from customerbalance where customerId='$customerId_retrive' and currencyId='$currencyId_retrive' ";
       $checking_Query=$db ->query($checking_Sql);
	   $checking_Row=$checking_Query ->fetch_array();
	   
	   $checking_amount=$checking_Row['amount'];
	   $checking_dollarAmount=$checking_Row['dollarAmount'];
	   
	   $total_checking_amount=$checking_amount-$amount_retrive;
	   $total_checking_dollarAmount=$checking_dollarAmount-$dollarAmount_retrive;
	   
	   $updateCustomerBalance="update customerbalance set amount='$total_checking_amount',dollarAmount='$total_checking_dollarAmount'  where customerId='$customerId_retrive' and currencyId='$currencyId_retrive'  ";
	   $updateCustomerBalanceQuery=$db ->query($updateCustomerBalance);
      
    //=============================================================================
					             	/* بخش ورودی جدید*/
    //=============================================================================
	    
	    $checking_Sql="select * from customeropeningbalance where customerId='$customerId_retrive' and currencyId='$currencyId'    ";
        $checking_Query=$db ->query($checking_Sql);
	    $checking_Row=$checking_Query ->fetch_array();
	    $checking=$checking_Row['currencyId'];
	 
	    if(isset($checking) and $checking!=$currencyId_retrive){
	    echo' <script>
					sweetAlert("اخطار...", "اطلاعات وارده در سیستم موجود است", "error");
			   </script>'; 
			   echo '<meta http-equiv="refresh" content ="1; url=../openingBalance.php" >';
			   // header("location: add_customer.php");
			 die ;
	       	  

	  
	  }
      
	   else{
	        $checking_Sql="select * from customerbalance where customerId='$customerId_retrive' and currencyId='$currencyId' ";
            $checking_Query=$db ->query($checking_Sql);
	        $checking_Row=$checking_Query ->fetch_array();
			$amount=$checking_Row['amount'];
			$dollarAmount=$checking_Row['dollarAmount'];
			if(isset($amount)){
	        
		      $newAmount=$amount+$openingBalance;
			  $newAmountdollar=$dollarAmount+$totalDollar;
		      
			  $updateCustomerBalance="update customerbalance set amount='$newAmount',dollarAmount='$newAmountdollar'  where customerId='$customerId_retrive' and currencyId='$currencyId'  ";
		      $updateCustomerBalanceQuery=$db ->query($updateCustomerBalance);
		       //===============================================
               $updateOpeningBalance_Sql="update customeropeningbalance set date='$date',
               customerId='$customerId_retrive',currencyId='$currencyId',amount='$openingBalance',rate='$dollarRatePrice',dollarAmount='$totalDollar' where id='$get_id'";
               $updateOpeningBalance_Query= $db ->query($updateOpeningBalance_Sql);

		       //===============================================  
             //update Customer Statement =
            $updateCustomerStatement = "update customer_statement set date='$date',currency_id ='$currencyId',amount ='$customerStatment_OP',transaction_type='$transactType' where transaction_id ='$get_id' and reference='بلانس افتتاحیه'";
	        $updateCustomerStatementQuery = $db->query($updateCustomerStatement);
	  			   





				  echo' <script>
			 	 
					
				   swal("ذخیره موفق!", "اطلاعات وارده با موفقیت ثبت سیستم شد", "success")
				</script>';
	             echo '<meta http-equiv="refresh" content ="1; url=../openingBalance.php" >';
             die;
		    }
			if(!isset($amount)){
			   $insert_sql="insert into customerbalance (customerId,currencyId,amount,dollarAmount)
      		   values('$customerId_retrive','$currencyId','$openingBalance','$totalDollar')";
		       $insert_Query= $db ->query($insert_sql);
			   
			   
			   $updateOpeningBalance_Sql="update customeropeningbalance set date='$date',
               customerId='$customerId_retrive',currencyId='$currencyId',amount='$openingBalance',rate='$dollarRatePrice',dollarAmount='$totalDollar' where id='$get_id'";
               $updateOpeningBalance_Query= $db ->query($updateOpeningBalance_Sql);

			   //update Customer Statement =
				$updateCustomerStatement = "update customer_statement set date='$date',currency_id ='$currencyId',amount ='$customerStatment_OP',transaction_type='$transactType' where transaction_id ='$get_id' and reference='بلانس افتتاحیه'";
				$updateCustomerStatementQuery = $db->query($updateCustomerStatement);
					   
			   
			    echo' <script>
			 	 
					
				   swal("ذخیره موفق!", "اطلاعات وارده با موفقیت ثبت سیستم شد", "success")
				</script>';
	          echo '<meta http-equiv="refresh" content ="1; url=../openingBalance.php" >';
      
			}
		   die;
	       
	       
	  
	  }
    //=============================================================================
					              	/* بخش ورودی جدید*/
    //=============================================================================



  

	  
		 
}



?>