<style>
    .dropdown-toggle {
        background-color: #4c0870;
        border-color: #4c0870;
    }

    .dropdown-toggle:hover {
        background-color: #4c0870;
        border-color: #4c0870;
    }

    #tableWithSearch thead tr>th {
        background-color: #4c0870;
        color: #fff;
        /*width: 6% !important;*/
        font-size: 12px;
    }

    #tableWithSearch thead tr th[class*='sorting_'] {
        color: #fff;
    }

    .bg-master-lighter {
        border: none;
        background-color: #fff;
        border-top: 1px solid #4c0870;
    }

    .btn-group {
        /*        background-color:#ed9421 !important;*/
        color: #fff;
    }

    .btn-default {
        border: none;
        background-color: #eee;
    }

    .btn-default:hover {
        background-color: #ed9421 !important;
        color: #fff;
        border: none;
    }

    /*    .table-responsive {

    overflow-x: visible; 
    }*/
    .dropdown-menu>li>a:hover,
    .dropdown-menu>li>a:focus {
        background-color: #ed9421 !important;
        ;
        color: #fff;

    }

    .btn-default:hover {
        background-color: #ed9421 !important;
        color: #fff;
        border: none;
    }

    /*    .complete ,.btn-group  .active{
    background-color:#ed9421 !important;
    color:#fff;
    }*/
    /*    .MonthPicker,.YearPicker,.FromToPicker,#PrePaidList_filter{
    display:none;
    }*/
    /*    #selected_entry{
    height:90px;
    color: black;
    margin-top:20px;
    font-size: 16px;
    padding-top: 2%;
    }*/
    /*    .select_table td{
    padding-left: 70px;
    }*/
</style>
<script src="<?php echo THEME_PATH; ?>/plugins/moment/moment.min.js"></script>

<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"><?php print($IsActual ? CommonLanguage::getMessage('actual_manual_jv_list') : CommonLanguage::getMessage('manual_jv_list')); ?></div>

            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <div class="row form-group">
                <div class="card-group horizontal " id="accordion" role="tablist" aria-multiselectable="true">
                    <div class="card card-default m-b-0">
                        <div class="card-header " role="tab" id="headingOne">
                            <h4 class="card-title">
                                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne" class="collapsed btn btn-search">
                                    <span class="filter-title"> <i class="fa fa-search"></i> <?php echo CommonLanguage::getMessage('advanced_search'); ?></span>
                                </a>
                            </h4>
                        </div>
                        <div id="collapseOne" class="collapse" role="tabcard" aria-labelledby="headingOne" aria-expanded="false" style="">
                            <div class="card-block">
                                <div class="row p-15">
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                                        <input id="range_date" type="text" class="form-control" readonly name="range_date">
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('due_date') ?></label>
                                        <input id="range_duedate" type="text" class="form-control" readonly name="range_duedate">
                                    </div>

                                    <div class="col-md-3">
                                        <div class="row">
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_jv') ?></label></div>
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_jv') ?></label></div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6"><input type="number" min="1" id="from_jv" class="form-control full-width"></div>
                                            <div class="col-md-6"><input type="number" min="1" id="to_jv" class="form-control full-width"></div>
                                        </div>

                                    </div>
                                    <div class="col-md-3">
                                        <div class="row">
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_account') ?></label></div>
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_account') ?></label></div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6"><input type="number" min="1" id="from_account" class="form-control full-width"></div>
                                            <div class="col-md-6"><input type="number" min="1" id="to_account" class="form-control full-width"></div>
                                        </div>

                                    </div>
                                </div>
                                <div class="row p-15">
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" />
                                    </div>

                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('multi_accounts') ?></label>
                                        <input type="hidden" class="full-width" id="multi_accounts" />
                                    </div>
                                    <div class="col-md-3 trans_curr_div">
                                        <label><?php echo CommonLanguage::getMessage('trans_in_currency'); ?></label>
                                        <input type="hidden" class="full-width" id="trans_in_currrency" />
                                        <?php // echo Forms::CurrencyDropDown(1, 'complete') 
                                        ?>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="row">
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_amount') ?></label></div>
                                            <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_amount') ?></label></div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6"><input type="number" min="0" step="any" id="from_amount" class="form-control full-width"></div>
                                            <div class="col-md-6"><input type="number" min="0" step="any" id="to_amount" class="form-control full-width"></div>
                                        </div>

                                    </div>
                                </div>
                                <div class="row p-15">
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('entry_type') ?></label>
                                        <input type="hidden" class="full-width" id="ref_type" />
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('family_accounts') ?></label>
                                        <input type="hidden" class="full-width" id="family_acc" />
                                    </div>
                                    <div class="col-md-3">
                                        <label><?php echo CommonLanguage::getMessage('projects') ?></label>
                                        <input type="hidden" class="full-width" id="project_ids" />
                                    </div>
                                    <?php if ($IsActual) { ?>
                                        <div class="col-md-1">
                                            <label><?php print CommonLanguage::getMessage('actual_only'); ?></label>
                                            <input type="checkbox" id="actual_only" name="actual_only" />
                                        </div>
                                    <?php } ?>
                                </div>
                                <div class="row p-15">
                                    <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 p-15">
                                    <div class="col-md-2 pull-right">
                                        <button id="Generate_Report" type="button" class="btn btn-complete pull-right" data-toggle="dropdown" aria-expanded="false">
                                            <?php print CommonLanguage::getMessage('generate_report'); ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>

            <div class="row">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover demo-table-search" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center"><?php print CommonLanguage::getMessage('jv'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('reference'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('account'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('account_name'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('description'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('debit'); ?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('credit'); ?></th>
                                <th class="text-center no-print"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                        <tfoot>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th><?php echo CommonLanguage::getMessage('total') . ':' ?></th>
                                <th><span id="total_debit"></span>&nbsp&nbsp<span class="CurrencyIndicator"><?php echo smc_session()['local_currency_symbol'] ?></span></th>
                                <th>
                                    <div><span id="total_credit"></span>&nbsp&nbsp<span class="CurrencyIndicator"><?php echo smc_session()['local_currency_symbol'] ?></span></div>
                                </th>

                                <th></th>
                            </tr>
                            <tr>
                                <th><?php if ($permissions->hasPermission($IsActual ? "delete_multi_act_manual_jv" : "delete_multi_manual_jv")) { ?>
                                        <button class="btn btn-complete m-b-10 full-width" id="delete_all"><?php echo CommonLanguage::getMessage('Delete'); ?></button>
                                    <?php }
                                    if ($permissions->hasPermission($IsActual ? "convert_multi_act_manual_jv_to_official" : "convert_multi_manual_jv_to_actual")) { ?>
                                        <button class="btn btn-complete full-width" id="change_actual"><?php echo CommonLanguage::getMessage($IsActual ? 'to_official' : 'to_actual'); ?></button>
                                    <?php } ?>
                                </th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th><?php echo CommonLanguage::getMessage('balance') . ':' ?></th>
                                <th>
                                    <div class="text-center"><span id="total_balance"></span>&nbsp&nbsp<span class="CurrencyIndicator"><?php echo smc_session()['local_currency_symbol'] ?></span></div>
                                </th>

                                <th></th>
                                <th></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

</div>
</div>
<div class="modal fade" id="ConfirmDelete" 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_record') ?>&nbsp;<span id="rec_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="rec_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">
                <div id="change_act_alert"></div>
                <h4 class="modal-title"><?php print CommonLanguage::getMessage($IsActual ? 'to_official_alert' : 'to_actual_alert') ?></h4>
            </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 is_actual = <?php echo json_encode($IsActual); ?>,
        jv_id = <?php echo json_encode($jv_id); ?>,
        title = <?php echo json_encode($IsActual ? CommonLanguage::getMessage('act_daily_journals') : CommonLanguage::getMessage('daily_journal')); ?>,
        startDate = '',
        endDate = '',
        startDueDate = '',
        endDueDate = '',
        rec_to_delete = [],
        rec_nb_del = [],
        rec_to_change = [],
        rec_nb_act = [];
    $(function() {
        build_select2($("#job_id"), "ACCAjax/JobSearch", 1)
        //        build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs", 1)
        build_select2($("#trans_in_currrency"), "xhr/CurrencySearch", 1)
        build_select2($("#multi_accounts"), ("xhr/accIDSearch?type=Payment"), 1)
        build_select2($("#ref_type"), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype", 1)
        build_select2($("#family_acc"), "xhr/CommonSearch?col_id=family_id&col_name=family_name&table=tbl_family_accounts", 1)
        build_select2($("#project_ids"), "ACCAjax/projectSearch", 1)
        new Switchery($("#actual_only").get(0), {
            color: $.Pages.getColor("complete")
        })
        build_select2($("#search_branch_id"), "xhr/CommonSearch?col_name=branch_name&col_id=branch_id&table=tbl_organization_branches");


        $("input[name=range_date]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function(start, end, label) {
            //            console.log(label)

        });
        $('input[name="range_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDate = picker.endDate.format('YYYY-MM-DD');
            //            console.log('here')
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        });
        $('input[name="range_date"]').on('cancel.daterangepicker', function(ev, picker) {
            //            console.log('there')
            window.startDate = ''
            window.endDate = ''
            $(this).val('');
        });

        $("input[name=range_duedate]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function(start, end, label) {
            //            window.startDueDate = start.format("YYYY-MM-DD"),
            //                    window.endDueDate = end.format("YYYY-MM-DD");
        });
        $('input[name="range_duedate"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDueDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDueDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        });
        $('input[name="range_duedate"]').on('cancel.daterangepicker', function(ev, picker) {
            window.startDueDate = ''
            window.endDueDate = ''
            $(this).val('');
        });

        $("#Generate_Report").on("click", function() {
            ChangeTable();
        })

        if (jv_id != 0) {
            $("#from_jv").val(jv_id),
                $("#to_jv").val(jv_id)
        }
        ChangeTable()

        //        $("#tableWithSearch").on("click", ".delete_jv", function () {
        //            var entry_value = $(this).parents('.Action').attr('data-id');
        //            var data = {
        //                id: entry_value,
        //                is_actual: is_actual
        //            };
        //            IncludeDeleteModal(common_delete_modal, data, function () {
        //                ChangeTable();
        //            }, "ACCAjax/delete_jv");
        //        })


        $("#delete_all").on("click", function() {
            rec_to_delete = []
            rec_nb_del = []
            $("#tableWithSearch .del_td:checked").each(function() {
                rec_to_delete.push($(this).attr("data-id"));
                rec_nb_del.push($(this).attr("data-nb"));
            })
            if ($("#tableWithSearch .del_td:checked").length > 0) {
                $("#rec_nb").html(rec_nb_del.join())
                $("#ConfirmDelete").modal("show")
            }
        })
        $("#tableWithSearch").on("click", ".delete_jv", function() {
            $('#rec_delete').attr('disabled', false);
            rec_to_delete = [$(this).parents(".Action").attr("data-id")];
            $("#rec_nb").html($(this).parents("tr").find("td:eq(0)").text())
            $("#ConfirmDelete").modal("show");
        })
        $("#rec_delete").on("click", function() {
            $.ajax({
                url: "ACCAjax/delete_jv",
                method: "GET",
                data: {
                    ids: rec_to_delete,
                    is_actual: is_actual
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'ok') {
                            $("#delete_alert").attr("class", "alert alert-success").html('<?php echo CommonLanguage::getMessage('Deleted_Successfully') ?>')
                            rec_to_delete = []
                            ChangeTable()
                            setTimeout(function() {
                                $("#ConfirmDelete").modal("hide")
                                $("#delete_alert").addClass("hidden")
                            }, 1500)
                        } else {
                            $("#delete_alert").attr("class", "alert alert-danger").html(v1.responseText)
                        }
                    }
                }
            });

        })
        $("#tableWithSearch").on("click", "input.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.del_td").prop("checked", is_checked);
            }
        });
        $("#tableWithSearch").on("click", ".change_actual", function() {
            rec_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() {
            rec_to_change = []
            rec_nb_act = []
            $("#tableWithSearch .del_td:checked").each(function() {
                rec_to_change.push($(this).attr("data-id"));
                rec_nb_act.push($(this).attr("data-nb"));
            })
            if ($("#tableWithSearch .del_td:checked").length > 0) {
                $("#act_nb").html(rec_nb_act.join())
                $("#change_actual_modal").modal("show")
            }
        })
        $("#change_act_btn").on("click", function() {
            $.ajax({
                url: "ACCAjax/change_jv_actual",
                method: "POST",
                data: {
                    id: rec_to_change,
                    is_actual: is_actual == 1 ? 0 : 1
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'OK') {
                            $("#change_act_alert").attr("class", "alert alert-success").html('<?php echo CommonLanguage::getMessage('Submitted_Successfully') ?>')
                            rec_to_change = []
                            ChangeTable()
                            setTimeout(function() {
                                $("#change_actual_modal").modal("hide")
                                $("#change_act_alert").addClass("hidden")
                            }, 1500)
                        } else {
                            $("#change_act_alert").attr("class", "alert alert-danger").html(v1.responseText)
                        }
                    }
                }
            })
        })
    })




    function ChangeTable() {
        var MyData = {
            trans_type: ['mjv'],
            Is_Actual: is_actual,
            from_jv: $("#from_jv").val(),
            to_jv: $("#to_jv").val(),
            from_account: $("#from_account").val(),
            to_account: $("#to_account").val(),
            job_ids: $("#job_id").val(),
            project_ids: $("#project_ids").val(),
            multi_accounts: $("#multi_accounts").val(),
            Transaction_Date_From: startDate,
            Transaction_Date_To: endDate,
            due_date_from: startDueDate,
            due_date_to: endDueDate,
            trans_currency: $("#trans_in_currrency").val(),
            from_amount: $("#from_amount").val(),
            to_amount: $("#to_amount").val(),
            ref_type: $("#ref_type").val(),
            family_acc: $("#family_acc").val(),
            search_branch_id: $("#search_branch_id").val(),
            jv_id: jv_id,
            actual_only: $("#actual_only").is(":checked") ? 1 : 0
        }

        buildTotals(MyData)
        RebuildDataTable(title, [0, 1, 2, 3, 4, 5, 6], 'ACCAjax/manual_jv_list_ajax', MyData, '#tableWithSearch', [0, 1, 5, 8])
    }

    function buildTotals(data) {
        $.ajax({
            url: "ACCAjax/getdilyJVsTotals",
            method: "GET",
            dataType: 'json',
            data: {
                data: data
            },
            complete: function(v1, v2) {
                 if (v2 == "success") {
                    var total_arr = v1.responseJSON;

                    $("#total_debit").html(AddCommas(public_round_number(parseFloat(total_arr['Debit']['amount'] || 0))))
                    $("#total_credit").html(AddCommas(public_round_number(parseFloat(total_arr['Credit']['amount'] || 0))))
                    $("#total_balance").html(AddCommas(public_round_number(parseFloat((total_arr['Debit']['amount'] - total_arr['Credit']['amount']) || 0))))

                    //                    $("#total_debit_second").html(AddCommas(parseFloat(total_arr['Debit']['second_amount'] || 0).toXFixed(3)))
                    //                    $("#total_credit_second").html(AddCommas(parseFloat(total_arr['Credit']['second_amount'] || 0).toXFixed(3)))
                    //                    $("#total_balance_second").html(AddCommas(parseFloat((total_arr['Debit']['second_amount'] - total_arr['Credit']['second_amount']) || 0).toXFixed(3)))
                }
            }
        })
    }
</script>