<?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">Employee</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">New Employee</button>
            </div>
        </div>
    </div>
</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 id="myTable" class="table card-table table-vcenter text-nowrap datatable" >
                                <thead>
                                    <tr>
                                        <!-- <th class="w-1"><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select all reservations"></th> -->
                                        <th>Name</th>
                                        <th>Position</th>
                                        <th>Phone</th>
                                        <th>Email</th>
                                        <th>NRC</th>
                                        <th>Gender</th>
                                        <th>DOB</th>
                                        <th>Address</th>
                                        <th>Join Date</th>
                                        <th>Resign Date</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createEntryModal" tabindex="-1" aria-labelledby="createEntryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createEntryModalLabel">Employee 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="staffId">
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Name</label>
                        <div class="col">
                        <input type="text" id="name" class="form-control" placeholder="Enter name">
                        </div>
                    </div>

                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Position</label>
                        <div class="col">
                        <input type="text" id="position" class="form-control" placeholder="Enter position">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Phone</label>
                        <div class="col">
                        <input type="text" id="phone" class="form-control" placeholder="Enter phone">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Email</label>
                        <div class="col">
                        <input type="email" id="email" class="form-control" placeholder="Enter email">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">NRC</label>
                        <div class="col">
                        <input type="text" id="nrc" class="form-control" placeholder="Enter nrc">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-md-4 col-form-label text-end">Gender:</label>
                        <div class="col" style="padding-top: 8px;">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" id="radioMale" name="r1" value="Male" checked>
                                <label class="form-check-label" for="radioMale">Male</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" id="radioFemale" name="r1" value="Female">
                                <label class="form-check-label" for="radioFemale">Female</label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Date of Birth</label>
                        <div class="col">
                        <input type="text" id="dob" class="form-control" placeholder="Select a date">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Address</label>
                        <div class="col">
                        <textarea id="address" class="form-control" placeholder="Enter address" data-bs-toggle="autosize"></textarea>
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Join Date</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="joinDate" placeholder="Select a date" required>
                        </div>
                    </div>
                    <div class="mb-3 row" id="resignDateSection" style="display: none;">
                        <label class="col-4 col-form-label text-end">Resign Date<input type="checkbox" id="chkResignDate">:</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="resignDate" placeholder="Select a date" required>
                        </div>
                    </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>
    var today = new Date().toISOString().split('T')[0];
$(function() {

	flatpickr("#dob", {
        dateFormat: "Y-m-d", 
        defaultDate: '2000-01-01',  
        maxDate: today,      
    });
	flatpickr("#joinDate", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    flatpickr("#resignDate", {
        dateFormat: "Y-m-d", 
        maxDate: today,      
    });
    // $("input[type='number']").on("input", function() {
    //     this.value = this.value.replace(/[^0-9]/g, ''); 
    // });

    getAll();
});

function getAll() {
    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/staff/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 1 }, 
            { data: 2 },
            { data: 3 }, 
            { data: 4 }, 
            { data: 5 }, 
            { data: 6 }, 
            { data: 7 }, 
            { data: 8 },
            { data: 9 },
            { data: 10 },
            { 
                data: null, 
                render: function(data, type, row) {
                    return `
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                Actions
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="edit('${row[0]}')">Edit</a></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="del('${row[0]}', this)">Delete</a></li>
                            </ul>
                        </div>
                    `;
                }
            }

        ],
        // columnDefs: [
        //     {
        //         targets: [10],
        //         createdCell: function (td, cellData, rowData, row, col) {
        //             $(td).css('text-align', 'left');
        //         }
        //     }
        //     {
        //         targets: [2, 3, 6], // Make columns 1, 2, and 3 searchable
        //         searchable: true
        //     },
        //     {
        //         targets: [0,1,4, 5,7,8,9,10], // Disable search functionality for columns 4, 5, 6
        //         searchable: false
        //     }
        // ],
        paging: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        },
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    });
}

$("#btnCreateNew").click(function() {
    // $("#createEntryForm").trigger("reset");
    $("#staffId").val("");
    $("#name").prop("disabled", false);
    $('#createEntryModal').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});


function validateAndSave() {

    let isValid = true;

    $("#name").removeClass("is-invalid");

    if ($("#name").val() === null || $("#name").val().trim() === "") {
        $("#name").addClass("is-invalid");
        isValid = false; 
    }

    if (isValid) {

        // $(this).prop("disabled", true).text("Loading...");

        var room_entry = {
            "id": $("#staffId").val(),
            "name": $("#name").val(),
            "position": $("#position").val(),
            "phone": $("#phone").val(),
            "email": $("#email").val(),
            "nrc": $("#nrc").val(),
            "gender": $('input[name=r1]:checked').val(),
            "dob": $("#dob").val(),
            "join_date": $("#joinDate").val(),
            "address": $("#address").val(),
            "resign_date": ($("#chkResignDate").prop("checked"))?$("#resignDate").val():""
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/staff/create_update.php",
            data: JSON.stringify(room_entry),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    // $("#createEntryForm").trigger("reset");
                    $('#createEntryModal').modal('hide');
                    $("#name").val("");
                    showAlert("Employee " + (data.message === "created" ? "Created" : "Updated") + " Successfully!", "success");
                    getAll();

                } else if (data.message === "duplicate") {
                    showAlert("name already exists!", "warning");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                // $("#btnSave").prop("disabled", false).text(button.innerText);
            }
        });
    }
}



function edit(id) {

    $("#createEntryForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createEntryModal').modal('show');
    $("#staffId").val(id);
    $("#resignDateSection").show();
    $.ajax({
        url: APP_URL + "api/staff/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            $("#name").prop("disabled", true);
            $("#name").val(data.name);
            $("#position").val(data.position); 
            $("#phone").val(data.phone);
            $("#email").val(data.email);
            $("#nrc").val(data.nrc);
            $("#dob").val(data.dob);
            $("#address").val(data.address);
            $("#joinDate").val(data.join_date);
            if (data.resign_date.trim() !== "") {;
			$("#chkResignDate").prop("checked", true);
			$("#resignDate").val(data.resign_date);
		    } else {
                $("#chkResignDate").prop("checked", false);
                $("#resign").val('');
            }
            $("input[name='r1'][value='" + data.gender + "']").prop("checked", true);

        } else {
            console.log(data);
        }
    });
}

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/staff/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data.message === "deleted") {
                    getAll();
                    // $(obj).closest("tr").remove();
                    showAlert("Employee 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");
            }
        });
    });
}


function showAlert(message, type) {
    Swal.fire({
        title: type === 'success' ? 'Success!' : 'Oops!',
        text: message,
        icon: type,
        timer: 1000,
        timerProgressBar: true, 
        willClose: () => {
            console.log('Alert closed');
        }
    });
}
</script>
