<?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">Type</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Create Type</button>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-vcenter card-table" id="myTable">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Type Code</th>
                                        <th>Type</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createModel" tabindex="-1" aria-labelledby="createModelLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModelLabel">Type Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="container" id="alertContainer2"></div>
            <div class="modal-body">
                <form id="createEntryForm">
                    <input type="hidden" class="form-control" id="txtRoomId">
                    <div class="mb-3">
                        <label for="category" class="form-label">Category</label>
                        <select class="form-control" id="category" required>
                            <option value="" disabled selected>Select category</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="typeCode" class="form-label">Type Code</label>
                        <input type="text" class="form-control" id="typeCode" placeholder="Enter type code" required>
                    </div>
                    <div class="mb-3">
                        <label for="type" class="form-label">Type</label>
                        <input type="text" class="form-control" id="type" placeholder="Enter type" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="btnSave" class="btn btn-outline-success" onclick="validateAndSave()">Create</button>
            </div>
        </div>
    </div>
</div>

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

<script>
$(function() {
    getAll();
    fillCategory();
});

function getAll(){
		$("#myTable").find("tbody").find("tr").remove();
        var category = "";	
		$.ajax({
			url: APP_URL + "api/type/get_all_rows.php",
				type: "POST",
				data: JSON.stringify({ category: category }),
		}).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);
				var buttonHtml = '';
				// if (!v.type_code) {
					buttonHtml = "<td'><button type='button' class='btn btn-block btn-outline-success btn-sm fas fa-edit' onclick='edit(\"" + v.id + "\", this)' style='padding: 0px 13px;font-size: 14px; min-width: 37px'></button></td>";
				// }
				$("#myTable").find("tbody")
				.append($('<tr>')
					// .append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td>" + v.category + "</td>")
					.append("<td>" + v.type_code + "</td>")
					.append("<td>" + v.type + "</td>")
					.append(buttonHtml)
					// <span class='btn btn-danger btn-sm' style='cursor:pointer; font-size: 12px; width: 40px;' onclick='delItem(\"" + v.id + "\", this)'><i class='fas fa-trash' title='Delete'></i></span>
					)
			});
		});
	}

function fillCategory(){
    $.ajax({
        url: APP_URL + "api/category/get_all_rows.php"
    }).done(function(data) {	
    $("#category").find("option").remove();
        $.each(data.records, function(i, v) {	
            $("#category").append("<option value= '" + v.category + "' code='"+v.code+"' id='"+v.id+"'>" + v.category + "</option>");		
        });
    });

}



$("#btnCreateNew").click(function() {
    $("#createEntryForm").trigger("reset");
    $('#createModel').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});

function validateAndSave(){	
		$("#loading").css("display","block");
        var category = $("#category").val();	
		var type_code = $("#typeCode").val();	
		var type = $("#type").val();	

		if(type_code=="" || type=="" ){
			showAlert("Please fill the boxes.",'warning');
			$("#loading").css("display","none");
			return false;
		}else{
			$.ajax({
				url: APP_URL + "api/type/create.php",
				type: "POST",
				data: JSON.stringify({ category: category, type_code: type_code, type: type }),
			}).done(function(data){
				$("#loading").css("display","none");
				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.",'danger');
				}
			});
		}		
	}

    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');
            }
        });
    }

</script>
