<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 
<style>
.table-responsive {
    overflow: visible !important;
}

.dropdown {
    position: relative !important;
}

</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">Income Report</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
						<div class="row">
							<div class="col-3 mb-3 row">
                                <label class="col-4 col-form-label text-end">Date From</label>
                                <div class="col">
                                    <input type="text" class="flatpickr flatpickr-input active form-control" id="dateFrom" required>
                                </div>
                            </div>
							<div class="col-3 mb-3 row">
                                <label class="col-4 col-form-label text-end">Date To</label>
                                <div class="col">
                                    <input type="text" class="flatpickr flatpickr-input active form-control" id="dateTo" required>
                                </div>
                            </div>
                            <div class="col-3 mb-3 row">
                                <label for="cboType" class="col-4 col-form-label text-end">Type</label>
                                <div class="col">
                                    <select type="text" class="form-select" id="cboType" placeholder="Select type">
                                        <option value="">Select type</option>
                                        <option value="Petty Cash">Petty Cash</option>
                                        <option value="Main Cash">Main Cash</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-3 mb-3 row">
                                <label for="cboAccountHead" class="col-4 col-form-label text-end">Account Head</label>
                                <div class="col">
                                    <select class="form-select" id="cboAccountHead" name="cboAccountHead" placeholder="Select account head">
                                    </select>
                                </div>
                            </div>
						</div>
                <div class="card">
                    <div class="card-body">
                        <div class="export-buttons-container" style="margin-bottom: 10px;">
                            <button id="exportCSV" class="btn btn-outline-primary">Export to CSV</button>
                            <button id="exportExcel" class="btn btn-outline-primary">Export to Excel</button>
                            <button id="exportPDF" class="btn btn-outline-primary">Export to PDF</button>
                            <button id="printTable" class="btn btn-outline-primary">Print Table</button>
                        </div>
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter datatable" >
                                <thead>
                                    <tr>
                                        <th>ID</th>
										<th style="text-align: left;">Date</th>
                                        <th style="text-align: left;">Voucher No.<span class="searchable">🔍</span></th>
                                        <th>Type</th>
                                        <th style="text-align: left;">Code</th>
                                        <th>Account Head</th>
                                        <th>Particular<span class="searchable">🔍</span></th>
                                        <th class="text-end">Quantity</th>
                                        <th class="text-end">Unit Price</th>
                                        <th class="text-end">Amount</th>
                                        <th>Remark</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="9">Total</th>
                                        <th id="totalAmount">0.00</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        <!-- <div class="d-flex justify-content-end text-bold">Total Amount: <span id="totalAmount">0.00</span></div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="myModel">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit</h5>
            </div>
            <div class="modal-body">
                <form>
                    <input type="hidden" class="form-control" id="txtID">
                    <div class="row">
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Date</label>
                            <div class="col">
                                <input type="text" class="flatpickr flatpickr-input active form-control" id="txtDatePicker2" required>
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Particular</label>
                            <div class="col">
                                <textarea class="form-control" id="txtParticularE" name="txtParticularE" data-bs-toggle="autosize" style="overflow: hidden; overflow-wrap: break-word; resize: none;"></textarea>
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Voucher No.</label>
                            <div class="col">
                                <input type="text" class="form-control" id="txtVoucherNoE">
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label for="txtQuantityE" class="col-md-4 col-form-label text-end">Qty/Unit Price</label>
                            <div class="col-md-3">
                                <input type="number" id="txtQuantityE" class="form-control" value="1" min="1">
                            </div>
                            <div class="col-md-5">
                                <input type="text" id="txtUnitPriceE" class="form-control" value="0" min="0">
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Type</label>
                            <div class="col">
                                <select type="text" class="form-control" id="cboTypeE">
                                    <option value="Petty Cash">Petty Cash</option>
                                    <option value="Main Cash">Main Cash</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Remark</label>
                            <div class="col">
                                <textarea class="form-control" id="txtRemarkE" name="txtRemarkE" data-bs-toggle="autosize" style="overflow: hidden; overflow-wrap: break-word; resize: none;"></textarea>
                            </div>
                        </div>
                        <div class="col-6 mb-3 row">
                            <label class="col-4 col-form-label text-end">Account Head</label>
                            <div class="col">
                                <select id="cboAccountHeadE" class="form-select"></select>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="create();" id="btnSave">Update</button>
            </div>
        </div>
    </div>
</div>

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

<script>
	var today = new Date().toISOString().split('T')[0];
$(function() {
    getAccountHead();
	flatpickr("#dateFrom", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
	flatpickr("#dateTo", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    flatpickr("#txtDatePicker2", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    getAll();

});

$("#dateFrom, #dateTo, #cboType, #cboAccountHead").change(function() {
    getAll();
});

function getAccountHead(){

    $.ajax({
        url: APP_URL + "api/coa/get_all_rows.php",
        type: "POST",
        data: JSON.stringify({account_type: ""})

    }).done(function(data) {	
        $("#cboAccountHead").find("option").remove();
        $("#cboAccountHead").append("<option value = '' >Select account head</option>");
        $("#cboAccountHeadE").find("option").remove();
        $("#cboAccountHeadE").append("<option value = '' >Select account head</option>");
        $.each(data.records, function(i, v) {	
            $("#cboAccountHead").append("<option value= '" + v.account_code + "' head= '" + v.account_head + "'>" + v.account_code + " " + v.account_head + "</option>");	
            $("#cboAccountHeadE").append("<option value= '" + v.account_code + "' head= '" + v.account_head + "'>" + v.account_code + " " + v.account_head + "</option>");							
        });
    });
}

function getAll() {
    var df = $("#dateFrom").val();
    var dt = $("#dateTo").val();
    var account_type = $("#cboType").val();
    var account_code = $("#cboAccountHead").val();

    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/income/search.php",
            method: "GET",
            dataType: "json",
            data: {
                df: df,
                dt: dt,
                account_type: account_type,
                account_code: account_code
            },
            dataSrc: function(json) {
                // if (json.net_amount) {
                //     $("#totalAmount").text(parseFloat(json.net_amount).toLocaleString(undefined, { minimumFractionDigits: 2 }));
                // }
                return json.records;
            }
        },
        columns: [
			{ data: 0, visible:false },
			{ data: 1, className: 'text-left' },  
            { data: 2, className: 'text-nowrap'  }, 
            { data: 3, className: 'text-nowrap' }, 
            { data: 4, className: 'text-nowrap' }, 
            { data: 5, className: 'text-nowrap' }, 
            { data: 6 }, 
            {
                data: 7,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? '' : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            {
                data: 8,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? '' : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            {
                data: 9,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? '' : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            { data: 10 }, 
            {
                data: null,
                render: function(data, type, row) {
                    if (row[0] == 0) {
                        return ""; // Hide actions if row[0] is 0
                    }
                    return "<div class='btn-list flex-nowrap'>" +
                        "<div class='dropdown btn-group'>" +
                            "<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] + "\", this)'>Edit</a></li>" +
                                "<li><a class='dropdown-item text-danger' href='#' onclick='del(\"" + row[0] + "\", this)'>Delete</a></li>" +
                            "</ul>" +
                        "</div>" +
                    "</div>";
                }
            }


        ],
		columnDefs: [
            {
                targets: [1, 2, 4],
                createdCell: function (td, cellData, rowData, row, col) {
                    $(td).css('text-align', 'left');
                }
            },
            {
                targets: [2, 6], // Make columns 1, 2, and 3 searchable
                searchable: true
            },
            {
                targets: [0,1,3,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"]],
        order: [[1, 'asc'], [4, 'asc']],
        buttons: [
            {
                extend: 'csv',
                text: 'Export to CSV',
                className: 'buttons-csv',
                filename: 'ExpenseReport ' + df + ' to ' + dt,
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'excel',
                text: 'Export to Excel',
                className: 'buttons-excel',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'pdf',
                text: 'Export to PDF',
                className: 'buttons-pdf',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'print',
                text: 'Print Table',
                className: 'buttons-print',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            }
        ],
        drawCallback: function(settings) {
            let api = this.api();
            let data = api.rows({ search: 'applied' }).data();

            let totalAmount = 0;

            data.each(function(record) {
                // Ensure the amount is correctly parsed
                let total_amount = parseFloat(String(record[9]).replace(/[^0-9.-]+/g, '')) || 0;
                totalAmount += total_amount;
            });

            // Format and display the total
            $("#totalAmount").text(totalAmount.toLocaleString(undefined, { minimumFractionDigits: 2 }));
        }
    });

    $('#exportCSV').on('click', function() {
        table.button('.buttons-csv').trigger();
    });

    $('#exportExcel').on('click', function() {
        table.button('.buttons-excel').trigger();
    });

    $('#exportPDF').on('click', function() {
        table.button('.buttons-pdf').trigger();
    });

    $('#printTable').on('click', function() {
        table.button('.buttons-print').trigger();
    });
}

function edit(id,obj){
    $("#myModel").modal('show');
    var tr = $(obj).closest('tr'); 
    $("#txtID").val(id);

    $("#txtDatePicker2").val($(tr).find("td").eq(0).text());
    $("#txtVoucherNoE").val($(tr).find("td").eq(1).text());
    $("#cboTypeE").val($(tr).find("td").eq(2).text());
    $("#cboAccountHeadE").val($(tr).find("td").eq(3).text());
    $("#txtParticularE").val($(tr).find("td").eq(5).text());
	$("#txtQuantityE").val(parseFloat(tr.find("td").eq(6).text().trim().replace(/,/g, '')));
    $("#txtUnitPriceE").val($(tr).find("td").eq(7).text());
    $("#txtRemarkE").val($(tr).find("td").eq(9).text());
}	

function del(id, obj) {
    Swal.fire({
        title: 'Are you sure?',
        text: 'Do you really want to delete this item?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, keep it',
        customClass: {
            confirmButton: 'btn-danger',
            cancelButton: 'btn-primary'
        },
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                type: "POST",
                url: APP_URL + "api/income/delete.php",
                data: JSON.stringify({ id: id }),
                success: function(data) {
                    if (data == "deleted") {
                        getAll();
                    } else {
                        Swal.fire('Error!', 'Error on server side.', 'error');
                    }
                }
            });
        }
    });
}

function create(){ 
    var id = $("#txtID").val();
    var date = $("#txtDatePicker2").val();
    var voucher_no = $("#txtVoucherNoE").val();
    var type = $("#cboTypeE").val();
    var account_head = $("#cboAccountHeadE option:selected").attr("head");
    var account_code = $("#cboAccountHeadE").val();
    var particular = $("#txtParticularE").val();
    var quantity = parseFloat($("#txtQuantityE").val().replace(/,/g, ''));
    var price = parseFloat($("#txtUnitPriceE").val().replace(/,/g, ''));
    var remark = $("#txtRemarkE").val();

    if(particular.trim()=="" ){
        showAlert("Please fill particular.",'warning');
    }else if(account_head.trim()==""){
        showAlert("Please choose account head.",'warning');
    }
    else{
        $.ajax({
            url: APP_URL + "api/income/create_update.php",
            type: "POST",
            data: JSON.stringify({ id: id, date: date, voucher_no: voucher_no, type: type, account_head: account_head, account_code: account_code, particular:particular, quantity:quantity, price:price, remark:remark}),
        }).done(function(data){
            console.log(data);
            if(data.message=="created"){
                $("#myModel").modal('hide');
                showAlert("Successfully Saved.","success");
                $("#txtID").val("");
                $("#txtVoucherNoE").val("");
                $("#cboAccountHeadE").val("");
                $("#txtParticularE").val("");
                $("#txtQuantityE").val(1);
                $("#txtUnitPriceE").val("");
                $("txtRemarkE").val("");
                getAll();
            }else if(data.message=="updated"){
                $("#myModel").modal('hide');
                showAlert("Successfully Updated.","success");
                $(".btnSave").css("display", "block");
                $(".btnEdit").css("display", "none");
                $("#txtID").val("");
                $("#txtVoucherNoE").val("");
                $("#cboAccountHeadE").val("");
                $("#txtParticularE").val("");
                $("#txtQuantityE").val(1);
                $("#txtUnitPriceE").val("");
                $("txtRemarkE").val("");
                getAll();
            }else{
                showAlert("Error on server side.","warning");
            }
        });
    }   
}

function showAlert(message, type) {
    Swal.fire({
        title: type == 'success' ? 'Success' : 'Oops!',
        text: message,
        icon: type
    });
}
</script>
