<style>
    #tableWithSearch thead tr >th{
        background-color:#4c0870;
        color:#fff;
    }
    #tableWithSearch thead tr th[class*='sorting_'] {
        color: #fff;
    }
    .fa-trash{
        cursor:pointer;
    }
</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 class="col-md-3" >
                    <label><?php echo CommonLanguage::getMessage('choose_customer'); ?></label>
                    <input class="current_customer_id full-width" id="current_customer_id" name="current_customer_id" type="hidden" value="" data-select-name='' required />
                </div>
                <div class="col-md-3" >
                    <label><?php echo CommonLanguage::getMessage('status'); ?></label>
                    <select name="status_id" id="status_id" class="full-width" data-init-plugin="select2">
                        <option value=""><?php echo CommonLanguage::getMessage('All'); ?></option>
                        <option value="1"><?php echo CommonLanguage::getMessage('not_paid'); ?></option>
                        <option value="2"><?php echo CommonLanguage::getMessage('partially_paid'); ?></option>
                        <option value="3"><?php echo CommonLanguage::getMessage('paid'); ?></option>
                    </select>
                </div> 
                <div class="col-md-3">
                    <label><?php echo CommonLanguage::getMessage('due_date'); ?></label>
                    <div class="input-group" >
                        <input id="From_To_Date" type="text" class="form-control" name="From_To_Date" autocomplete="off">
                        <span class="input-group-addon bg-complete"><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">
                    <table class="table table-bordered table-hover" id="tableWithSearch">
                        <thead>
                            <tr>
                                <th class="text-center" style="width:2%" >#</th>
                                <th class="text-center" style="width:4%" > <?php print CommonLanguage::getMessage('customer_name'); ?></th>
                                <th class="text-center" style="width:4%" > <?php print CommonLanguage::getMessage('due_date'); ?></th>
                                <th class="text-center" style="width:5%" > <?php print CommonLanguage::getMessage('amount'); ?></th>
                                <th class="text-center" style="width:20%" > <?php print CommonLanguage::getMessage('paid_amount'); ?></th>
                                <th class="text-center" style="width:5%" > <?php print CommonLanguage::getMessage('remaining_amount'); ?></th>
                                <th class="text-center no-print" style="width:5%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="add_payment_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="text-left bold "><?php echo CommonLanguage::getMessage('add_payment'); ?></h5>
            </div>
            <div class="modal-body">
                <form id="payment_form" method="POST" onsubmit="return false">
                    <input type="hidden" name="currency_id" id="currency_id" />
                    <input type="hidden" name="customer_id" id="customer_id" />
                    <input type="hidden" name="bill_detail_id" id="bill_detail_id" />
                    <input type="hidden" name="bill_id" id="bill_id" />
                    <input type="hidden" name="total_amount" id="total_amount" />
                    <input type="hidden" name="paid_amount" id="paid_amount" />
                    <div class="row">
                        <?php echo Forms::AlertDiv('payment_alert'); ?>
                    </div>
                    <div class="row form-group ">
                        <div class="col-md-12">
                            <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                            <span class="red-star">*</span>
                            <input type="text" id="payment_date" name="payment_date" value="<?php echo $today; ?>" class="form-control " autocomplete="off" required>
                        </div>
                    </div>
                    <div id="payment_rows">
                        <div class="row form-group ">
                            <div class="col-md-3">
                                <label><?php print CommonLanguage::getMessage('payment_type'); ?></label>
                            </div>

                            <div class="col-md-3">
                                <label><?php print CommonLanguage::getMessage('amount'); ?> <span id="currency_symbol" class="<?php echo smc_session()['default_setting']['activate_schedule_bill_multi_currency'] == 1 ? 'hidden' : ' ' ?>"></span></label>
                                <span class="red-star">*</span>
                            </div>
                            <div class="col-md-3 <?php echo smc_session()['default_setting']['activate_schedule_bill_multi_currency'] == 0 ? 'hidden' : ' ' ?>">
                                <label><?php print CommonLanguage::getMessage('currency'); ?> </label>
                                <span class="red-star">*</span>
                            </div>
                        </div>
                        <div class="row form-group row-item">
                            <div class="col-md-3">
                                <input class="payment_type full-width"  name="payment_type" type="hidden"  value="<?php echo smc_session()['user_accounts']['cash_account_id'] ?>" data-select-name='<?php echo smc_session()['user_accounts']['c_name'] ?>' />
                            </div>

                            <div class="col-md-3">
                                <input type="number" class="payment_amount form-control" name="payment_amount"  autocomplete="off" min="0" required>
                            </div>
                            <div class="col-md-3 <?php echo smc_session()['default_setting']['activate_schedule_bill_multi_currency'] == 0 ? 'hidden' : ' ' ?>">
                                <select class="full-width payment_currency" data-init-plugin="select2">
                                    <?php foreach ($currency_list as $currency): ?>
                                        <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>"  value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                    <?php endforeach; ?>
                                </select>             
                            </div>
                            <div class="col-md-3 <?php echo smc_session()['default_setting']['activate_schedule_bill_multi_currency'] == 0 ? 'hidden' : ' ' ?>">
                                <div class="col-xs-12 AddButtons ">
                                    <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px;cursor:pointer;"></span>
                                    <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;cursor:pointer;"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row form-group ">
                        <div class="col-md-12">
                            <label><?php print CommonLanguage::getMessage('user_ref'); ?></label>
                            <span class="red-star">*</span>
                            <input type="text" id="user_ref" name="user_ref" class="form-control " autocomplete="off"  required>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn btn-complete" id="submit_payment"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('paymentLoader'); ?>
        </div>
    </div>
</div>
<script>
    var is_actual = <?php echo $is_actual ? "true" : "false" ?>, today = <?php echo json_encode($today) ?>,
            local_currency = <?php echo json_encode(smc_session()['default_setting']['local_currency']) ?>,
            activate_multi_currency = <?php echo json_encode(smc_session()['default_setting']['activate_schedule_bill_multi_currency']) ?>,
            CurrencyRate = <?php echo json_encode($Extable); ?>;
    $(function () {
        build_select2($("input.payment_type"), ("xhr/accIDSearch"))
        $('#payment_date').datepicker({autoclose: true})
        build_select2($("#current_customer_id"), ("xhr/customerSearch"))

        ChangeTable()
         $("input[name=From_To_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')]
            }, locale: {
                cancelLabel: 'Clear'
            }, allowEmpty: false,
            autoUpdateInput: false
        });

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

        $("#payment_rows").on("click", ".AddButtons > .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var Parent = $(this).parents(".row-item"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            $(".select2-container", NewItem).empty().remove()
            NewItem.find("input.payment_type").val('').attr('data-select-name', '')
            build_select2($("input.payment_type", NewItem), ("xhr/accIDSearch"))
            NewItem.find("select.payment_currency").show().select2()
            $(".select2-container", NewItem).show();
        })
        $("#payment_rows").on("click", ".AddButtons > .fa-minus-circle", function (e) {
            $(this).closest(".row-item").empty().remove();
            $("#payment_rows").each(function () {
                $(".AddButtons > .fa-minus-circle", $(this).parent()).css({"display": $(".AddButtons", $(this).parent()).length <= 1 ? "none" : "inline-block"})
            });
        })


        $("#current_customer_id,#status_id").on('change', function () {
            ChangeTable();
        });
        $("#tableWithSearch").on("click", ".delete_bill_payment", function () {
            var bill_id = $(this).attr('data-bill-id'), bill_detail_id = $(this).attr('data-bill-detail-id'),
                    transaction_nb = $(this).attr('data-transaction-nb')
            IncludeDeleteModal(common_delete_modal, {JV_ID: transaction_nb, main_id: bill_id,
                sub_id: bill_detail_id,currency_id:$("#currency_id").val()}, function () {
                ChangeTable();
            }, "ACCAjax/deletePaymentScheduleBills");
        })
        $('#tableWithSearch').on('click', '.add_payment_btn', function () {
            var parent = $(this).parents('tr');
            $('#bill_id').val($(this).attr('data-bill-id'));
            $('#payment_date').val(today);
            $('#bill_detail_id').val($(this).attr('data-bill-detail-id'));
            $('#currency_id').val($(this).attr('data-currency-id'));
            $('#customer_id').val($(this).attr('data-customer-id'));
            $('#currency_symbol').html('(' + $(this).attr('data-currency-symbol') + ')');
            $('#total_amount').val($(this).attr('data-amount'));
            $("#payment_type").val('<?php echo smc_session()['user_accounts']['cash_account_id']; ?>').attr('data-select-name', '<?php echo smc_session()['user_accounts']['c_name']; ?>');
            build_select2($("#payment_type"), ("xhr/accIDSearch"));
            CommonViewById('ACCAjax/getTotalPaymentBill', {bill_id: $('#bill_id').val(),
                bill_detail_id: $('#bill_detail_id').val()},
                    '#paymentLoader', function (response) {
                        $('#paid_amount').val(response)
                        if (activate_multi_currency == 0)
                            $('.payment_amount').val(parseFloat($('#total_amount').val()) - parseFloat($('#paid_amount').val()))
                        $('select.payment_currency').val($('#currency_id').val()).select2()
                    });
        });
        $("#add_payment_modal").on("hidden.bs.modal",function(){
            $(".row-item:gt(0)").remove()
        })
        $("#submit_payment").on("click", function () {
            if (!$("#payment_form").valid())
                return;
            var Data = new FormData(document.getElementById("payment_form"));
            Data.append('is_actual', is_actual);

            is_valid = true;
            var payment_arr = [], total_paid = parseFloat($('#paid_amount'))||0;
            $(".row-item").each(function () {
                var amount = parseFloat($(this).find(".payment_amount").val()) || 0,
                        payment_account = $(this).find("input.payment_type").val(),
                        currency_id = $(this).find("select.payment_currency").val();
                total_paid += ConvertCurrency2(amount, currency_id, local_currency);
                console.log(amount+'=='+currency_id)
                if (amount != 0 && payment_account != 0 && payment_account != '' && currency_id != 0 && currency_id != '') {

                    payment_arr.push({
                        payment_amount: amount,
                        payment_account: payment_account,
                        currency_id: currency_id
                    })
                } else {
                    is_valid = false;
                }
            })
//            console.log(is_valid)
//            console.log(payment_arr)
            if (!is_valid) {
                AddAlert("#payment_alert", '<?php echo CommonLanguage::getMessage('Required_Fields'); ?>', "danger")
                return;

            }
            var local_paid_amount = ConvertCurrency2(parseFloat($('#total_amount').val()) - parseFloat($('#paid_amount').val()), $('#currency_id').val(), local_currency);
console.log(total_paid+'==='+local_paid_amount)            
if (total_paid > local_paid_amount || total_paid == 0) {
                AddAlert("#payment_alert", '<?php echo CommonLanguage::getMessage('paid_amount_less_total'); ?>', "danger")
                return;
            }

            Data.append('payment_arr', JSON.stringify(payment_arr))
            $("#paymentLoader").removeClass('hidden');
            $.ajax({
                url: "ACCAjax/submitSchedulePaymentBill",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            ChangeTable();
                            hideModalAlert('add_payment_modal', 'payment_alert');
                        }
                        AddAlert("#payment_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#paymentLoader").addClass('hidden');
                }
            });
        });
    });

    function ChangeTable() {
        var Date = {
            is_actual: is_actual ? 1 : 0,
            bill_due_date_from: (window.startDate ? window.startDate : ''),
            bill_due_date_to: (window.endDate ? window.endDate : ''),
            customer_id: $('#current_customer_id').val(),
            status_id: $('#status_id').val()
        };
        RebuildDataTable($('.panel-title h4').html(), [0, 1, 2, 3, 4, 5, 6, 7], 'ACCAjax/scheduleBillsPayments', Date, '#tableWithSearch', [0, 1, 2, 3, 5, 6])
    }
</script>
