<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 
<style>
    #myTable tbody tr:hover {
        background-color: #f1f1f1; /* Adjust to your preferred color */
        cursor: pointer;
    }
</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">Driver</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Add Driver</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 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>Driver Name</th>
                                        <th>Phone</th>
                                        <th>License No.</th>
                                        <th>License Expiry</th>
                                        <th>Note</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">Driver 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="agentId">
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Driver Name</label>
                        <div class="col">
                        <input type="text" id="agentName" class="form-control" placeholder="Enter driver name">
                        </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">License No.</label>
                        <div class="col">
                        <input type="text" id="email" class="form-control" placeholder="Enter license number">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">License Expiry</label>
                        <div class="col">
                        <input type="date" id="address" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Note</label>
                        <div class="col">
                        <textarea id="remark" class="form-control" placeholder="Enter note" data-bs-toggle="autosize"></textarea>
                        </div>
                    </div>
                    <div class="mb-3 row d-flex align-items-center">
                        <label class="col-4 col-form-label text-end">Inactive</label>
                        <div class="col">
                        <input type="checkbox" class="form-check-input" id="inActive" name="inActive" value="0" >
                        </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>
$(function() {
    $('#checkbox').hide();

    // $('#createEntryModal').modal({
    //     backdrop: 'static', // Prevents closing the modal by clicking outside it
    //     keyboard: false // Prevents closing the modal with the Escape key
    // });

    $("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/agent/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 1 }, 
            { data: 2 },
            { data: 3 }, 
            { data: 4 }, 
            { data: 5 }, 
            { 
                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" href="#" onclick="del('${row[0]}', this)">Delete</a></li>
                            </ul>
                        </div>
                    `;
                }
            }
        ],
        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"
        }
    });
}

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


function validateAndSave() {

    let isValid = true;

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

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

    if (isValid) {

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

        var driver_entry = {
            "id": $("#agentId").val(),
            "agent_name": $("#agentName").val(),
            "commission": 0,
            "phone": $("#phone").val(),
            "email": $("#email").val(),
            "address": $("#address").val(),
            "remark": $("#remark").val(),
            "inactive" : $('#inActive').is(':checked') ? "1" : "0"

        };

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

                } else if (data.message === "duplicate") {
                    showAlert("Driver 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');
    $("#agentId").val(id);
    $.ajax({
        url: APP_URL + "api/agent/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            // $("#roomNumber").prop("disabled", true);
            $("#agentName").val(data.agent_name);
            $("#phone").val(data.phone);
            $("#email").val(data.email);
            $("#address").val(data.address);
            $("#remark").val(data.remark);
            $("#inActive").prop("checked", data.inactive);
        } 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/agent/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data.message === "deleted") {
                    getAll();
                    // $(obj).closest("tr").remove();
                    showAlert("Driver 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,
        // 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>
