<style>
    .btn.btn-default.active {
        background-color: #6d5baf;
        color: white;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title">
                <h4 class="bold"><?php echo $title; ?> </h4>
            </div>
            <div class="row">
                <div id="ViewMode">
                    <span style="margin:0 13px"><?php print CommonLanguage::getMessage('type'); ?>: </span>
                    <div class="btn-group" data-toggle="buttons">
                        <label class="btn btn-default active">
                            <input type="radio" name="ViewType" value="1" checked=""><?php print CommonLanguage::getMessage('Daily'); ?>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="ViewType" value="2"><?php print CommonLanguage::getMessage('monthly'); ?>
                        </label>
                        <label class="btn btn-default">
                            <input type="radio" name="ViewType" value="3"><?php print CommonLanguage::getMessage('yearly'); ?>
                        </label>
                    </div>
                </div>
                <div class="col-md-3 <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">
                    <label><?php echo CommonLanguage::getMessage('choose_branch') ?></label>
                    <input id="search_branch_id" type="hidden" class="full-width" name="search_branch_id" >
                </div>

            </div>
            <div class="row">
                <div class="col-md-12 input-group m-b">
                    <div id="Date_Group" class="form-group form-group-default input-group col-md-3 pull-right ">
                        <label class="fade"><?php print CommonLanguage::getMessage('Date'); ?></label>
                        <input id="Daily_Date" name="Daily_Date" class="form-control" value="<?php echo ($today); ?>" aria-required="true" aria-invalid="false">
                        <input id="Month_Date" name="Month_Date" class="form-control hidden" data-date-format="yyyy-mm" value="<?php echo ($year . '/' . $monthName); ?>" aria-required="true" aria-invalid="false">
                        <input id="Year_Date" name="Year_Date" class="form-control hidden" data-date-format="yyyy" value="<?php echo ($year); ?>" aria-required="true" aria-invalid="false">
                        <span class="input-group-addon bg-primary"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 table-responsive" id="MyTable">
                    <table class="table table-bordered inventory" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center" style="width:5%"><input type="checkbox" class="ret_check_all_td pull-left multi_delete" />#</th>
                                <th class="text-center" style="width:10%"><?php echo CommonLanguage::getMessage("invoice_nb"); ?></th>
                                <th class="text-center" style="width:15%"><?php echo CommonLanguage::getMessage($IsVendor ? "vendor" : "customer"); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('total'); ?></th>
                                <th class="text-center" style="width:30%"><?php print CommonLanguage::getMessage('note'); ?></th>
                                <th class="text-center" style="width:15%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                        <tfoot>
                            <th>
                                <?php if ($permissions->hasPermission($is_actual ? ($IsVendor ? "act_ret_vend_multi_delete" : "act_ret_cust_multi_delete") : ($IsVendor ? ($is_noqty ? "multi_delete_ret_supp_noqty" : "ret_vend_multi_delete") : ($is_noqty ? "multi_delete_ret_cust_noqty" : "ret_cust_multi_delete")))) { ?>
                                    <button class="btn btn-primary m-b-10 full-width" id="delete_all"><?php echo CommonLanguage::getMessage('Delete'); ?></button>
                                <?php }
                                if ($permissions->hasPermission($is_actual ? ($IsVendor ? 'act_ret_vend_multi_to_official' : 'act_ret_cust_multi_to_official') : ($IsVendor ? ($is_noqty ? "multi_ret_supp_noqty_to_act" : "ret_vend_multi_to_actual") : ($is_noqty ? "multi_ret_cust_noqty_to_act" : "ret_cust_multi_to_actual")))) { ?>
                                    <button class="btn btn-primary full-width" id="change_actual"><?php echo CommonLanguage::getMessage($is_actual ? 'to_official' : 'to_actual'); ?></button>
                                <?php } ?>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="ConfirmDeleteRet" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header text-left">
                <h4 class="modal-title bold"><?php print CommonLanguage::getMessage('Confirm_Delete') ?></h4>
                <div id="delete_alert"></div>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12 m-t-10">
                        <p><?php print CommonLanguage::getMessage('about_delete_inv') ?>&nbsp;<span id="ret_nb" class="bold red-star"></span></p>
                        <p><?php print CommonLanguage::getMessage('Proceed_Delete') ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-danger width-auto" id="inv_delete"><?php print CommonLanguage::getMessage('delete') ?></button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="change_actual_modal" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><?php print CommonLanguage::getMessage($is_actual ? 'to_official_alert' : 'to_actual_alert') ?></h4>
                <div id="change_act_alert"></div>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12 m-t-10">
                        <span id="act_nb" class="bold red-star"></span>
                        <p><?php print CommonLanguage::getMessage('proceed') . ' ?' ?></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-danger width-auto" id="change_act_btn"><?php print CommonLanguage::getMessage('proceed') ?></button>
            </div>
        </div>
    </div>
</div>
<script>
    var IsVendor = <?php echo $IsVendor ? "true" : "false" ?>,
        IsSales = <?php echo $IsVendor ? "false" : "true" ?>,
        IsActual = <?php echo $is_actual ? "true" : "false" ?>,
        is_noqty = <?php echo json_encode($is_noqty); ?>,
        title = <?php echo json_encode(CommonLanguage::getMessage($IsVendor ? 'return_vendor_list' : 'return_customer_list')); ?>;
    Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    data_linked_to_app = <?php echo json_encode(CommonLanguage::getMessage('data_linked_to_app')); ?>;
    Deleted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Deleted_Successfully')); ?>;
    var ret_to_delete = [],
        ret_nb_del = [],
        ret_to_change = [],
        ret_nb_act = [];
    $(function() {
        var optns = {
            cb_ft: function(dt_optns) {
                // stop sorting for column since on click on header checkbox the sorting is triggered
                dt_optns.columnDefs.push({
                    targets: [0],
                    "orderable": false
                });
            },
        };
        var data_session = get_storage_element(page_link);
        //        console.log(data_session.month_date)
        if (data_session.daily_date != undefined && data_session.daily_date != '')
            $("#Daily_Date").val(data_session.daily_date)
        if (data_session.month_date != undefined && data_session.month_date != '')
            $("#Month_Date").val(data_session.month_date)
        if (data_session.year_date != undefined && data_session.year_date != '')
            $("#Year_Date").val(data_session.year_date)
        build_select2($("#search_branch_id"), "xhr/CommonSearch?col_name=branch_name&col_id=branch_id&table=tbl_organization_branches");

        var dataArr = {
            freq: parseInt($("#ViewMode input:checked").val()),
            Date: $("#Daily_Date").val(),
            search_branch_id: $("#search_branch_id").val(),
            Is_Vendor: IsVendor ? 1 : 0,
            IsActual: IsActual ? 1 : 0,
            is_noqty: is_noqty
        }

        RebuildDataTable(title, [0, 1], 'InventoryAjax/ReturnCustomerList', dataArr, '', '', optns);
        
        //Setting Daily datepicker
        $("#Daily_Date").datepicker({
            autoclose: true
        })
        //Setting Monthly datepicker
        $("#Month_Date").datepicker({
            autoclose: true,
            viewMode: "months",
            minViewMode: "months"
        })
        //Setting Yearly datepicker
        $("#Year_Date").datepicker({
            autoclose: true,
            viewMode: "years",
            minViewMode: "years"
        })
        $("#ViewMode label").on("click", function() {
            setTimeout(function() {
                var freq = $("#ViewMode label.active> input").val();
                if (freq == 1) {
                    $("#Daily_Date").removeClass("hidden") //to show daily datepicker
                    $("#Month_Date").addClass("hidden") //to hide monthly datepicker
                    $("#Year_Date").addClass("hidden") //to hide yearly datepicker
                } else //freq Condition for monthly with id 2
                    if (freq == 2) {
                        $("#Daily_Date").addClass("hidden") //to hide daily datepicker
                        $("#Month_Date").removeClass("hidden") //to show monthly datepicker
                        $("#Year_Date").addClass("hidden") //to hide yearly datepicker
                    } else //freq condition for yearly with id 3
                        if (freq == 3) {
                            $("#Daily_Date").addClass("hidden") //to hide daily datepicker
                            $("#Month_Date").addClass("hidden") //to hide monthly datepicker
                            $("#Year_Date").removeClass("hidden") //to show yearly datepicker
                        }
                AjaxReq(freq);
            }, 200)
        })

        $("#tableWithSearch").on("click", ".copy_to_invoice_purchase", function() {
            var type = IsSales ? 'inv' : 'pur';
            //            console.log(type)
            $("#invoice_type_id").val('').attr('data-select-name', '')
            build_select2($("#invoice_type_id"), "xhr/invoice_type_search?type=" + type + "&is_actual=" + (IsActual ? 1 : 0));

        })



        $("#tableWithSearch").on("click", "input.ret_check_all_td", function(e) {
            var is_checked = $(this).is(":checked");
            var row = $("#tableWithSearch").dataTable().fnGetNodes();
            for (var i = 0; i < row.length; i++) {
                $(row[i]).find("input.ret_del_td").prop("checked", is_checked);
            }
        });
        $("#ViewMode label input[name=ViewType][value=" + (data_session.freq) + "]").trigger("click")
        /**********************************************************************Begining of onChange datepicker*************************************/
        $("#Daily_Date,#Month_Date,#Year_Date").on("changeDate", function(e) {
            setTimeout(function() {
                var freq = $("#ViewMode label.active> input").val();
                AjaxReq(freq); //Rebuild table based on selected date
            }, 200)
        }) //End of onChange datepicker

        $("#tableWithSearch").on("click", ".change_actual", function() {
            ret_to_change = [$(this).parents(".Action").attr("data-id")];
            $("#act_nb").html($(this).parents("tr").find("td:eq(0)").text())
            $("#change_actual_modal").modal("show")
        })
        $("#change_actual").on("click", function() {
            ret_to_change = []
            ret_nb_act = []
            $("#tableWithSearch .ret_del_td:checked").each(function() {
                ret_to_change.push($(this).attr("data-id"));
                ret_nb_act.push($(this).attr("data-nb"));
            })
            if ($("#tableWithSearch .ret_del_td:checked").length > 0) {
                $("#act_nb").html(ret_nb_act.join())
                $("#change_actual_modal").modal("show")
            }
        })
        $("#change_act_btn").on("click", function() {
            $.ajax({
                url: "InventoryAjax/change_return_actual",
                method: "POST",
                dataType: 'json',
                data: {
                    id: ret_to_change,
                    is_actual: (IsActual ? 0 : 1),
                    is_customer: (IsVendor ? 0 : 1)
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseJSON[0] == 'OK') {
                            $("#change_act_alert").attr("class", "alert alert-success").html(Submitted_Successfully + '<br>' + v1.responseJSON[1])
                            ret_to_change = []
                            AjaxReq()
                            if (v1.responseJSON[1] == '') {
                                setTimeout(function() {
                                    $("#change_actual_modal").modal("hide")
                                    $("#change_act_alert").addClass("hidden")
                                }, 1500)
                            }
                        } else {
                            $("#change_act_alert").attr("class", "alert alert-danger").html(v1.responseJSON[0])
                        }
                    }
                }
            })
        })
        $('#search_branch_id').on('change', function () {
            AjaxReq();
        });

        $("#delete_all").on("click", function() {
            ret_to_delete = []
            ret_nb_del = []
            $("#tableWithSearch .ret_del_td:checked").each(function() {
                ret_to_delete.push($(this).attr("data-id"));
                ret_nb_del.push($(this).attr("data-nb"));
            })
            if ($("#tableWithSearch .ret_del_td:checked").length > 0) {
                $("#ret_nb").html(ret_nb_del.join())
                $("#ConfirmDeleteRet").modal("show")
            }
        })
        $("#tableWithSearch").on("click", ".delete_inv", function() {
            ret_to_delete = [$(this).parents(".Action").attr("data-id")];
            $("#ret_nb").html($(this).parents("tr").find("td:eq(0)").text())
            if ($(this).attr('data-invoice-app-id') != 0)
                $("#delete_alert").attr("class", "alert alert-danger").html(data_linked_to_app)
            $("#ConfirmDeleteRet").modal("show")
        })
        $("#inv_delete").on("click", function() {
            var data = ret_to_delete
            $.ajax({
                url: "InventoryAjax/delete_return",
                method: "POST",
                data: {
                    ids: data,
                    is_purchase: IsVendor ? 1 : 0
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'OK') {
                            $("#delete_alert").attr("class", "alert alert-success").html(Deleted_Successfully)
                            ret_to_delete = []
                            AjaxReq()
                            setTimeout(function() {
                                $("#ConfirmDeleteRet").modal("hide")
                                $("#delete_alert").addClass("hidden")
                            }, 1500)
                        } else {
                            $("#delete_alert").attr("class", "alert alert-danger").html(v1.responseText)
                        }
                    }
                }
            })
        });
        $('#ConfirmDeleteRet').on('hidden.bs.modal', function() {
            $("#delete_alert").attr("class", "").html('')
        });
    })

    function AjaxReq(freq) {
        var freq = parseInt($("#ViewMode input:checked").val());
        MyCurrentDate(freq); //return current date
        var CurrentDate = {
            freq: freq,
            Date: MyDate,
            Is_Vendor: (IsVendor ? 1 : 0),
            IsActual: (IsActual ? 1 : 0),
            daily_date: $("#Daily_Date").val(),
            month_date: $("#Month_Date").val(),
            year_date: $("#Year_Date").val(),
            search_branch_id: $("#search_branch_id").val(),
            is_noqty: is_noqty

        };
        set_storage_element(page_link, CurrentDate)
        var optns = {
            cb_ft: function(dt_optns) {
                // stop sorting for column since on click on header checkbox the sorting is triggered
                dt_optns.columnDefs.push({
                    targets: [0],
                    "orderable": false
                });
            },
        };
        //        CurrentDate.freq = freq;
        //        CurrentDate.Date = MyDate;
        //        CurrentDate.Is_Vendor = IsVendor ? 1 : 0;
        //        CurrentDate.IsActual = IsActual ? 1 : 0;
        RebuildDataTable(title, [0, 1], 'InventoryAjax/ReturnCustomerList', CurrentDate, '', '', optns);
    }
    /******************Function to return Current Date based on selected frequency**************************************************/
    function MyCurrentDate(freq) {
        var MyDate;
        if (freq == 1) {
            window.MyDate = $("#Daily_Date").val()
        } else
        if (freq == 2) {
            window.MyDate = [moment($("#Month_Date").val()).format("YYYY"), moment($("#Month_Date").val()).format("MM"), moment($("#Month_Date").val()).format("DD")]
        } else
        if (freq == 3) {
            window.MyDate = [moment($("#Year_Date").val()).format("YYYY"), moment($("#Year_Date").val()).format("MM"), moment($("#Year_Date").val()).format("DD")]
        }
    }
</script>
<?php
include 'Views/Inventory/general_invoice_type_modal.php';
