<?php
session_start();
include("pdate.php");
include("db.php");
$targetAddress="sell.php";	
$page_title = "فروش";
$pdate1 = pdate("Y-m-d");


	//select database name from file
$file_db = fopen("database_name.txt","r+");
$fname = fgets($file_db);
// sleect from database 
 $select_db = "select name from exchangecurrency1396.database_name order by id desc limit 1";
$selec_db_query = $db->query($select_db);
$selectdbNameRow = $selec_db_query->fetch_array();
 $db_name = $selectdbNameRow['name'];
  if($db_name==""){
	 $db_name="exchangecurrency1396";
 }



if($db_name !=$fname){
	$old = "old";
}else{
 $old ="";
}



			
?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" class="no-js">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
 
<title><?php echo $page_title;?></title>
<script>
   
function myconfirm()
{
    if(confirm('آیا اطلاعات را می خواهید به طور دائم پاک کنید؟'))
        return true;
    return false;
}
      
	   
  
	 </script>
	 <script>
  function bayerAmount(){
	    $('#buyerAmount').hide();
		$.post('retrivebuyeramount.php', {bCurrencyA:form.counterCurrency.value},
			function(output){
				$('#buyerAmount').html(output).fadeIn(10);
		})
	
	}	      
	   
   
      function get_amount(){
	    $('#rate').hide();
		$.post('retiverate.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;
		  
		  totalDollar=(dollarexactresult*1)*(dollarmainrate*1);
		  findTotalDollar=totalDollar.toFixed(2); 
		  
		  document.getElementById('totalDollar').value=FormatNumberBy3(findTotalDollar);
		 
		/*  totalDollar=(dollarRatePrice*1)*(amount*1);
         findTotalDollar=totalDollar.toFixed(2);	  
		 document.getElementById('totalDollar').value=FormatNumberBy3(findTotalDollar*1);
		 */
		
		}
		
	function  calculatePrice(){
	 var counterAmount = $("#counterAmount").val();
	 var baceAmount = $("#baceAmount").val();
	 
	 var decimalCharacter = ".",
          regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
          baceAmount=baceAmount=+baceAmount.match(regex).join("");
		  
		  regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
          counterAmount=counterAmount=+counterAmount.match(regex).join("");
		 
	 
	 var price=0;
	  price = (counterAmount*1)/(baceAmount*1);
	  price = price.toFixed(2);
	 
	 $("#rateOfCurrency").val(price);
}
		
			
		
		
</script>
	 
<!--=========================================================-->
     <script src="js/jquery/jquery-1.4.1.min.js" type="text/javascript"></script>
	 <script src="js/validation.js"></script>
     <script src="dist/sweetalert-dev.js"></script>
     <link rel="stylesheet" href="dist/sweetalert.css">
     <link rel="stylesheet" href="css/screen.css" type="text/css"   />
	 <script type="text/javascript" src="js/decimal.js"></script>
     <script type="text/javascript" src="js/NumberFormat.js"></script>
<!--=========================================================-->
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGIN STYLES -->
<link href="../../assets/global/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css"/>
<!-- END PAGE LEVEL PLUGIN STYLES -->
<!-- BEGIN PAGE LEVEL PLUGIN STYLES -->
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/select2/select2.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/datatables/extensions/Scroller/css/dataTables.scroller.min.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/datatables/extensions/ColReorder/css/dataTables.colReorder.min.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap-rtl.css"/>
<link href="../../assets/global/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css"/>
<!-- END PAGE LEVEL PLUGIN STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/select2/select2.css"/>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME STYLES -->
<link href="../../assets/global/css/components-md-rtl.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/css/plugins-md-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout/css/layout-rtl.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="../../assets/admin/layout/css/themes/darkblue-rtl.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout/css/custom-rtl.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body class="page-md page-header-fixed page-quick-sidebar-over-content">

<?php require_once('header.php');?>

<div class="clearfix">
</div>
<!-- BEGIN CONTAINER -->
<div class="page-container">
	<!-- BEGIN SIDEBAR -->
	<?php
	$menu_selected="treat";
	require_once('sidebar.php');?>
	<!-- END SIDEBAR -->
	<!-- BEGIN CONTENT -->
	<div class="page-content-wrapper">
		<div class="page-content">
			<!-- BEGIN PAGE CONTENT-->
			<!--BEGIN PAGE HEADER-->
			<div class="page-bar">
				<ul class="page-breadcrumb">
					<li>
						<i class="fa fa-home"></i>
						<a href="index.php">صفحه اصلی</a>
						<i class="fa fa-angle-left"></i>
					</li>
					<li>
						<a href="sell.php">فروش</a>
					</li>
					<li>
					 <?php if($old=="old"){ echo "<span style='color:red'>  شما وارید دوره قبلی شده اید و نمی توانید  اطلاعات ثبت کنید</span>";} ?>
					</li>
				</ul>
			</div>
			<!-- END PAGE HEADER-->
			<div class="row">
				<div class="col-md-12">
					<div class="portlet box blue" id="form_wizard_1">
						<div class="portlet-title">
							<div class="caption">
								<i class="fa fa-user"></i>فروش<span class="step-title"></span>
							</div>
							<div class="tools hidden-xs">
								<a href="javascript:;" class="collapse">
								</a>
							</div>
						</div>
						<div class="portlet-body form">
							<form action="registerSell.php" class="form-horizontal"  name="form" id="submit_form" method="POST">
								<div class="form-wizard">
									<div class="form-body">
										<div class="tab-content">
											 
											<div class="tab-pane active" id="tab1">
												<h3 class="block">فروش</h3>
												<div class="form-group">
													<label class="control-label col-md-2">تاریخ<span class="required">
													</span>
													</label>
													<div class="col-md-4">
													  <?php include("datepicker.php"); ?>
														<input type="hidden" name="target"   value="<?php echo $targetAddress;?>"/>
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<label class="control-label col-md-2">ارز مورد فروش<span class="required">
													</span>
													</label>
													<div class="col-md-4">
													<select name="counterCurrency" id="counterCurrency" style="width:300px" onClick="bayerAmount();dollarPrice();get_amount()" onChange="bayerAmount();dollarPrice();get_amount()">
													<option></option>
														<?php
															include("config/views/db_const.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>";	
															}
															echo "</select>";
														?>
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<label class="control-label col-md-2">موجودی ارز مورد فروش<span class="required">
													</span>
													</label>
													<div class="col-md-4">
														<div id='buyerAmount'><input type='text' placeholder="" class="filed"  ></div>
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<label class="control-label col-md-2">مقدار<span class="required">
													</span>
													</label>
													<div class="col-md-4">
														<input type="text" autocomplete="off" onkeyup="addSeparator(this);" onclick="calculatePrice();" onchange="calculatePrice()"  name="counterAmount" id="counterAmount"  placeholder="" class="filed"  onChange="calculateDollar();nazari();"  onclick="calculateDollar();nazari()"/>
														
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<label class="control-label col-md-2">ارز پایه<span class="required">
													</span>
													</label>
													<div class="col-md-4">
													<select name="basecurrency"  id='basecurrency' style="width:300px" onchange="findCash();calculate();get_amount()" onclick="calculate();findCash();get_amount()">
															<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>";
													   }
													echo "</select>";
													?>
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<label class="control-label col-md-2">موجودی ارز پایه<span class="required">
													</span>
													</label>
													<div class="col-md-4">
														<div id='cash'><input type="text" class='filed'></div>
														<span class="help-block">
														</span>
													</div>
												</div>
												
													<div class="form-group">
													<label class="control-label col-md-2">قیمت<span class="required">
													</span>
													</label>
													<div class="col-md-4">
													    
														<td><div id='rate'><input type="text" name="rateOfCurrency" id='rateOfCurrency' class='filed' ></div></td>
														<span class="help-block">
														</span>
													</div>
												</div>
												
												<div class="form-group">
													<label class="control-label col-md-2">ارزش به ارز پایه<span class="required">
													</span>
													</label>
													<div class="col-md-4">
														<input type='text' name='baceAmount' id="baceAmount"  onkeyup="calculatePrice()" onChange="calculatePrice();"  onClick="calculatePrice()" class='filed'   >
														<input type='hidden' name='buyAmount' id="buyAmount"   >
														<span class="help-block">
														</span>
													</div>
												</div>
												
											
												
												<div class="form-group">
													<!--<label class="control-label col-md-2">قیمت به دالر<span class="required">
													</span>
													</label>-->
													<div class="col-md-4">
													    
														<td><div id='dollarPrice'><input type="hidden"   class='filed' ></div></td>
														<span class="help-block">
														</span>
													</div>
												</div>
												<div class="form-group">
													<!--<label class="control-label col-md-2">ارزش به دالر<span class="required">
													</span>
													</label>-->
													<div class="col-md-4">
														<input type='hidden' name='totalDollar' id="totalDollar" class='filed'   >
														<span class="help-block">
														</span>
													</div>
												</div>
											</div>
										</div>
									</div>
									<div class="button_wrapper">
										<div class="row">
											<div class="col-md-offset-3 col-md-4">
												<input type="submit" id="submitbtn" value="&nbsp;&nbsp;ذخیره&nbsp;&nbsp;" <?php if($old=="old") echo "disabled"; ?> class="btn green button-submit" name="submit"/>
											</div>
										</div>
									</div>	
								</div>
							</form>
                            <!-- BEGIN PAGE CONTENT-->
							<div class="row">
								<div class="col-md-12">
									<!-- BEGIN EXAMPLE TABLE PORTLET-->
									<div class="table-wrapper">
										<hr class="horizontal-line" />
										<div class="portlet-body">
											<table class="table table-striped table-bordered table-hover" id="sample1">
											<thead>
											<tr>
											   <th class="table-number">
													شماره
												</th>
												<th>
													تاریخ
												</th>
												<th class="table-operation-header">
													ارز مورد معاوضه
												</th>
												<th class="table-operation-header">
													مقدار
												</th>
												<th class="table-operation-header">
													ارز پایه
												</th>
												<th class="table-operation-header">
													قیمت
												</th>
												<th class="table-operation-header">
													ارزش به ارز پایه
												</th>
												<th class="table-operation-header">
													ویرایش
												</th>
											</tr>
											</thead>
											<tbody >
                                             
                                               <?php
												     include("db.php");
												     $allSql="select * from transaction where treatment='2' and date='$pdate1' ";
													 $allQuery= $db ->query($allSql);
													 $ii=1;
													 while($allRow=$allQuery ->fetch_array()){
													       $date=$allRow['date'];
													       $counterCurrencyId=$allRow['counterCurrency'];
													       $counterAmount=$allRow['counterAmount'];
													       $rate=$allRow['rate'];
													       $baseCurrencyId=$allRow['baseCurrency'];
													       $baseAmount=$allRow['baseAmount'];
														   $editID=$allRow['id'];
														   
														   $table_name='transaction';
														   
														   //basecurrency
														   $basecurrencySQl="select name from currencies where id='$baseCurrencyId'";
														   $basecurrencyQuery= $db ->query($basecurrencySQl);
														   $basecurrencyRow=$basecurrencyQuery ->fetch_array();
														   $basecurrency=$basecurrencyRow['name'];

														   //countercurrency
														   $countercurrencySQl="select name from currencies where id='$counterCurrencyId'";
														   $countercurrencyQuery= $db ->query($countercurrencySQl);
														   $countercurrencyRow=$countercurrencyQuery ->fetch_array();
														   $countercurrency=$countercurrencyRow['name'];
														   
														    //=============finding Unit====================================
															  $unit_sql="select unit from crrencyrate where counterCurrency='$counterCurrencyId'";
															  $unit_query=$db ->query($unit_sql);
															  $unit_Row=$unit_query ->fetch_array();
															  $unit=$unit_Row['unit'];
															//=============end finding Unit====================================
															 
														   
													        echo "<tr>
															      <td>$ii</td> 
															      <td>$date</td> 
															      <td>$countercurrency</td> 
															      <td>".number_format($counterAmount,2)."</td> 
															      <td>$basecurrency</td> 
															      <td>".$rate*$unit."</td> 
															      <td>".number_format($baseAmount,2)."</td>";
																  echo" <td class='table-operation'><a  href='edit/edit_registerSell.php?editID=".$editID."  & table=".$table_name."'  ><img alt='Submit' src='img/edit.png'   class='dontPrint' title='ویرایش'></a> </td>";
															       
													    $ii++;    
													 }  
												?>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
                        </div>
					</div>
				</div>
			</div>
			<!-- END PAGE CONTENT-->
		</div>
	</div>
<!-- BEGIN FOOTER -->
<?php
	require_once('footer.php');

?>
<!-- END FOOTER -->
</div>
<?php
	if (isset($_GET['save'])) {
		echo "<script>alert('ولایت موفقانه در سیستم ذخیره شد.');</script>";
	}
?>
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="../../assets/global/plugins/respond.min.js"></script>
<script src="../../assets/global/plugins/excanvas.min.js"></script> 
<![endif]-->
<script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="../../assets/global/plugins/select2/select2.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/extensions/TableTools/js/dataTables.tableTools.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/extensions/Scroller/js/dataTables.scroller.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="../../assets/global/plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/jquery-validation/js/additional-methods.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="../../assets/global/plugins/select2/select2.min.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="../../assets/admin/layout/scripts/layout.js" type="text/javascript"></script>
<script src="../../assets/admin/layout/scripts/demo.js" type="text/javascript"></script>
<script src="../../assets/admin/pages/scripts/table-advanced.js"></script>
<script src="../../assets/admin/pages/scripts/form-wizard.js"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<script>
jQuery(document).ready(function() { 
    
    $('#totalUSD').hide(); $('#currency').hide();
    var b = $('#balance');
    b.blur(function(){
       if(b.val() != "0"){
            $('#totalUSD').show(); $('#currency').show();
       } 
    });
    
   // initiate layout and plugins
   Metronic.init(); // init metronic core components
   Layout.init(); // init current layout
   Demo.init(); // init demo features
   TableAdvanced.init();
   FormWizard.init(); 
});
</script>

<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
<?php
/* }
else{
	header("Location: login.php");
} */
?>