<?php 
$page_name ='sales_entry';  
session_start();

include ('../common/library.php');  
include ('../common/helper.php');  
include ('../template/header.php'); 
include ('../template/sidebar.php');

/*if($_REQUEST['clear']==1){
 $_SESSION['sale_no'] = '';
 header('location:sales_entry.php');
}*/

if(isset($_POST['cancel_sub'])){
	$_SESSION['sale_no'] = '';
	header('location:sales_entry.php');
}

if($_GET['s_no']>0){
$_SESSION['sale_no'] = $_GET['s_no'];
}

if(isset($_POST['sales_submit'])){
if($_SESSION['sale_no']>0){

$journal_del = $conn->query('delete from journal where tr_no="'.$_SESSION['sale_no'].'" and tr_from="Sales"');
$receipt_del = $conn->query('delete from journal where tr_no="'.$_SESSION['sale_no'].'" and tr_from="Receipt"');
$discount_del = $conn->query('delete from journal where tr_no="'.$_SESSION['sale_no'].'" and tr_from="Discount"');

$journal_item_del = $conn->query('delete from journal_item where tr_no="'.$_SESSION['sale_no'].'" and tr_from="Sales"');
}

if($_POST['customer_type']=="Registered"){
$jv_date = $_POST['r_sales_date'];
}else{
$jv_date = $_POST['c_sales_date'];
}



$upd="update sales_master set sales_date='".$jv_date."', discount='".$_POST['discount']."', total_amt='".$_POST['total_amt']."', collection='".$_POST['collection']."'
 , dues='".$_POST['due']."', changes='".$_POST['change']."', actual_receipt='".$_POST['actual_receipt']."', payment_type='".$_POST['payment_type']."', details='".$_POST['details']."'
where s_no='".$_SESSION['sale_no']."' ";
$conn->query($upd);


$ssql2 = "select sum(d.amount) as total_amount,m.s_no,m.sales_date,m.MsgStatus,c.ledger_id,c.business_name,c.mobile_no from sales_master m,sales_order d,customer_info c where m.s_no=d.s_no and m.group_for='".$_SESSION['group_for']."' and m.dealer_code=c.id and m.s_no='".$_SESSION['sale_no']."'";

$sql = $conn->query($ssql2);
$j_data = $sql->fetch_assoc();


$max_jv = find_a_field('journal','max(jv_no)+1','1');

$tr_from = 'Sales';
$cr_ledger = 1000002;
$status = 'Unpaid';

$entry_by = $_SESSION['user_id'];
if($max_jv==''){
$max_jv = date('Ymd');
}

//journal($max_jv,$jv_date,$ledger_id,$dr_amt,$cr_amt,$tr_from,$tr_no,$status='')

journal($max_jv,$jv_date,$j_data['ledger_id'],$j_data['total_amount'],0,$tr_from,$_SESSION['sale_no'],$status);

journal($max_jv,$jv_date,$cr_ledger,0,$j_data['total_amount'],$tr_from,$_SESSION['sale_no'],$status);

if($_POST['discount']>0){
	$dr_ledger = 1000004;
	$cr_ledger = $j_data['ledger_id'];

	$tr_from = 'Discount';
	$status = 'Paid';

	journal($max_jv,$jv_date,$dr_ledger,$_POST['discount'],0,$tr_from,$_SESSION['sale_no'],$status);

	journal($max_jv,$jv_date,$cr_ledger,0,$_POST['discount'],$tr_from,$_SESSION['sale_no'],$status);

}

//journa end
// payment journal actual_receipt
if($_POST['actual_receipt']){

	if($_POST['payment_type'] !=''){
		$dr_ledger = $_POST['payment_type'];
	}else{
		$dr_ledger = 1000002;
	}

$status = 'Paid';
$tr_from = 'Receipt';

$max_jv = find_a_field('journal','max(jv_no)','1');
if($max_jv=='' || $max_jv==0){
$max_jv = date('Ymd');
}else{
    $max_jv = $max_jv+1;
}

journal($max_jv,$jv_date,$dr_ledger,$_POST['actual_receipt'],0,$tr_from,$_SESSION['sale_no'],$status);

journal($max_jv,$jv_date,$j_data['ledger_id'],0,$_POST['actual_receipt'],$tr_from,$_SESSION['sale_no'],$status);


//journa end
}
$select = $conn->query("select * from sales_order where group_for = '".$_SESSION['group_for']."' and s_no='".$_SESSION['sale_no']."'");
 while( $item_data = $select->fetch_assoc()){

$journal_item = $conn->query("INSERT INTO `journal_item`(`journal_date`, `item_id`, `rate`, `item_ex`, `tr_no`, `tr_from`,`entry_by`,`warehouse`) VALUES ('".$item_data['s_date']."','".$item_data['item_id']."','".$item_data['rate']."','".$item_data['qty']."','".$item_data['s_no']."','Sales','".$_SESSION['user_id']."' ,'".$_SESSION['warehouse']."')");
}


//Text Sms
function sms_send($recipients,$massage) {
    $url = "http://bulksmsbd.net/api/smsapimany";
    $api_key = "nJbYuQLCmipRo4zdSoxo";
    $senderid = "8809601004489";
    $messages = json_encode( [
        [
            "to" => $recipients,
            "message" => $massage
        ]
    ]);
    $data = [
        "api_key" => $api_key,
        "senderid" => $senderid,
        "messages" => $messages
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    //return $response;
}

$recipients ="88".$j_data['mobile_no']."";
$massage  = "Dear ".$j_data['business_name'].",\r\n";
$massage .= "Invoice No: APSCBD-".$j_data['s_no']." Date: ".$j_data['sales_date']." \r\n";
$massage .= "Invoice Item: \r\n";
$items = $conn->query("select i.item_name , d.qty from item_info i, sales_order d where i.item_id=d.item_id and s_no =".$j_data['s_no']." ");

while( $it_data = $items->fetch_assoc()){
$massage .= "".$it_data['item_name'].",(".$it_data['qty']." P) \r\n";
}

$massage .= "Total Amount : ".$j_data['total_amount']." Taka \r\n";
$massage .= "Due Balance: ".find_a_field('journal','sum(dr_amt-cr_amt)','ledger_id='.$j_data['ledger_id'])." Taka \r\n";
$massage .= "Thank You, \r\n";
$massage .= "Busicus \r\n";
$massage .= "Mobile: +8801620615052 \r\n";
$massage .= "Web: busicus.com \r\n";

if($j_data['MsgStatus']>0){ }else{
	echo sms_send($recipients,$massage);
}



$upd="update sales_master set MsgStatus='1' where s_no='".$_SESSION['sale_no']."' ";
$conn->query($upd);

//Text Sms
 $msg .= '<span style="color:green; font-weight:bold; font-size:18px;">Sales Entry Successful</span>';
 $_SESSION['sale_no'] = '';
 echo '<script>window.location.replace("sale_entry.php?clear=1")</script>'; 
}else{
  //$msg = '<span style="color:red; font-weight:bold; font-size:18px;">No data found!</span>';
}





if(isset($_POST['update'])){
  $dealer_type = $_POST['customer_type'];
  $dealer = $_POST['dealer'];
  $dealer_name = $_POST['dealer_name'];
  $sales_date = $_POST['sales_date'];
  $address = $_POST['address'];
  $contact = $_POST['contact'];


  if($_SESSION['sale_no']>0){
  $update = $conn->query("update sales_master set sales_date='".$sales_date."',dealer_type='".$dealer_type."',dealer_code='".$dealer."',dealer_name='".$dealer_name."',dealer_address='".$address."',contact='".$contact."' where s_no='".$_SESSION['sale_no']."'");
  }

  if($update==true){
 /* echo '<script>window.location.href = "customer_setup.php";</script>';*/
  $msg =  '<span style="color:green; font-weight:bold; font-size:18px;">Successfully Updated. Sales No. - '.$_SESSION['sale_no'].'</span>';
  echo '<script>window.location.replace("sale_entry.php?clear=1")</script>'; 
  }else{
  $msg =  '<span style="color:red; font-weight:bold; font-size:18px;">Plesae Try Again!</span>';
 }
}
 "select * from sales_master where s_no='".$_SESSION['sale_no']."'";
$select = $conn->query("select * from sales_master where s_no='".$_SESSION['sale_no']."'");
$data = $select->fetch_assoc();



 if(isset($_POST['sales_delete'])){
  $del = $conn->query("delete from sales_master where s_no=".$_SESSION['sale_no']."");
  $del2 = $conn->query("delete from sales_order where s_no=".$_SESSION['sale_no']."");
  $del3 = $conn->query("delete from journal where tr_from like 'Sales' and tr_no=".$_SESSION['sale_no']."");
  $del4 = $conn->query("delete from journal_item where tr_from like 'Sales' and tr_no=".$_SESSION['sale_no']."");

  $_SESSION['sale_no'] = ''; 
  //header('location:sale_entry.php');
  echo '<script>window.location.replace("sale_entry.php?clear=1")</script>'; 
 }



 /////////////////////////  Item Input  /////////////////////////
 if(isset($_POST['item_save'])){

	$item_name = $_POST['item_name'];
	$uom = $_POST['uom'];
	$item_group =  $_POST['item_group'];
	$status = $_POST['status'];
	$brand = $_POST['brand'];
	$model = $_POST['model'];
	$item_code = $_POST['item_code'];
	$retail_price = $_POST['retail_price'];
	$regular_price = $_POST['regular_price'];
	$group_for = 1;
	$status = 'Active';
	$entry_by = $_SESSION['user_id'];
	$opening_date=date("Y-m-d");
    print_r($_POST);
  $max = $conn->query("select max(item_id) as item_code from item_info where 1");
  $c_data = $max->fetch_assoc();
  if($c_data['item_code'] != ''){
	  $max_item_id = $c_data['item_code']+1;
  }else{
	  $max_item_id = 5001;
  }
  
  $insert ="insert into item_info(item_id,item_code,`item_name`,`uom`,`item_group`,brand, model,`status`,`entry_by`,`group_for`,`retail_price`,`regular_price` ) 
	 Values('".$max_item_id."','".$item_code."','".$item_name."','".$uom."','".$item_group."','".$brand."', '".$model."','".$status."','".$entry_by."','".$group_for."','".$retail_price."','".$regular_price."')";
	$ins = $conn->query($insert);

  if($_POST['item_stocks'] > 0 && $ins==true){
	$sqll = "INSERT INTO `journal_item` (`journal_date`, `warehouse`, `item_id`, `rate`, `item_in`, `item_ex`, `tr_no`, `tr_from`, `entry_at`, `entry_by`) 
	VALUES ('".date('Y-m-d')."', '".$_SESSION['warehouse']."', '".$max_item_id."', '".$_POST['regular_price']."', '".$_POST['item_stocks']."', '0.00', '0', 'Opening', current_timestamp(), '".$_SESSION['user_id']."')";
	
	$insert_journal=$conn->query($sqll);
  }
	if($ins==true){
	$insert_id = mysqli_insert_id($conn);
  
  //Item photo end
	$msg =  '<span style="color:green; font-weight:bold; font-size:18px;">New Item Successfully Inserted.</span>';
	echo '<script>window.location.replace("sale_entry.php")</script>'; 
	} else{
	$msg =  '<span style="color:red; font-weight:bold; font-size:18px;">Plesae Try Again!</span>';
   }
  
  }
?>

<style>
	.loader {
		border: 10px solid #f3f3f3;
		border-radius: 50%;
		border-top: 10px solid blue;
		border-right: 10px solid green;
		border-bottom: 10px solid red;
		width: 40px;
		height: 40px;
		-webkit-animation: spin 2s linear infinite;
		animation: spin 2s linear infinite;
	}

	@-webkit-keyframes spin {
		0% {
			-webkit-transform: rotate(0deg);
		}

		100% {
			-webkit-transform: rotate(360deg);
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="main-panel">
	<div class="content">
		<div class="row">
			<div class="col-md-9">
			<div class="container">
				<div class="card">
					<div class="card-header">
						<div class="d-flex align-items-center">
							<h4 class="card-title">Sales Entry. <?php echo $msg ;?></h4>
						</div>
						<button class="btn btn-primary btn-round btn-sm ml-auto " style="float: right;"
							data-toggle="modal" data-target="#addRowModal">
							<i class="fa fa-plus"></i>Add Item
						</button>
					</div>



					<div class="card-body">
						<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
							<a href="#" class="close" data-dismiss="alert" aria-label="close">×x</a>

						</div>

						<form method="post" id="sales" autocomplete="off">
							<div class="row">
								<div class="col-12">
									<div class="form-group row">
										<div class="col-sm-2">
											<div class="loader" id="load" title="Internet maybe slow"
												style="margin-left:44%; display:none;"></div>
										</div>
										<label class="col-sm-2 col-form-label">Customer Type</label>
										<div class="col-sm-6">
											<select name="customer_type" class="form-control form-control" id="customer"
												onchange="ctype()">
												<option></option>
												<option <?php echo ($data['dealer_type']=="Registered")? 'selected':''?>
													value="Registered">Registered</option>
												<option <?php echo($data['dealer_type']=="Corporate")? 'selected':''?>
													value="Corporate">Walk-In</option>
											</select>
										</div>
									</div>
								</div>
							</div>



							<!-- Registered Customer Start-->
							<div class="row" id="rc" style="display:none;">
								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label"> Party:</label>
										<div class="col-sm-10">
											<input name="r_dealer_id" class="form-control form-control" id="r_dealer_id"
												onchange="party()" list="party"
												value="<?php if($data['dealer_name']!='') echo $data['dealer_name'].'#'.$data['dealer_code'];?>" />

											<datalist id="party">
												<?php $d_s = $conn->query("select * from customer_info where group_for = '".$_SESSION['group_for']."' and status='Active' and customer_type='Registered'");
                                                           while($dealer = $d_s->fetch_assoc()){
														   ?>
												<option
													<?php echo ($data['dealer_code']==$r_dealer['id'])? 'selected':''?>
													value="<?php echo $dealer['business_name']."#".$dealer['id'];?>">
													<?php echo $dealer['business_name']."-".$dealer['customer_address'];?>
												</option>
												<?php } ?>
											</datalist>
										</div>
									</div>
								</div>

								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Date:</label>
										<div class="col-sm-10">
											<input type="date" name="r_sales_date" class="form-control form-control-sm"
												id="r_sales_date"
												value="<?php if($data['sales_date'] !='') echo $data['sales_date']; else echo date('Y-m-d');?>"
												required>
										</div>
									</div>
								</div>

								<div class="col-12">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Address:</label>
										<div class="col-sm-10">
											<input type="text" name="r_address" class="form-control form-control-sm"
												id="r_address"
												value="<?php echo find_a_field('customer_info','customer_address','id="'.$data['dealer_code'].'"');?>"
												readonly>
										</div>
									</div>
								</div>


								<div class="col-12">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Item:</label>
										<div class="col-sm-10">
											<input name="item_id" list="ids" class="form-control form-control"
												id="item_id">
											<datalist id="ids">
												<option></option>
												<?php $itm = $conn->query("select * from item_info where group_for = '".$_SESSION['group_for']."' and status='Active'");
                                                           while($item = $itm->fetch_assoc()){
														   ?>
												<option <?php echo ($data['item_id']==$item['item_id'])? 'selected':''?>
													value="<?php echo $item['item_id']?>">
													<?php echo $item['item_code']?> #> <?php echo $item['item_name']?></option>
												<?php } ?>
											</datalist>
										</div>
									</div>
								</div>
							</div>

							<!--  Registered Customer End-->
							<!--  Corporate Customer Start-->

							<div class="row" id="cc" style="display:none;">
								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Party :</label>
										<div class="col-sm-10">
											<input type="text" name="c_dealer_name" list="partylist"
												class="form-control custom-select custom-select-sm" id="c_dealer_name"
												value="<?php if($data['dealer_name']!='') echo $data['dealer_name'].'<#>'.$data['dealer_address'];?>"
												onchange="c_party()">
											<datalist id="partylist">
												<?php 
																	  $s = $conn->query("select * from customer_info where group_for = '".$_SESSION['group_for']."' and customer_type='Corporate'");
																	  while($dealer = $s->fetch_assoc()){
																	 ?>
												<option
													value="<?php echo $dealer['business_name'].'<#>'.$dealer['customer_address'];?>">
													<?php } ?>
											</datalist>
										</div>
									</div>
								</div>


								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Date:</label>
										<div class="col-sm-10">
											<input type="date" name="c_sales_date" class="form-control form-control-sm"
												id="c_sales_date"
												value="<?php if($data['sales_date'] !='') echo $data['sales_date']; else echo date('Y-m-d');?>">
										</div>
									</div>
								</div>

								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Address:</label>
										<div class="col-sm-10">
											<input type="text" name="c_address" class="form-control form-control-sm"
												id="c_address" value="<?php echo $data['dealer_address']?>">
										</div>
									</div>
								</div>
								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Phone:</label>
										<div class="col-sm-10">
											<input type="text" name="c_contact" class="form-control form-control-sm"
												id="c_contact" value="<?php echo $data['contact']?>" >
										</div>
									</div>
								</div>

								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Item:</label>
										<div class="col-sm-10">
											<input name="c_item_id" list="itemIds" class="form-control form-control"
												id="c_item_id">
											<datalist id="itemIds">
												<option></option>
												<?php $itm = $conn->query("select * from item_info where group_for = '".$_SESSION['group_for']."' and status='Active'");
                                                           while($item = $itm->fetch_assoc()){
														   ?>
												<option <?php echo ($data['item_id']==$item['item_id'])? 'selected':''?>
													value="<?php echo $item['item_id']?>">
													<?php echo $item['item_name']?></option>
												<?php } ?>
											</datalist>
										</div>
									</div>
								</div>
							</div>
							<!--  Corporate Customer End-->
							<!--
										 <input type="submit" name="update" value="Update" id="btnSaveAction" class="btn btn-warning">
										 <input type="submit" name="add" value="Add" id="btnSaveAction" class="btn btn-success">-->
					</div>
				</div>

				<div class="card">
					<div class="card-body">
						<table class="text-center" style="width:100%">
							<thead>
								<th width="25%">Item Description</th>
								<th >Problem</th>
								<th>Warranty</th>
								<th>IMEI No</th>
								<th>Stock</th>
								<th >Unit</th>
								<th >Rate</th>
								<th >Qty</th>
								<th>Amount</th>
								<th>Action </th>
							</thead>

							<tbody>
							<tbody id="show">
								<?php
										 $select = $conn->query("select * from sales_order where s_no='".$_SESSION['sale_no']."' ");
                                         while( $item_data = $select->fetch_assoc()){
										$brand = find_a_field('item_info','brand','item_id="'.$item_data['item_id'].'"');	
										 $unit = find_a_field('item_info','uom','item_id="'.$item_data['item_id'].'"');
										 $dealer_id = find_a_field('sales_master','dealer_code','s_no="'.$_SESSION['sale_no'].'"');
                                         $dealer_name = find_a_field('customer_info','business_name','id="'.$dealer_id.'"');
										 $customer_address = find_a_field('customer_info','customer_address','id="'.$dealer_id.'"');
										?>
								<tr>


									<td><input type="hidden" name="cdealername" id="cdealername"
											value="<?php if($dealer_name!='') echo $dealer_name.'<#>'.$customer_address;?>" /><select
											name="item_name_<?php echo $item_data['id'];?>"
											class="form-control form-control"
											id="item_name_<?php echo $item_data['id'];?>"
											onchange="edit(<?php echo $item_data['id'];?>)">

											<option></option>
									<?php $itm = $conn->query("select * from item_info where group_for = '".$_SESSION['group_for']."' and status='Active'");

                                           while($item = $itm->fetch_assoc()){
					               ?>
											<option
												<?php echo ($item_data['item_id']==$item['item_id'])? 'selected':''?>
												value="<?php echo $item['item_id']?>"><?php echo $item['item_name']?>
											</option>

											<?php } ?>

										</select><input type="hidden" name="update_id_<?php echo $item_data['id'];?>"
											id="update_id_<?php echo $item_data['id'];?>"
											onkeyup="edit(<?php echo $item_data['id'];?>)"
											value="<?php echo $item_data['id'];?>" /></td>

											<td><input type="text" name="co_party_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="co_party_<?php echo $item_data['id'];?>"
											value="<?php if($item_data['co_party']!='') echo $item_data['co_party']; else  echo $co_party;?>"
											></td>

											<td>
												<select name="warranty_<?php echo $item_data['id'];?>" id="warranty_<?php echo $item_data['id'];?>" class="form-control" onblur="edit(<?php echo $item_data['id'];?>);cal(<?php echo $item_data['id'];?>);">
													<option value="">Select</option>
													<option <?php if($item_data['warranty']=='1 Month') echo 'selected';?> value="1 Month">1 Month</option>
													<option <?php if($item_data['warranty']=='3 Month') echo 'selected';?> value="3 Month">3 Month</option>
													<option <?php if($item_data['warranty']=='6 Month') echo 'selected';?> value="6 Month">6 Month</option>
													<option <?php if($item_data['warranty']=='12 Month') echo 'selected';?> value="12 Month">12 Month</option>
													<option <?php if($item_data['warranty']=='24 Month') echo 'selected';?> value="24 Month">24 Month</option>
													<option <?php if($item_data['warranty']=='36 Month') echo 'selected';?> value="36 Month">36 Month</option>
												</select>
											</td>

											<td><input type="text" name="model_no_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="model_no_<?php echo $item_data['id'];?>"
											value="<?php if($item_data['model_no']!='') echo $item_data['model_no']; else  echo $model_no;?>"
											 onblur="edit(<?php echo $item_data['id'];?>);cal(<?php echo $item_data['id'];?>);"></td>

									<td><input type="text" name="stock_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="stock_<?php echo $item_data['id'];?>"
											value="<?php echo find_a_field('journal_item','sum(item_in-item_ex)','item_id="'.$item_data['item_id'].'"')?>"
											readonly></td>

									<td><input type="text" name="unit_<?php echo $item_data['id'];?>"
											list="new_unit_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="unit_<?php echo $item_data['id'];?>"
											value="<?php if($item_data['unit']!='') echo $item_data['unit']; else  echo $unit;?>"
											required>
									</td>
									<td><input type="text" name="rate_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="rate_<?php echo $item_data['id'];?>"
											cal(<?php echo $item_data['id'];?>);
											value="<?php echo $item_data['rate'];?>" required></td>
									<td><input type="text" name="qty_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="qty_<?php echo $item_data['id'];?>"
											onblur="edit(<?php echo $item_data['id'];?>);cal(<?php echo $item_data['id'];?>);"
											value="<?php echo $item_data['qty'];?>" required></td>
									<td><input type="text" name="amount_<?php echo $item_data['id'];?>"
											class="form-control form-control" id="amount_<?php echo $item_data['id'];?>"
											value="<?php echo $item_data['amount'];?>" required></td>
									<td><button onclick="deleteData(<?php echo $item_data['id'];?>)"
											id="del_<?php echo $item_data['id'];?>" class="btn btn-danger">X</button>
									</td>
									<td>
										<div class="loader" id="updateload_<?php echo $item_data['id'];?>"
											align="center" title="Internet maybe slow" style="display:none;"></div>
										<!--<input type="button" name="edit_<?php echo $item_data['id'];?>" class="btn btn-primary" value="Edit" id="edit_<?php echo $item_data['id'];?>">-->
									</td>
								</tr>
								<?php } ?>
							</tbody>
						</table>
					</div>
				</div>

				
				<div class="card-footer text-center">
					<input type="submit" name="sales_submit" class="btn btn-secondary">
					<?php if($_SESSION['sale_no']>0){?>
					<input type="submit" name="sales_delete" value="Delete" class="btn btn-warning">
					<input type="submit" name="cancel_sub" value="Cancel" class="btn btn-secondary">
					<?php } ?>
				</div>
				
			</div>



			


			<table cellpadding="10" cellspacing="1" width="12%" style="float:left;">
				<tbody id="ajax-response">
				</tbody>
			</table>

			

			

			<?php if($_SESSION['sale_no']==''){?>
			<table id="add-row" class="display table table-striped table-hover">
				<thead>
					<tr>
						<th>SL No</th>
						<th>Sales No</th>
						<th>Sales Date</th>
						<th>Party Name</th>
						<th>Item Desc</th>
						<th>Problem</th>
						<th>Qty</th>
						<th>Sales Amount</th>
						<th style="width: 10%">Action</th>
						<th>Print</th>
					</tr>
				</thead>

				<tbody>
					<?php
						$sql = "select s.*,c.business_name,c.customer_type,c.customer_address, i.item_name , sum(d.qty) as qty
						from sales_master s, customer_info c, item_info i ,sales_order d
						where i.item_id=d.item_id and c.id=s.dealer_code and s.s_no = d.s_no 
						group by s.s_no , s.sales_date 
						order by s.s_no desc";


							$select =$conn->query($sql); $i=1;

						while($c_data = $select->fetch_assoc()){

					?>

					<tr>
						<td><?php echo $i++;?></td>
						<td><a href="sales_print_view.php?sale_no=<?php echo $c_data['s_no']  ?>" target="_blank"><?php echo $c_data['s_no']?></a></td>
						<td><?php echo $c_data['sales_date']?></td>
						<td><?php echo $c_data['business_name']?></td>
						<td><?php echo $c_data['item_name']?></td>
						<td><?php echo $c_data['co_party']?></td>
						<td><?php echo $c_data['qty']?></td>
						<td><?php echo find_a_field('sales_order','sum(amount)','s_no='.$c_data['s_no']);?></td>

						<td><a href="?s_no=<?php echo $c_data['s_no']?>"><i class="fa fa-edit"></i></a></td>
						<td><a href="invoice.php?sale_no=<?php echo $c_data['s_no']  ?>" target="_blank" class="btn btn-primary">Customer Copy</a>
						<a href="invoice2.php?sale_no=<?php echo $c_data['s_no']  ?>" target="_blank" class="btn btn-warning">Office Copy</a>
					</td>

					</tr>

					<?php } ?>

				</tbody>

				<tfoot>



				</tfoot>

			</table>
					

			<?php } ?>
			</div>
			<div class="col-md-3">
				<div class="container">
					<div class="card">
						<div class="card-header">
							<div class="d-flex align-items-center">
								<h4 class="card-title">Receipt Entry. <?php echo $msg ;?></h4>
							</div>
						</div>

						<div class="card-body">

						
							<div class="row">
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Discount </label>
										<input type="text" onkeyup="paycal()" name="discount" id="discounts" class="form-control" value="" />
									</div>
								</div>

								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Total Amount </label>
										<input type="text" name="total_amt" id="total_amt" class="form-control" 
										value="<?=find_a_field('sales_order','sum(amount)','s_no="'.$_SESSION['sale_no'].'" ');?>" >
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Cash Received </label>
										<input type="text" onkeyup="paycal()" name="collection" id="collections" class="form-control" value="" >
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Due Amount</label>
										<input type="text"   readonly name="due" id="dues" class="form-control" value="" >
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Change/Refund Amount </label>
										<input type="text" name="change" readonly id="change" class="form-control" value="" >
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Actual receipt </label>
										<input type="text" name="actual_receipt" readonly id="actual_receipt" class="form-control" value="" >
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Payment Method </label>
										<select name="payment_type" id="payment_type" class="form-control">
												
												<option value="1000002">Cash</option>
												<option value="1000008">Bank</option>
												<option value="1000009">Commision</option>
										</select>
									</div>
								</div>
								<div class="col-sm-12">
									<div class="form-group form-group-default">
										<label>Remarks/Note </label>
										<textarea type="text" name="details" id="details" class="form-control" ></textarea>
									</div>
								</div>
							</div>
						</form>			

						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>


<!-- add item modal -->

			<form action="" method="post" enctype="multipart/form-data">	
				<div class="modal fade" id="addRowModal" tabindex="-1" role="dialog" aria-hidden="true">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<div class="modal-header no-bd">
								<h5 class="modal-title">
									<span class="fw-mediumbold">Item</span>
									<span class="fw-light">Information</span>
								</h5>
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
							</div>
							<div class="modal-body">
								<p class="small">Make Sure Fillup All Field</p>
								<div class="row">
									<div class="col-sm-12">
										<div class="form-group form-group-default">
											<label>Item ID <span style="color:#FF0000; font-size:15px;">*</span></label>
											<input type="text" name="item_id" id="item_id" class="form-control"
												value="<?=$max_item_id?>" readonly="readonly" required>
										</div>
									</div>

									<div class="col-sm-12">
										<div class="form-group form-group-default">
											<label>Item Name <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<input type="text" name="item_name" id="item_name" class="form-control"
												placeholder="Item Name" required>
										</div>
									</div>



									<div class="col-md-6 pr-0">
										<div class="form-group form-group-default">
											<label>Item Brand <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<input name="brand" id="brand" class="form-control" list="item_brand" />
											<datalist id="item_brand">
												<? foreign_relation('item_info','brand','brand',$brand,' 1 group by brand');?>
											</datalist>
										</div>
									</div>

									<div class="col-md-6 pr-0">
										<div class="form-group form-group-default">
											<label>Item Model <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<input name="model" id="model" class="form-control" list="item_model" />
											<datalist id="item_model">
												<? foreign_relation('item_info','model','model',$model,' 1 group by model');?>
											</datalist>
										</div>
									</div>

									<div class="col-sm-6">
										<div class="form-group form-group-default">
											<label>UOM <span style="color:#FF0000; font-size:15px;">*</span></label>
											<input type="text" name="uom" id="uom" class="form-control"
												placeholder="Unit">
										</div>
									</div>

									<div class="col-sm-6">
										<div class="form-group form-group-default">
											<label>Retail price <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<input type="text" name="retail_price" id="retail_price"
												class="form-control" placeholder="Retail price">
										</div>
									</div>
									<div class="col-sm-6">
										<div class="form-group form-group-default">
											<label>Regular Price <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<input type="text" name="regular_price" id="regular_price"
												class="form-control" placeholder="Regular Price">
										</div>
									</div>

									<div class="col-md-6 pr-0">
										<div class="form-group form-group-default">
											<label>Item Type <span
													style="color:#FF0000; font-size:15px;">*</span></label>
											<select name="item_group" id="item_group" class="form-control">
												<option value="Local">Local</option>
												<option value="Imported">Imported</option>
											</select>
										</div>
									</div>

									<div class="col-md-6">
										<div class="form-group form-group-default">
											<label>Item Stock</label>
											<input name="item_stocks" id="item_stock" type="text" class="form-control">
										</div>
									</div>
								</div>
							</div>
							<div class="modal-footer no-bd">
								<input type="submit" name="item_save" value="Add" class="btn btn-primary" />
								<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
							</div>
						</div>
					</div>
				</div>
			</form>

<script>
	function ctype() {
		var type = document.getElementById('customer').value;

		if (type == 'Registered') {
			document.getElementById('rc').style.display = "";
			document.getElementById('cc').style.display = "none";

		} else if (type == 'Corporate') {
			document.getElementById('cc').style.display = "";

			document.getElementById('rc').style.display = "none";
		}

	}
	window.onload = ctype;
</script>


<script>
	$(document).ready(function () {
		$("#item_id").change(function () {
			$("#item_id").attr("disabled", "disabled");
			$("#load").attr("style", "display:");
			var item_id = $('#item_id').val();
			var customer_type = $('#customer').val();
			var dealer_name = $('#c_dealer_name').val();
			var c_sales_date = $('#c_sales_date').val();
			var address = $('#c_address').val();
			var contact = $('#c_contact').val();
			var r_dealer = $('#r_dealer_id').val();
			var r_sales_date = $('#r_sales_date').val();


			if (item_id != "") {
				if (r_sales_date != "" || c_sales_date != "") {
					$.ajax({
						url: "sales_ajax.php",
						type: "POST",

						data: {
							item_id: item_id,
							customer_type: customer_type,
							dealer_name: dealer_name,
							c_sales_date: c_sales_date,
							address: address,
							contact: contact,
							r_dealer: r_dealer,
							r_sales_date: r_sales_date

						},
						cache: false,
						success: function (dataResult) {
							var dataResult = JSON.parse(dataResult);
							if (dataResult.statusCode == 200) {
								$("#save").removeAttr("disabled");
								$('#sales').find('input:text').val('');
								$("#success").show();
								$('#success').html(dataResult.row +
									' Item added successfully !');
								$('#show').load('sales_view_ajax.php');

								$("#item_id").removeAttr("disabled");
								$("#load").attr("style", "display:none");
								location.reload();
								party();

							} else if (dataResult.statusCode == 201) {
								alert("Error occured !");
							}
						}
					});
				} else {
					alert('Please fill Date field properly !');
				}

			} else {
				alert('Please fill all the field !');
			}
		});
	});



	$(document).ready(function () {
		$("#c_item_id").change(function () {
			$("#c_item_id").attr("disabled", "disabled");
			$("#load").attr("style", "display:");
			var item_id = $('#c_item_id').val();
			var customer_type = $('#customer').val();
			var dealer_name = $('#c_dealer_name').val();
			var c_sales_date = $('#c_sales_date').val();
			var address = $('#c_address').val();
			var contact = $('#c_contact').val();
			var r_dealer = $('#r_dealer_id').val();
			var r_sales_date = $('#r_sales_date').val();

			if (item_id != "") {
				$.ajax({
					url: "sales_ajax.php",
					type: "POST",
					data: {
						item_id: item_id,
						customer_type: customer_type,
						dealer_name: dealer_name,
						c_sales_date: c_sales_date,
						address: address,
						contact: contact,
						r_dealer: r_dealer,
						r_sales_date: r_sales_date
					},
					cache: false,
					success: function (dataResult) {
						var dataResult = JSON.parse(dataResult);
						if (dataResult.statusCode == 200) {
							$("#save").removeAttr("disabled");
							$('#sales').find('input:text').val('');
							$("#success").show();
							$('#success').html(dataResult.row + ' Item added successfully !');
							$('#success').html(dataResult.msg);
							$('#show').load('sales_view_ajax.php');
							$("#c_item_id").removeAttr("disabled");
							$("#load").attr("style", "display:none");
							//$("#c_dealer_name").attr("value",dataResult.pawri);
							document.getElementById("c_dealer_name").value = dataResult.pawri;
							c_party();
							location.reload();
						} else if (dataResult.statusCode == 201) {
							alert("Error occured !");
						}
					}
				});

			} else {
				alert('Please fill all the field !');
			}
		});

	});

	$("#item_id").change(function () {
		$('#show').load('sales_view_ajax.php');

		$("#r_address").attr("value", "address");

		party();
	});

	$("#c_item_id").change(function () {

		$('#show').load('sales_view_ajax.php');
		document.getElementById("c_dealer_name").value = document.getElementById("cdealername").value;
		c_party();
	});

	function edit(id) {
		$(document).ready(function () {
			//$('#edit').on('click', function(){

			$("#edit_" + id).attr("value", "W...");
			$("#del_" + id).attr("disabled", "disabled");
			$("#updateload_" + id).attr("style", "display:");
			var item_id = $('#item_name_' + id).val();
			var unit_name = $('#unit_' + id).val();
			var rate = $('#rate_' + id).val();
			var qty = $('#qty_' + id).val();
			var amount = $('#amount_' + id).val();
			var update_id = $('#update_id_' + id).val();
			var co_party = $('#co_party_' + id).val();
			var warranty = $('#warranty_' + id).val();
			var model_no = $('#model_no_' + id).val();

			if (item_id != "") {
				$.ajax({
					url: "sales_edit_ajax.php",
					type: "POST",
					data: {
						item_id: item_id,
						unit_name: unit_name,
						rate: rate,
						qty: qty,
						amount: amount,
						update_id: update_id,
						co_party: co_party,
						warranty: warranty,
						model_no: model_no
					},
					cache: false,
					success: function (dataResult) {
						var dataResult = JSON.parse(dataResult);
						if (dataResult.statusCode == 200) {
							$("#save").removeAttr("disabled");
							$('#sales').find('input:text').val('');
							$("#success").show();
							$('#success').html(' Item Update successfully !');
							$("#edit_" + id).attr("value", "Updated");
							$("#del_" + id).removeAttr("disabled");
							$("#updateload_" + id).attr("style", "display:none");
							document.getElementById("c_dealer_name").value = $('#cdealername').val();
							//party();
							//c_party();
							location.reload();

						} else if (dataResult.statusCode == 201) {
							alert("Error occured !");
						}
					}
				});
			} else {
				alert('Please fill all the field !');
			}
		});
	}

	function deleteData(str) {
		var id = str;
		$("#updateload_" + id).attr("style", "display:");
		$.ajax({
			type: "GET",
			url: "delete_ajax.php?p=del",
			data: "id=" + id,
			success: function (dataResult) {

				var dataResult = JSON.parse(dataResult);
				if (dataResult.statusCode == 200) {
					alert('deleted');
					$('#sales').find('input:text').val('');
					$("#success").show();
					$('#success').html(' Line Deleted !');
					$('#show').load('sales_view_ajax.php');
					$("#updateload_" + id).attr("style", "display:none");
					document.getElementById("c_dealer_name").value = $('#cdealername').val();
					//party();
					//c_party();
					location.reload();
				}
			}
		});

	}

	function pay(id) {

		$(document).ready(function () {
			$.ajax({
				url: "payment_view_ajax.php",
				method: "POST",
				dataType: "json",
				data: {
					s_no: $("#s_no").val()

				},

				success: function (data) {
					$("#sales_amount").val(data.sales_info.total_amt);
					$("#party").val(data.sales_info.dealer_name);
					$("#sales_dates").val(data.sales_info.sales_date);

				}
			})
		});
	}



	function party() {
		$(document).ready(function () {
			$.ajax({
				url: "party_info_ajax.php",
				method: "POST",
				dataType: "json",
				data: {
					dealer_id: $("#r_dealer_id").val()
				},
				success: function (data) {
					$("#r_address").val(data.dealer_info.customer_address);
				}

			})
		});
	}


	function c_party() {
		$(document).ready(function () {
			$.ajax({
				url: "party_info_ajax_corporate.php",
				method: "POST",
				dataType: "json",
				data: {
					dealer_id: $("#c_dealer_name").val()
				},
				success: function (data) {
					$("#c_address").val(data.dealer_info.customer_address);
					$("#c_contact").val(data.dealer_info.mobile_no);
					$("#c_address").attr("readonly", "readonly");
					$("#c_contact").attr("readonly", "readonly");
				}
			})
		});
	}




	function cal(id) {
		var rate = (document.getElementById('rate_' + id).value) * 1;
		var qty = (document.getElementById('qty_' + id).value) * 1;
		var total = rate * qty;
		document.getElementById('amount_' + id).value = total.toFixed(2);

	}


	function paycal() {
		var sales_amount = (document.getElementById('total_amt').value) * 1;
		var collectoin = (document.getElementById('collections').value) * 1;
		var discount = (document.getElementById('discounts').value) * 1;
			
		var total = collectoin + discount;
		var change = sales_amount - total;
		
		if(change > 0){
			document.getElementById('change').value = 0;
			document.getElementById('dues').value = change.toFixed(2);
			// actual receipt
			document.getElementById('actual_receipt').value = collectoin.toFixed(2);
		}else{
			document.getElementById('change').value = (change*(-1)).toFixed(2);
			document.getElementById('dues').value = 0;
			// actual receipt
			document.getElementById('actual_receipt').value = (sales_amount-discount).toFixed(2);
		}
	}
</script>
<?php include('../template/footer.php');?>