<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style>
.table-responsive {
    overflow: visible !important;
}

.dropdown {
    position: relative !important;
}

</style>
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Expense - Entry</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
			<div class="col-12">
				<div class="card">
					<form role="form">
						<div class="card-body">
							<div class="row">
							<input type="text" class="form-control" id="txtID" style="display:none;">
								<div class="col-md-4">
									<div class="mb-3 row">
										<label class="col-4 col-form-label text-end">Date</label>
										<div class="col">
											<input type="text" class="flatpickr flatpickr-input active form-control" id="txtDatePicker" required>
										</div>
									</div>
									<div class="mb-3 row">
										<label class="col-4 col-form-label text-end">Voucher No.:</label>
										<div class="col">
											<input type="hidden" id="txtID" class="form-control">
											<input type="text" id="txtVoucherNo" class="form-control">
										</div>
									</div>
									<div class="mb-3 row">
										<label class="col-4 col-form-label text-end">Type: </label>
										<div class="col">
											<select type="text" class="form-control" id="cboType">
												<option value="Petty Cash">Petty Cash</option>
												<option value="Main Cash">Main Cash</option>
												<!-- <option value="Transfer">Transfer</option> -->
											</select>
										</div>
									</div>	
									
								</div>
								<div class="col-md-4">
									<div class="mb-3 row">
										<label for="cboAccountHead" class="col-4 col-form-label text-end">Account Head:</label>
										<div class="col">
											<div class="input-group">
												<select id="cboAccountHead" class="form-select"></select>
											</div>
										</div>
									</div>
									<div class="mb-3 row">
										<label for="txtParticular" class="col-4 col-form-label text-end">Particular:</label>
											<div class="col">
												<textarea class="form-control" id="txtParticular" name="txtParticular" data-bs-toggle="autosize" style="overflow: hidden; overflow-wrap: break-word; resize: none;"></textarea>
											</div>
									</div>
								</div>
								<div class="col-md-4">
									
									<div class="mb-3 row">
										<label for="txtQuantity" class="col-4 col-form-label text-end">Quantity/Price:</label>
										<div class="col-3">
											<input type="number" id="txtQuantity" class="form-control" value="1" min="1" >
										</div>
										<div class="col-5">
											<input type="text" id="txtPrice" class="form-control" placeholder="Enter price" >
										</div>
									</div>
									<div class="mb-3 row">
										<label for="remark" class="col-4 col-form-label text-end">Remark:</label>
										<div class="col">
											<input type="text" id="txtRemark" class="form-control">
										</div>
									</div>
									<div class="mb-3 row">
										<div class="col-12 d-flex justify-content-end">
											<!-- Save Button -->
											<div class="btnSave" style="display: block;">
												<button type="button" class="btn btn-outline-success" onclick="create();" id="btnSave">Save</button>
											</div>

											<!-- Edit and Cancel Buttons -->
											<div class="btnEdit" style="display: none; margin-left: 10px;">
												<button type="button" class="btn btn-outline-danger" onclick="clearForm()">Cancel</button>
											</div>
											<div class="btnEdit" style="display: none; margin-left: 10px;">
												<button type="button" class="btn btn-outline-primary" onclick="create()">Update</button>
											</div>
										</div>
									</div>


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

				<div class="mb-3 mt-3 table-responsive" style="max-height: 400px; overflow-y: auto;">
					<table class="table table-vcenter card-table" id="myTable">
						<thead style="position: sticky; top: 0; z-index: 10;">
							<tr>
								<th>#</th>
								<th>Date</th>
								<th>Voucher No.</th>
								<th>Type</th>
								<th>Code</th>
								<th>Account Head</th>
								<th>Particular</th>
								<th class="text-end">Quantity</th>
								<th class="text-end">Unit Price</th>
								<th class="text-end">Amount</th>
								<th>Remark</th>
								<th class="w-1"></th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>


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

<?php include '../footer.php'; ?>
<script>
var today = new Date().toISOString().split('T')[0];
    
    $(function() {
		flatpickr("#txtDatePicker", {
			dateFormat: "Y-m-d", 
			defaultDate: today,  
			maxDate: today,      
		});
        getAccountHead();
		getAll();
    });

	function getAccountHead() {
    $("#cboAccountHead").find("option").remove(); // Clear existing options
    $.ajax({
        url: APP_URL + "api/coa/get_all_rows.php",
        type: "POST",
        data: JSON.stringify({account_type: ""}),
        success: function(data) {    
            $("#cboAccountHead").append("<option value='' ></option>");
            $.each(data.records, function(i, v) {    
                $("#cboAccountHead").append("<option value='" + v.account_code + "' head='" + v.account_head + "'>" + v.account_code + " " + v.account_head + "</option>");                            
            }); 
            // After adding all options, call disableAccountHead based on cboType
            // disableAccountHead();
        }
    });
}

function disableAccountHead() {
    var cboType = $("#cboType").val();
    if (cboType === 'Transfer') {
        $("#cboAccountHead option").each(function() {
            if ($(this).val() === '1-2120') {
                $(this).prop('disabled', false);
            } else {
                $(this).prop('disabled', true);
            }
        });
    } else {
        $("#cboAccountHead option").each(function() {
            if ($(this).val() === '1-2120') {
                $(this).prop('disabled', true);
            } else {
                $(this).prop('disabled', false);
            }
        });
    }
}

// $("#cboType").change(function() {
//     // Call disableAccountHead whenever cboType changes
//     disableAccountHead();
// });







	$("#txtDatePicker").change(function(){
    	getAll();
    });
	
	function getAll(){
		$("#myTable").find("tbody").find("tr").remove();
		var date = $("#txtDatePicker").val();
		$.ajax({
			url: APP_URL + "api/expense/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ date: date }),
		}).done(function(data) {
			console.log(data);
			$.each(data.records, function(i, v) {
				if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(0 + " record(s) found.");}
				console.log(v);
				$("#myTable").find("tbody")
				.append($('<tr>')
				.append("<td style='width: 10px'>" + (i + 1) + "</td>")
				.append("<td>" + v.date + "</td>")
				.append("<td>" + v.voucher_no + "</td>")
				.append("<td>" + v.type + "</td>")
				.append("<td>" + v.account_code + "</td>")
				.append("<td>" + v.account_head + "</td>")
				.append("<td>" + v.particular + "</td>")
				.append("<td style='text-align:right;'>" + Number(v.quantity).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
				.append("<td style='text-align:right;'>" + Number(v.price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
				.append("<td style='text-align:right;'>" + Number(v.total_amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
				.append("<td>" + v.remark + "</td>")
				.append(`
					<td>
						<div class="dropdown">
							<button class="btn btn-outline-primary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
								Actions
							</button>
							<ul class="dropdown-menu">
								<li><a class="dropdown-item" onclick="edit('${v.id}', this)">Edit</a></li>
								<li><a class="dropdown-item text-danger" onclick="del('${v.id}', this)">Delete</a></li>
							</ul>
						</div>
					</td>
				`)
			);

			});
			$("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
			.append("<td colspan='9' style='text-align:right;'>Total Amount</td>")
			.append("<td style='text-align:right;'>" + ((data.net_amount)?Number(data.net_amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
			.append("<td style='text-align:right;'></td>")
			.append("<td style='text-align:right;'></td>")
  			); 
		});
	}

	function create(){ 
		var id = $("#txtID").val();
		var date = $("#txtDatePicker").val();
		var voucher_no = $("#txtVoucherNo").val();
		var type = $("#cboType").val();
		var account_head = $("#cboAccountHead option:selected").attr("head");
		var account_code = $("#cboAccountHead").val();
		var particular = $("#txtParticular").val();
		var quantity = parseFloat($("#txtQuantity").val().replace(/,/g, ''));
		var price = parseFloat($("#txtPrice").val().replace(/,/g, ''));
		var remark = $("#txtRemark").val();

		if(particular.trim()=="" ){
			showAlert("Please fill particular.",'warning');
		}else if(account_head.trim()==""){
			showAlert("Please choose account head.",'warning');
		}
		else{
			$.ajax({
				url: APP_URL + "api/expense/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, date: date, voucher_no: voucher_no, type: type, account_head: account_head, account_code: account_code, particular:particular, quantity:quantity, price:price, remark:remark}),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					showAlert("Successfully Saved.","success");
					$("#txtID").val("");
				// 	$("#txtVoucherNo").val("");
				// 	$("#cboAccountHead").val("");
					$("#txtParticular").val("");
					$("#txtQuantity").val(1);
					$("#txtPrice").val("");

					getAll();
				}else if(data.message=="updated"){
					showAlert("Successfully Updated.","success");
					$(".btnSave").css("display", "block");
					$(".btnEdit").css("display", "none");
					$("#txtID").val("");
				// 	$("#txtVoucherNo").val("");
				// 	$("#cboAccountHead").val("");
					$("#txtParticular").val("");
					$("#txtQuantity").val(1);
					$("#txtPrice").val("");

					getAll();
				}else{
					showAlert("Error on server side.","warning");
				}
			});
		}   
	}

    function del(id, obj) {
		Swal.fire({
			title: 'Are you sure?',
			text: 'Do you really want to delete this item?',
			icon: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes, delete it!',
			cancelButtonText: 'No, keep it',
			customClass: {
				confirmButton: 'btn-danger',
				cancelButton: 'btn-primary'
			},
			reverseButtons: true
		}).then((result) => {
			if (result.isConfirmed) {
				$.ajax({
					type: "POST",
					url: APP_URL + "api/expense/delete.php",
					data: JSON.stringify({ id: id }),
					success: function(data) {
						if (data == "deleted") {
							getAll();
						} else {
							Swal.fire('Error!', 'Error on server side.', 'error');
						}
					}
				});
			}
		});
	}

	function edit(id, obj) {

		$(".btnSave").css("display", "none");
		$(".btnEdit").css("display", "block");
		$(".fa-edit").attr("disabled", true);
		$(obj).attr("disabled", false);

		var tr = $(obj).closest('tr'); 

		console.log('Table row content:', tr.find("td").map(function() { return $(this).text(); }).get());

		$("#txtID").val(id);
		$("#txtDatePicker").val(tr.find("td").eq(1).text().trim());
		$("#txtVoucherNo").val(tr.find("td").eq(2).text().trim());
		$("#cboType").val(tr.find("td").eq(3).text().trim());
		$("#cboAccountHead").val(tr.find("td").eq(4).text().trim());
		$("#txtParticular").val(tr.find("td").eq(6).text().trim());
		$("#txtQuantity").val(parseFloat(tr.find("td").eq(7).text().trim().replace(/,/g, '')));
		$("#txtPrice").val(tr.find("td").eq(8).text().trim());
		$("#txtRemark").val(tr.find("td").eq(10).text().trim());
	}

	function clearForm(){

		$(".btnSave").css("display", "block");
		$(".btnEdit").css("display", "none");
		$(".fa-edit").attr("disabled", false);

		$("#txtID").val("");
		$("#txtDatePicker").val(today);
		$("#txtVoucherNo").val("");
		$("#cboAccountHead").val("");
		$("#txtParticular").val("");
		$("#txtQuantity").val(1);
		$("#txtPrice").val("");
		$("#txtRemark").val("");

	}

	function showAlert(message, type) {
		Swal.fire({
			title: type == 'success' ? 'Success' : 'Oops!',
			text: message,
			icon: type
		});
	}
</script>
