<html>
<head>
    <script src="dist/sweetalert-dev.js"></script>
    <link rel="stylesheet" href="dist/sweetalert.css">
    <link rel="stylesheet" href="css/screen.css" type="text/css"   />
</head>
<body>

<?php
if($_POST['submit']){
  include("db.php");
    $customerId=$_POST['customerId'];
     $mode=$_POST['mode'];
    $date=$_POST['date'];
	 
	$counterCurrency=$_POST['counterCurrency'];//نام ارزی که مقدار آن باید اضافه شود
	 
	$counterAmountP=$_POST['counterAmount'];//  مقدار ارزی که باید اضافه شود
    $counterAmount = preg_replace('/[^\d\.-]/', '', $counterAmountP);
     
	$basecurrency=$_POST['basecurrency'];//  نام ارزی که مقدار آن باید کم شود 
	
	//=================پیدا کردن ارز پـایه نصبت به دالر==========================
	     echo  $baseCurrencyRate_Sql="select rate from crrencyrate where baseCurrency='$basecurrency' and counterCurrency='2' order by id desc limit 1";
	      $baseCurrencyRate_Query= $db ->query($baseCurrencyRate_Sql);
		  $baseCurrencyRate_Row=$baseCurrencyRate_Query->fetch_array();
		  $baseCurrencyRate=$baseCurrencyRate_Row['rate'];
	      if(!isset($baseCurrencyRate)){
	       
		     echo "<script> alert('قیمت ارز پـایه را به دالر در قسمت نرخ دهی ثبت کنید')
			 
			     window.location = 'currencyRate.php';
			 
			 </script>";
		   
		   die;
		   }
	
	//=================پیدا کردن ارز پـایه نصبت به دالر==========================
	
	 
	$balanceP=$_POST['balance'];//  موجودی ارز پایه
    $balance = preg_replace('/[^\d\.-]/', '', $balanceP); 
 //=======================================================================================
	 
	$baceAmountP=$_POST['baceAmount'];    //  ارزش به ارز پایه(مقداری که باید کم شود)
    $baceAmount = preg_replace('/[^\d\.-]/', '', $baceAmountP);
	 
	$remainCustomerP=$_POST['remainCustomer'];    // الباقی حساب مشتری
    $remainCustomer = preg_replace('/[^\d\.-]/', '', $remainCustomerP);	
  //---------------------------------------------------------------------------- 
	$dollarmoadelBaceCurrency=$baceAmount/$baseCurrencyRate;
	 
//======================================================================================	 
//======================================================================================	 
//======================================================================================	 
	 $change_currencyPriecRow=$_POST['change_currencyPriec'];//  قیمت فروش جدی 
	 $rateRow=$_POST['currencyPriec'];        //به پـــول پــایـــه
     
	if($change_currencyPriecRow!=0){
	
	   
	   
	   if($mode=='mode_1'){
			$newCurrency=split("/",$rateRow);
	        $first_newCurrency=$newCurrency[0];
	        $second_newCurrency=$newCurrency[1];
            $salerate=($change_currencyPriecRow/$second_newCurrency);			
		  }
		  if($mode=='mode_2'){
			 
			$newCurrency=split("/",$rateRow);
	        $first_newCurrency=$newCurrency[0];
	        $second_newCurrency=$newCurrency[1]; 
			$salerate=($first_newCurrency/$change_currencyPriecRow);
		  }
	 
//=======================================================================================	 
	 $buyRateRow=$_POST['buyRate'];    //  قیمت خرید از ارز پایه
	 if($buyRateRow!=0){
     
	  if($mode=='mode_1'){
			 $buymix=split("/",$rateRow);
			 $first_buy=$buymix[0];
			 $second_buy=$buymix[1]; 
             $salerate=($change_currencyPriecRow/$second_newCurrency);
             $buyRate=($buyRateRow/$second_buy);			 
		  }
		  if($mode=='mode_2'){
			 
			 $buymix=split("/",$rateRow);
			 $first_buy=$buymix[0];
			 $second_buy=$buymix[1]; 
			 $buyRate=($first_buy/$buyRateRow);	
		  }
	 
	       $resultTotalBuy=($buyRate*1)*$counterAmount; //مجموع معامله بر اساس قیمت خرید
	  
	}
	 
	 
 
    //-------------------------------------------------------------------------
 
	$buyRate_dollarRow=$_POST['buyRate_dollar'];// قیمت خرید به دالر
	$buyRate_dollarRowwmix=split("/",$buyRate_dollarRow);
	$first_buyRate_dollar =$buyRate_dollarRowwmix[0];
	$second_buyRate_dollar=$buyRate_dollarRowwmix[1]; 
	  
	 
	 
	//========================
 
	//========================
	     $resultTotalSale=($salerate)*$counterAmount; //مجموع به مقدار فروخته شده
		//$resulttotlaDollar_sale=($first_NewdollarPrice/$second_NewdollarPrice)*$counterAmount;  //ارزش به دلار بابت فروش
	     
		//$salerate=($first_newCurrency/$second_newCurrency);
	
	} //if($change_currencyPriecRow!=0){
	//===================================================================================
	//===================================================================================
	//===================================================================================
					/*در صــــورتی که قیمت جدیــــد وجـــود نـــداشتــــه باشــــد*/
	
	     
		$salerateRow=$_POST['currencyPriec'];//  قیمت فروش ارز پایه
		 
		if($change_currencyPriecRow==0){
		
		   $oldCurrency=split("/",$salerateRow);
		   $first=$oldCurrency[0];
		   $second=$oldCurrency[1]; 
		   /* if($second=='1000' || $second=='1'){
			  
			   $unit_Sale=$second;
					   
			   $salerate= $first;		  
		   }else{
			   $unit_Sale=$first; 		  
			   $salerate= $second;
			  
		}  */
		    
		    $resultTotalSale=($first/$second)*$counterAmount; //مجمــوع بــه مقــدار خـــریداری شده
			//$resulttotlaDollar_sale=($first_dollarRatePrice/$secno_dollarRatePrice)*$counterAmount;  //ارزش به دالر به مقدار خریداری شده
			$salerate=($first/$second);
		}
 //=======================================================================================    
 //=======================================================================================    
	 
	 
	//------------------------------------------------------------------------
    
    $totalDollar=$_POST['totalDollar'];    // ارزش به دالر 	
	$unit=$_POST['unit'];
 
	//===========================================================
    
     $description=$_POST['desc'];    // توضیحات
     $profitCurrency=$resultTotalSale-$resultTotalBuy;  //محاسبه سود بعد از کم کردن قیمت خرید ارز پایه 
     
     //$dollarBuy=($first_buyRate_dollar/$second_buyRate_dollar)*$counterAmount; //ارزش به دلار بابت خرید
	 $dolarProfit=$totalDollar-$counterAmount;
   
   
   
    
    
 //=============================================قیمت خرید========================
 
 //==================================کم و اضافه کردن به حسابات مشتری==============
   //کم شدن از حسابی که باید کم شود
        $decreasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId' and currencyId='$basecurrency' ";
		$decreasecustomerQuery= $db ->query($decreasecustomerSql);
        $decreasecustomerRow=$decreasecustomerQuery ->fetch_array();
		$decreaseamount=$decreasecustomerRow['amount'];
		$decreasedollarAmount=$decreasecustomerRow['dollarAmount'];
		 
        //======new amount
		$newDecreaseAmoun=$decreaseamount-$baceAmount;
		$newDecreaseDollarAmoun=$decreasedollarAmount-$dollarmoadelBaceCurrency;
        $updateDecreaseCustomerSql="update customerbalance set amount='$newDecreaseAmoun',dollarAmount='$newDecreaseDollarAmoun'  where customerId='$customerId' and currencyId='$basecurrency'";
        $updateDecreaseCustomerQuery= $db ->query($updateDecreaseCustomerSql);
         
  //=========== اضافه شدن به حساب مشتری
   
        $increasecustomerSql="select amount,dollarAmount from customerbalance where customerId='$customerId' and currencyId='$counterCurrency' ";
        $increasecustomerQuery= $db ->query($increasecustomerSql);
        $increasecustomerRow=$increasecustomerQuery ->fetch_array();
	    $amount=$increasecustomerRow['amount'];
		 
		$dollarAmount=$increasecustomerRow['dollarAmount'];
		 
		if($amount==""){
		    $amount=0;
			$dollarAmount=0;
			 $newDecreaseAmoun=$amount+$counterAmount;
			 $newDecreaseDollarAmoun=$dollarAmount+$totalDollar;
		     
			 $insertcustomerSql="insert into customerbalance (customerId,currencyId,amount,dollarAmount)
             values('$customerId','$counterCurrency','$counterAmount','$newDecreaseDollarAmoun')";
		    $insertcustomerQuery=$db ->query($insertcustomerSql); 
		      
		}
		if(isset($amount)){
		    $newDecreaseAmoun=$amount+$counterAmount;
		    $newDecreaseDollarAmoun=$dollarAmount+$totalDollar;
      
		   $updateincreaseCustomerSql="update customerbalance set amount='$newDecreaseAmoun',dollarAmount='$newDecreaseDollarAmoun'  where customerId='$customerId' and currencyId='$counterCurrency'";
           $updateincreaseCustomerQuery= $db ->query($updateincreaseCustomerSql);
             
		
		}
        
 //============================ انتها کم و اضافه کردن به حسابات مشتری==============
 
 
 
 //=====================ذخیره کردن به قسمت خرید و فروش============================
    $customerSellSql="insert into `customerssell` 
   (customerId,date,counterCurrency,baseAmount,amount,sellRate,buyRate,totalSell,totalBuy,baceCurrencyRate,dollartotalbuy,profit,descr)
												values
	('$customerId','$date','$counterCurrency','$basecurrency','$counterAmount','$salerate','$buyRate','$resultTotalSale','$resultTotalBuy','$baseCurrencyRate','$totalDollar','$profitCurrency','$description')";
    
     $customerSellQuery=$db ->query($customerSellSql);  
   
   if($customerSellQuery){
   
       $takeLastIdSql="SELECT id from customerssell ORDER BY `id` DESC LIMIT 1";
	   $takeLastIdQuery= $db ->query($takeLastIdSql);
	   $takeLastIdRow=$takeLastIdQuery->fetch_array();
	   $takeLastId=$takeLastIdRow['id'];
   
   
   }


 //======بردگی
    $insertCustomerPaymentGetSql="insert into customerpayment 
   (customersell_id,customerId,date,referenceNo,transacttype,transactCurrency,customerasset,amount,customerRemain,description) values 
   ('$takeLastId','$customerId','$date','خریدو فروش','2','$basecurrency','$decreaseamount','$baceAmount','$remainCustomer','$description')";
   $insertCustomerPaymentGetQuery=$db ->query($insertCustomerPaymentGetSql);
   
    $insertCustomerPaymentSaveSql="insert into customerpayment 
    (customersell_id,customerId,date,referenceNo,transacttype,transactCurrency,customerasset,amount,customerRemain,description) values 
    ('$takeLastId','$customerId','$date','خریدو فروش','1','$counterCurrency','$amount ','$counterAmount','$newDecreaseAmoun','$description')";
    $insertCustomerPaymentSaveQuery=$db ->query($insertCustomerPaymentSaveSql);
   
   
   echo "<script> window.close(); </script>";
}

?>