<?php 
$page_name ='purchase_entry';
include ('../common/library.php');  
include ('../common/helper.php');  
include ('../template/header.php');  
include ('../template/sidebar.php');

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

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


if(isset($_POST['purchase_submit']) && $_SESSION['purchase_no']>0){
//$find = find_a_field('journal','count(id)','tr_from like "Purchase" and tr_no='.$_SESSION['purchase_no']);
//if($find>0){ $_SESSION['purchase_no'] = ''; }else{



$journal_del = $conn->query('delete from journal where tr_no="'.$_SESSION['purchase_no'].'" and tr_from="Purchase"');

$journal_item_del = $conn->query('delete from journal_item where tr_no="'.$_SESSION['purchase_no'].'" and tr_from="Purchase"');
$jv_date = $_POST['purchase_date'];


$upd="update purchase_master set purchase_date='".$jv_date."' where purchase_no='".$_SESSION['purchase_no']."' ";
$conn->query($upd);



$ssql2 = "select sum(d.amount) as total_amount,m.purchase_no,m.purchase_date,c.ledger_id,c.supplier_name,c.phone_no from purchase_master m,purchase_order d,supplier_info c where m.purchase_no=d.purchase_no and m.supplier_id=c.id and m.group_for =".$_SESSION['group_for']." and m.purchase_no='".$_SESSION['purchase_no']."'";

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


$tr_from = 'Purchase';

//echo $jv_date = date('Y-m-d');

$cr_ledger = 1000005;

$status = 'Unpaid';
$entry_by = $_SESSION['user_id'];



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

if($max_jv==''){
$max_jv = date('Y-m-d');
}


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

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


// payment journal actual_receipt
if($_POST['total_paid']>0){

	if($_POST['payment_type'] !=''){
		$cr_ledger = $_POST['payment_type'];
	}else{
		$cr_ledger = 1000002;
	}
$dr_ledger = $j_data['ledger_id'];
$status = 'Paid';
$tr_from = 'Payment';

$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['total_paid'],0,$tr_from,$_SESSION['purchase_no'],$status);

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

}

$select = $conn->query("select * from purchase_order where  group_for =".$_SESSION['group_for']." and purchase_no='".$_SESSION['purchase_no']."'");

 while( $item_data = $select->fetch_assoc()){
$journal_item = $conn->query("INSERT INTO `journal_item`(`journal_date`, `item_id`, `rate`, `item_in`, `tr_no`, `tr_from`,`entry_by`,`warehouse`) VALUES ('".$jv_date."','".$item_data['item_id']."','".$item_data['rate']."','".$item_data['qty']."','".$item_data['purchase_no']."','Purchase','".$_SESSION['user_id']."','".$_SESSION['warehouse']."')");

}



//Text Sms

//function sms($dest_addr,$sms_text){
//$url = "https://api.mobireach.com.bd/SendTextMessage?Username=mollik&Password=Mplaza@123&From=MollikPlaza";
//

//$fields = array(
//    'Username'      => "mollik",
//    'Password'      => "Mplaza@123",
//    'From'          => "MollikPlaza",
//    'To'            => $dest_addr,
//    'Message'       => $sms_text
//);
//$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, count($fields));
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
//$result = curl_exec($ch);
//curl_close($ch);
//}



//$recipients ="88".$j_data['phone_no']."";
//$massage  = "Dear Sir,\r\nNew Purchase Order Submitted. \r\n";
//$massage .= "PO No. ".$j_data['purchase_no']." \r\n";
//$massage .= "Party Name : ".$j_data['supplier_name']." \r\n";
//$massage .= "Total Amount : ".$j_data['total_amount']." Taka \r\n";
//$sms_result=sms($recipients, $massage);
//$api =  'https://api.mobireach.com.bd/SendTextMessage?Username=mollik&Password=Mplaza@123&From=MollikPlaza&To=8801737174415&Message=testmessage';
//Text Sms
 $_SESSION['purchase_no'] = '';

}




if(isset($_POST['delete_submit'])){ 
	$purchase_master = $conn->query("DELETE FROM purchase_master WHERE purchase_no=".$_POST['delete_id']." ");
	$purchase_order = $conn->query("DELETE FROM purchase_order WHERE purchase_no=".$_POST['delete_id']." ");
	$journal = $conn->query("DELETE FROM journal WHERE tr_from like 'Purchase' and tr_no=".$_POST['delete_id']." ");
	$journal_item = $conn->query("DELETE FROM journal_item WHERE tr_from like 'Purchase' and tr_no=".$_POST['delete_id']." ");
	$msg = "Data deleted successfully !";
}


if(isset($_POST['update'])){}

$select = $conn->query("select * from purchase_master where group_for = ".$_SESSION['group_for']."  and purchase_no='".$_SESSION['purchase_no']."'");
$data = $select->fetch_assoc(); 



/*function find_a_field($table_name,$field,$unique_id){
    global $conn;
  $sql = "select ".$field." from ".$table_name." where ".$unique_id." limit 1";
 if(mysqli_num_rows($sql)>0){
$select = $conn->query($sql);
$data = $select->fetch_assoc();
echo $data[0];
}
 }*/



 /////////////////////////  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>';
   }
  
  }
?>



<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-8">
			<div class="container">
				<div class="card">
					<div class="card-header">
						<div class="d-flex align-items-center">
							<h4 class="card-title">Purchase Entry. <?=$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">
							<!-- Registered Customer Start-->
							<div class="row" id="rc">
								<div class="col-6">
									<div class="form-group row">
										<label class="col-sm-2 col-form-label">Select Party:</label>
										<div class="col-sm-10">
											<select name="supplier_id" class="form-control form-control"
												id="supplier_id">
												<option></option>
												<?php 
													     foreign_relation('supplier_info','id','supplier_name',$data['supplier_id'],'group_for="'.$_SESSION['group_for'].'" and status="Active"');
													   ?>
											</select>
										</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="purchase_date" required
												class="form-control form-control-sm" id="purchase_date"
												value="<? if($data['purchase_date'] !='') echo $data['purchase_date']; else echo date('Y-m-d');?>" placeholder="dd/mm/yyyy"
												min="2022-01-01" max="2030-12-31" />
										</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="itemIds" class="form-control form-control" id="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>
							<!--  Registered Customer End-->
					</div>
				</div>

				<div class="card">
					<div class="card-body">
						<table class="text-center" style="width:100%">
							<thead>
								<th>Item Name</th>
								<th>Stock</th>
								<th>Unit</th>
								<th>Rate</th>
								<th>Qty</th>
								<th>Amount</th>
								<th colspan="2">Action</th>
							</thead>
							<tbody>
							<tbody id="show">



								<?php
				$total_amt=0;
				$select = $conn->query("select * from purchase_order where group_for=".$_SESSION['group_for']." and purchase_no='".$_SESSION['purchase_no']."'");
				while( $item_data = $select->fetch_assoc()){
					$stock = find_a_field('journal_item','sum(item_in-item_ex)','1 and warehouse="'.$_SESSION['warehouse'].'" and item_id ='.$item_data['item_id']);
					$uom   = find_a_field('item_info','uom','item_id='.$item_data['item_id']);
					$total_amt +=$item_data['amount'];
				?>
								<tr>

									<td><select name="item_name_<?=$item_data['id'];?>"
											class="form-control form-control" id="item_name_<?=$item_data['id'];?>"
											onchange="edit(<?=$item_data['id'];?>)">
											<option></option>
											<?php
				foreign_relation('item_info','item_id','item_name',$item_data['item_id'],'group_for="'.$_SESSION['group_for'].'" and status="Active"');
				?>
										</select>
										<input type="hidden" name="update_id_<?=$item_data['id'];?>"
											id="update_id_<?=$item_data['id'];?>" onkeyup="edit(<?=$item_data['id'];?>)"
											value="<?=$item_data['id'];?>" /></td>
									<td><input type="text" name="stock_<?=$item_data['id'];?>"
											class="form-control form-control" id="stock_<?=$item_data['id'];?>"
											onkeyup="edit(<?=$item_data['id'];?>)" value="<?=$stock?>" required></td>
									<td><input type="text" name="unit_<?=$item_data['id'];?>"
											class="form-control form-control" id="unit_<?=$item_data['id'];?>"
											onkeyup="edit(<?=$item_data['id'];?>)" value="<?=$uom?>" required></td>
									<td><input type="text" name="rate_<?=$item_data['id'];?>"
											class="form-control form-control" id="rate_<?=$item_data['id'];?>"
											onkeyup="edit(<?=$item_data['id'];?>);cal(<?=$item_data['id'];?>);"
											value="<?=$item_data['rate'];?>" required></td>
									<td><input type="text" name="qty_<?=$item_data['id'];?>"
											class="form-control form-control" id="qty_<?=$item_data['id'];?>"
											onkeyup="edit(<?=$item_data['id'];?>);cal(<?=$item_data['id'];?>);"
											value="<?=$item_data['qty'];?>" required></td>
									<td><input type="text" name="amount_<?=$item_data['id'];?>"
											class="form-control form-control" id="amount_<?=$item_data['id'];?>"
											value="<?=$item_data['amount'];?>" required></td>
									<td><input type="button" name="edit_<?=$item_data['id'];?>" class="btn btn-primary"
											value="Edit" id="edit_<?=$item_data['id'];?>"></td>
									<td><button onclick="deleteData(<?=$item_data['id'];?>)"
											id="del_<?=$item_data['id'];?>" class="btn btn-danger">X</button></td>
								</tr>
								<?php } ?>
								<tr>
									<td colspan="5" class="text-right">Total Amount</td>
									<td><input type="text" name="total_amount" class="form-control form-control"
											id="total_amount" value="<?=$total_amt;?>" readonly></td>
									<td colspan="2"></td>
								</tr>
							</tbody>
						</table>
					</div>

					<!--<div class="card-footer text-center">
						        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#viewModal" id="pay" onclick="pay();">Payment</button>
						    </div>-->


					<div class="card-footer text-center">
						<input type="submit" name="purchase_submit" class="btn btn-secondary">
						<?php if($_GET['purchase_no']){ ?>
						<input type="hidden" name="delete_id" id="delete_id"
							value="<?php echo $_SESSION['purchase_no']; ?>">
						<input type="submit" name="delete_submit" value="Delete" class="btn btn-danger">
						<?php } ?>
					</div>
					
				</div>


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


			</div>
		</div>	
		
		<div class="col-md-4">
			<!--payment option-->
			<div class="card card">
				<div class="card-header ">
					<div class="card-title">Payment Option
					</div>
				</div>
				<div class="card-body">
					<div class="row">
						<div class="col-md-12">
							<div class="form-group
								form-group-default">
								<label>Payment Type</label>
								<select name="payment_type" id="payment_type" class="form-control">
									<option value="1000007">Cash</option>
									<option value="1000008">Bank</option>
									<option value="1000009">Commision</option>
								</select>
							</div>
							
							<div class="form-group
								form-group-default">
								<label>Details/Money Receipt</label>
								<input name="details" id="details" type="text" class="form-control" value="">
							</div>

							<div class="form-group
								form-group-default">
								<label>Total Paid</label>
								<input name="total_paid" id="total_paid" type="text" class="form-control" value="">
							</div>	
						</div>
					</div>
				</div>
			</div>	
		</div>
	</form>	

		</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>
	$(document).ready(function () {
		$("#item_id").change(function () {
			$("#item_id").attr("disabled", "disabled");
			var item_id = $('#item_id').val();
			var supplier_id = $('#supplier_id').val();
			var purchase_date = $('#purchase_date').val();



			if (item_id != "" && purchase_date != "") {
				$.ajax({
					url: "purchase_ajax.php",
					type: "POST",
					data: {
						item_id: item_id,
						supplier_id: supplier_id,
						purchase_date: purchase_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('purchase_view_ajax.php');
							$("#item_id").removeAttr("disabled");

						} else if (dataResult.statusCode == 201) {
							alert("Error occured !");
						}
					}
				});

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

			}
		});
	});



	$(document).ready(function () {});

	$("#item_id").change(function () {
		var purchase_date = $('#purchase_date').val();
		if (purchase_date != "") {
			$('#show').load('purchase_view_ajax.php');

		}
	});



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

		var purchase_date = $('#purchase_date').val();
		if (purchase_date != "") {
			$('#show').load('purchase_view_ajax.php');
		}
	});




	function edit(id) {

		$(document).ready(function () {

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

			$("#edit_" + id).attr("value", "W...");
			$("#del_" + id).attr("disabled", "disabled");
			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();


			if (item_id != "") {
				$.ajax({
					url: "purchase_edit_ajax.php",
					type: "POST",
					data: {
						item_id: item_id,
						unit_name: unit_name,
						rate: rate,
						qty: qty,
						amount: amount,
						update_id: update_id

					},
					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 !');
							$('#show').load('purchase_view_ajax.php');
							$("#edit_" + id).attr("value", "Updated");
							$("#del_" + id).removeAttr("disabled");

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

		});
	}



	function deleteData(str) {
		var id = str;
		$.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('purchase_view_ajax.php');
				}
			}
		});
	}




	function pay(id) {
		$(document).ready(function () {
			$.ajax({
				url: "payment_view_ajax.php",
				method: "POST",
				dataType: "json",
				data: {
					purchase_no: $("#purchase_no").val()
				},
				success: function (data) {
					$("#purchase_amount").val(data.sales_info.total_amt);
					$("#supplier").val(data.sales_info.supplier_name);
					$("#purchase_dates").val(data.sales_info.purchase_date);
				}
			})

		});
	}




	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('purchase_amount').value) * 1;
		var collectoin = (document.getElementById('paid').value) * 1;
		var discount = (document.getElementById('discount').value) * 1;
		var total = collectoin + discount;
		var due = sales_amount - (collectoin + discount);

		document.getElementById('total_paid').value = total.toFixed(2);
		document.getElementById('due').value = due.toFixed(2);
	}
</script>
<?php include('../template/footer.php');?>