<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

		<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">Chart of Account - Entry</h2>
					</div>
				</div>
			</div>
		</div>
			

		<div class="page-body">
			<div class="container-xl">
				<div class="row row-cards">
					<div class="col-md-4">
						<div class="card card-outline card-primary">
							<form role="form">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12 mb-3">
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Account Type: </label>
												<div class="col-md-8">
													<select type="text" class="form-select" id="cboAccountType">
														<option value="" code=''></option>
														<option value="Asset" code='1-'>Asset</option>
														<option value="Liabilities"  code='2-'>Liabilities</option>
														<option value="Equity"  code='3-'>Equity</option>
														<option value="Incomes"  code='4-'>Incomes</option>
														<option value="Cost of Sales"  code='5-'>Cost of Sales</option>
														<option value="Expenses"  code='6-'>Expenses</option>
													</select>       
												</div>
											</div>
										</div>
										<div class="col-md-12 mb-3">
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Type of Expense: </label>
												<div class="col-md-8">
													<select type="text" class="form-select" id="cboTypeOfExpense">
														<option value="" code=''></option>
                                                        <option value="Operation Expenses">Operation Expenses</option>
                                                        <option value="Operation Expenses - Housekeeping Supplies">Operation Expenses - Housekeeping Supplies</option>
                                                        <option value="Operation Expenses - Kitchen Supplies">Operation Expenses - Kitchen Supplies</option>
                                                        <option value="Operation Expenses - Customer Complimentary & Other Expenses">Operation Expenses - Customer Complimentary & Other Expenses</option>
                                                        <option value="Office & Admin Expenses">Office & Admin Expenses</option>
                                                        <option value="Employment Expenses">Employment Expenses</option>
                                                        <option value="Selling & Distribution Expenses">Selling & Distribution Expenses</option>
													</select>       
												</div>
											</div>
										</div>
										<div class="col-md-12 mb-3">
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Account Code: </label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtID" hidden >
													<input type="text" class="form-control" id="txtAccountCode" maxlength="6">
												</div>
											</div>
										</div>
										<div class="col-md-12 mb-3">
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Account Head: </label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtAccountHead">
												</div>
											</div>
										</div>
										<div class="col-md-12 mb-3" style="display:none;">
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Status: </label>
												<div class="col-md-8">
													<!-- Radio button for Debit -->
													<div class="form-check form-check-inline mt-2">
														<input class="form-check-input" type="radio" name="status" id="debit" value=1>
														<label class="form-check-label" for="debit">Debit</label>
													</div>
													<!-- Radio button for Credit -->
													<div class="form-check form-check-inline mt-2">
														<input class="form-check-input" type="radio" name="status" id="credit" value=0>
														<label class="form-check-label" for="credit">Credit</label>
													</div>
												</div>
											</div>
										</div>
										<div class="col-md-12 mb-3">
											<div class="form-group row">
												<div class="col-md-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>
													
													<!-- Cancel Button (Hidden by default) -->
													<div class="btnEdit" style="display: none;">
														<button type="button" class="btn btn-outline-danger" onclick="clearForm()">Cancel</button>
													</div>
													
													<!-- Update Button (Hidden by default) -->
													<div class="btnEdit" style="display: none;">
														<button type="button" class="btn btn-outline-primary ms-2" onclick="create()">Update</button>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>
					<div class="col-md-8">
						<div class="card card-outline card-primary">
							<div class="card-body p-0">
								<table class="table table-striped table-bordered" id="myTable">
									<thead>                  
										<tr>
											<th style="width: 3%">#</th>
											<th>Account Type</th>
											<th>Type Of Expense</th>
											<th>Account Code</th>
											<th>Account Head</th>
											<!--<th style="width: 3%;white-space: nowrap;">Debit</th>-->
											<!--<th style="width: 3%;white-space: nowrap;">Credit</th>-->
											<th style="width: 10%;">Edit</th>
										</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

<?php include '../footer.php'; ?>
<script>


	$(function() {
		// $("body").addClass("sidebar-collapse");
		$("#cboTypeOfExpense").prop("disabled", true);
		$("#txtAccountCode").val($("#cboAccountType option:selected").attr("code"));
		getAll();
	});

	$("#cboAccountType").change(function () {
		$("#txtAccountCode").val($("#cboAccountType option:selected").attr("code"));
		if ($("#cboAccountType").val() === "Expenses") {
			$("#cboTypeOfExpense").prop("disabled", false);
		} else {
			$("#cboTypeOfExpense").val("");
			$("#cboTypeOfExpense").prop("disabled", true);
		}
	});


	function create(){	
		var id = $("#txtID").val();
		var type_of_expense = $("#cboTypeOfExpense").val();	
		var account_type = $("#cboAccountType").val();	
		var account_code = $("#txtAccountCode").val();
		var account_head = $("#txtAccountHead").val();	
		var debit_credit = $('input[name="status"]:checked').val();

// 		if(debit_credit==1){
			var debit = 0;
			var credit = 0;
// 		}else if(debit_credit==0){
// 			var debit = 0;
// 			var credit = 0;
// 		}
// 		else{
// 			showAlert("Please choose debit or credit.","warning");
// 		}

		if(account_type=="" || account_code=="" || account_head==""){
			showAlert("Please fill the boxes.","warning");
			return false;
		}else{
			$.ajax({
				url: APP_URL + "api/coa/create.php",
				type: "POST",
				data: JSON.stringify({ id: id, type_of_expense: type_of_expense, account_type: account_type, account_code:account_code, account_head: account_head, debit:debit, credit:credit }),
			}).done(function(data){
				if(data.message=="created"){
					showAlert("Successfully Added.","success");
					getAll();
					clearForm();
				}else if(data.message=="duplicate"){
					showAlert("Not allow duplicate rows.","warning");
				}else if(data.message=="updated"){
					showAlert("Successfully Updated","success");
					getAll();
					clearForm();
				}else{
					showAlert("Error on server side.","warning");
				}
			});
		}		
	}

	function btozero(obj){
		if($(obj).val() == "")$(obj).val("");
	}

	function isNumber(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    var input = evt.target.value;
    var decimalPointIndex = input.indexOf('.');
    
    return (charCode >= 48 && charCode <= 57) || // digits 0-9
           (charCode == 46 && decimalPointIndex === -1) ;
}

    $("#cboAccountType").change(function(){
    	getAll();
    });

	function getAll(){
		var account_type = $("#cboAccountType").val();
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/coa/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ account_type: account_type })
		}).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.account_type + "</td>")
					.append("<td>" + v.type_of_expense + "</td>")
					.append("<td>" + v.account_code + "</td>")
					.append("<td>" + v.account_head + "</td>")
				// 	.append("<td  style='text-align:center;'>" + (v.debit == 1 ? '<i class="fas fa-check-circle" ></i>' : '') + "</td>")
				// 	.append("<td  style='text-align:center;'>" + (v.credit == 1 ? '<i class="fas fa-check-circle"></i>' : '') + "</td>")
.append("<td><button type='button' class='btn btn-block btn-outline-success btn-sm' onclick='edit(\"" + v.id + "\", this)'>Edit</button>&nbsp;<button type='button' class='btn btn-block btn-outline-danger btn-sm' onclick='del(\"" + v.id + "\", this)'>Delete</button></td>")
					);
			});
		});
	}

	function clearForm(){
		$("#cboAccountType").attr("disabled", false);
		$("#txtAccountCode").attr("disabled", false);

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

		$("#txtID").val("");
		$("#txtAccountHead").val("");
		$("#txtAccountCode").val("");
		$("#txtAccountCode").val($("#cboAccountType option:selected").attr("code"));

	}


	function edit(id, obj){
		$("#txtAccountHead").focus();
		$("#cboAccountType").attr("disabled", true);
		$("#txtAccountCode").attr("disabled", true);



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

		$(obj).attr("disabled", false);
		var tr = $(obj).parent().parent();

		if ($(tr).find("td").eq(1).text() === "Expenses") {
			$("#cboTypeOfExpense").prop("disabled", false);
		} else {
			$("#cboTypeOfExpense").val("");
			$("#cboTypeOfExpense").prop("disabled", true);
		}
		
		$("#txtID").val(id);
		$("#cboAccountType").val($(tr).find("td").eq(1).text());
		$("#cboTypeOfExpense").val($(tr).find("td").eq(2).text());
		$("#txtAccountCode").val($(tr).find("td").eq(3).text());
		$("#txtAccountHead").val($(tr).find("td").eq(4).text());

// 		let hasDebitIcon = $(tr).find("td").eq(4).find("i").length > 0;
// 		let hasCreditIcon = $(tr).find("td").eq(5).find("i").length > 0;


		console.log("Has debit icon:", hasDebitIcon);
		console.log("Has credit icon:", hasCreditIcon);


// 		if (hasDebitIcon) {
// 			$("#debit").prop("checked", true);
// 			$("#credit").prop("checked", false);
// 		} else if (hasCreditIcon) {
// 			$("#credit").prop("checked", true);
// 			$("#debit").prop("checked", false);
// 		} else {
// 			$("#debit").prop("checked", false);
// 			$("#credit").prop("checked", false);
// 		}
	}

	function showAlert(message, type) {
		Swal.fire({
			title: type === 'success' ? 'Success!' : 'Oops!',
			text: message,
			icon: type,
			// confirmButtonText: 'OK',
			timer: 1000, // Auto close after 3000 milliseconds (3 seconds)
			timerProgressBar: true, // Optional: Show a progress bar
			willClose: () => {
				// Optional: Execute code just before the alert closes
				console.log('Alert closed');
			}
		});
	}
	
	function del(id, obj) {
    $('#modal-delete').modal('show');
    $('#confirm-delete').off('click').on('click', function() {
        // $(this).prop("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');

        $.ajax({
            type: "POST",
            url: APP_URL + "api/coa/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data === "deleted") {
                    getAll();
                    // $(obj).closest("tr").remove();
                    showAlert("Deleted Successfully!", "success");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                $('#modal-delete').modal('hide');
                // $('#confirm-delete').prop("disabled", false).text("Delete");
            }
        });
    });
}

</script>
