<?php
include('../db/model.php');
$obj = new Model();

$empList = $obj->EmployeeList();

if (isset($_POST["type"])) {
    if ($_POST["type"] == "led") {
        $ledger = $obj->GetEmpLedgerByEmpId($_POST, true);
        header('Content-Type: application/json');
        echo json_encode($ledger);
        exit;
    }

    if ($_POST["type"] == "led_upd") {
        $ledger = $obj->UpdateEmpLedger($_POST);
        header('Content-Type: application/json');
        echo json_encode($ledger);
        exit;
    }
}

?>

<style>
    #dataTable tbody td:nth-child(1),
    #dataTable tbody td:nth-child(2) {
        text-align: center;
    }

    #dataTable tbody td:nth-child(4),
    #dataTable tbody td:nth-child(5),
    #dataTable tbody td:nth-child(6) {
        text-align: end;
    }
</style>

<div class="row justify-content-center">
    <div class="mb-3 row align-items-center">
        <div class="col-12 col-md-4 mb-3">
            <select name="empList" id="empList" class="form-control form-select">
                <option value="">Select Employee</option>
                <?php foreach ($empList as $row): ?>
                    <option value="<?php echo $row['id']; ?>">
                        <?php echo $row['full_name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-12 col-md-4 mb-3" id="">
            <div class="d-flex">
                <div class="input-group rounded align-items-center justify-content-center" id="custom-form-light">
                    <input type="date" name="fromDate" id="fromDate" class="form-control">
                    <label for="" class="px-2" id="">to</label>
                    <input type="date" name="toDate" id="toDate" class="form-control">
                </div>
            </div>
        </div>
        <div class="col-12 col-md-4 mb-3">
            <div class="d-flex">
                <div class="input-group justify-content-center justify-content-md-end">
                    <button class="btn btn-sm action-btn-1" id="ViewLedger241201">FROM 1-DEC-2024</button>
                    <button class="btn btn-sm action-btn-1" id="ViewLedger">VIEW LEDGER</button>
                    <button class="btn btn-sm action-btn-1" id="UpdateLedger">UPDATE LEDGER</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="table-responsive">
    <table id="dataTable" class="table table-sm table-dark table-hover table-bordered" style="width: 100%;">
        <thead style="color:var(--s-text-color);" class="mt-3">
            <tr>
                <th style="width: 100px">Assign Date</th>
                <th style="width: 120px">Evn/Pay Date</th>
                <th>Event/Details</th>
                <th style="width: 70px;">Payable</th>
                <th style="width: 70px;">Payment</th>
                <th style="width: 70px;">Balance</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

</div>

<script>
    $(document).ready(function() {

        loadSelect2(['#empList']);

        var today = new Date();

        var firstOfPreviousMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
        var toDate = firstOfPreviousMonth.toISOString().split('T')[0];
        document.getElementById('fromDate').value = toDate;

        var fromDate = today.toISOString().split('T')[0];
        document.getElementById('toDate').value = fromDate;

        var table = $('#dataTable').DataTable({
            "paging": true,
            "lengthChange": true,
            "searching": false,
            "ordering": false,
            "info": true
        });

        $('#empList').on('change', function(e) {
            var emp_id = this.value;
            var fromDate = $('#fromDate').val();
            var toDate = $('#toDate').val();
            LoadLedger(emp_id, fromDate, toDate);
        });

        $('#ViewLedger').on('click', function(e) {
            var emp_id = $('#empList').val();
            var fromDate = $('#fromDate').val();
            var toDate = $('#toDate').val();
            LoadLedger(emp_id, fromDate, toDate)
        });

        $('#ViewLedger241201').on('click', function(e) {
            var emp_id = $('#empList').val();
            var fromDate = '2024-12-01';
            $('#fromDate').val(fromDate);
            var toDate = $('#toDate').val();
            LoadLedger(emp_id, fromDate, toDate)
        });

        function LoadLedger(emp_id, fromDate, toDate) {

            if (emp_id > 0) {
                if (fromDate == null || fromDate == '' || toDate == null || toDate == '') {
                    swal("Please check DATE range", {
                        icon: "warning",
                    });
                } else {
                    table.clear();
                    table.draw();

                    $.ajax({
                        type: "post",
                        url: "report_emp_ledger.php",
                        data: {
                            type: 'led',
                            emp_id: emp_id,
                            fromDate: fromDate,
                            toDate: toDate
                        },
                        success: function(response) {
                            table.clear();

                            if (response.length > 0) {
                                response.forEach(function(item) {
                                    var row = [
                                        sDate(item.create_at),
                                        sDate(item.date),
                                        item.remarks,
                                        item.payable_amt,
                                        item.payment,
                                        item.balance
                                    ];
                                    table.row.add(row).draw();
                                });
                                table.page('last').draw(false);
                            }
                        }
                    });
                }
            } else {
                swal("Please select Employee", {
                    icon: "warning",
                });
            }
        }

        $('#UpdateLedger').on('click', function(e) {
            var emp_id = $('#empList').val();
            var fromDate = $('#fromDate').val();
            var toDate = $('#toDate').val();

            if (emp_id > 0) {
                swal({
                    title: "Are you sure?",
                    text: "Once update ledger, you will not be able to recover old data!",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        if (fromDate == null || fromDate == '' || toDate == null || toDate == '') {
                            swal("Please check DATE range", {
                                icon: "warning",
                            });
                        } else {
                            $.ajax({
                                type: "post",
                                url: "report_emp_ledger.php",
                                data: {
                                    type: 'led_upd',
                                    emp_id: emp_id,
                                    fromDate: fromDate,
                                    toDate: toDate
                                },
                                success: function(response) {
                                    if (response) {
                                        swal("Ledger Updated", {
                                            icon: "success",
                                        });
                                        LoadLedger(emp_id, fromDate, toDate);
                                    }
                                },
                            });
                        }
                    }
                });
            } else {
                swal("Please select Employee", {
                    icon: "warning",
                });
            }
        });

        $('#printButtonEmpLedger').on('click', function(e) {
            var emp_id = $('#empList').val();
            var fromDate = $('#fromDate').val();
            var toDate = $('#toDate').val();

            if (CheckPrint()) {
                var printUrl = "../print/emp_ledger.php?ei=" + emp_id + "&f=" + fromDate + "&t=" + toDate;
                window.open(printUrl, "_blank");
            }
        });

    });
</script>