<?php
$this->load->view ( $left );
$this->load->view ( $header );
?>
<style type="text/css">
    .ibox-content {
        border-style : none;
    }
    .hr-line-dashed {
        margin: 5px 0;
    }
    .select-invoice {
        background: #72f53c;
    }
    .point-invoice {
        background: #c69fde;
    }
</style>
<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2><?php echo ($payment_received_id == '') ? 'New Payments Received' : 'Edit Payments Received';?></h2>
    </div>
</div>
<div class="wrapper wrapper-content">
    <div class="row text-center animated fadeInRightBig">
        <form method="post" class="form-horizontal" id="invoice_data">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">Invoice</label>
                        <div class="col-sm-8">
                            <select class="form-control" name="customer_id" id="choose_customer">
                                <option value="">Select Customer</option>
                                <?php if (count($customer_list) > 0) {
                                    foreach ($customer_list as $key => $value) {?>
                                        <option value="<?php echo $value->id;?>" <?php echo (!empty($payment_received_id) && isset($recived_payment_data) && ($recived_payment_data['customer_id'] == $value->id)) ? 'selected="selected"' : '';?>><?php echo $value->name;?></option>
                                    <?php }
                                }?>
                            </select>
                        </div>
                        <div class="col-sm-12" id="customer_address"></div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Amount</label>
                        <div class="col-lg-4">
                            <input placeholder="Amount" class="form-control pull-left amount" type="number" id="amount" name="amount" value="<?php //echo !empty($user_details->name) ? $user_details->name : '';?>"> 
                            <span class="help-block m-b-none" id="balance_amount" style="color: coral;"></span>
                        </div>
                        <div class="col-lg-1">
                            <button type="button" class="btn btn-success btn-xs confirm_amount"><i class="fa fa-check"></i></button>
                        </div>
                        <div class="col-lg-4" id="invoice_ids"></div>
                    </div>
                   
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Bank Charges (if any)</label>
                        <div class="col-lg-8">
                            <input placeholder="Bank Charge" class="form-control pull-left bank_charges" type="number" id="bank_charges" name="bank_charges" value="<?php //echo !empty($user_details->contact_display_name) ? $user_details->contact_display_name : '';?>">
                        </div>
                    </div>
                    <div class="form-group date_calender">
                        <label class="col-lg-3 control-label" style="text-align: right;">Payment Date</label>
                        <div class="col-lg-8 input-group date">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                            <input type="text" class="form-control pull-left payment_date" id="payment_date" name="payment_date" value="<?php echo date('d/m/Y');?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Payment Mode</label>
                        <div class="col-lg-8">
                            <select class="form-control" name="payment_type" id="payment_type">
                                <option value="">Select Payment Mode</option>
                                <option value="1">Cash</option>
                                <option value="2">Check</option>
                                <option value="3">Online</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Reference#</label>
                        <div class="col-lg-8">
                            <input placeholder="Referance No." class="form-control pull-left reference" id="reference" type="text" name="reference" value="<?php //echo !empty($user_details->contact_display_name) ? $user_details->contact_display_name : '';?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Deposit To</label>
                        <div class="col-lg-8">
                            <select class="form-control deposit_to" name="deposit_to" id="deposit_to">
                                <option value="">Select Payment Account</option>
                                <?php if(count($bank_list) > 0){
                                    foreach ($bank_list as $key => $value) {?>
                                        <option value="<?php echo $value->account_id;?>"><?php echo $value->account_name;?></option>
                                <?php }
                                }?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-lg-3 control-label" style="text-align: right;">Payment Note</label>
                        <div class="col-lg-8">
                            <input placeholder="PAYMENT NOTE" class="form-control pull-left note" id="note" type="text" name="note" value="<?php //echo !empty($user_details->contact_display_name) ? $user_details->contact_display_name : '';?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-lg-12">
                            <button class="btn btn-primary pull-right m-l-sm recived_payment" type="button"><strong>Save</strong></button>
                            <button class="btn btn-danger pull-right cancel_payment" type="button"><strong>Cancel</strong></button>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <div class="row" id="invoices"></div>
    </div>
</div>
<?php $this->load->view($footer); ?>
<script type="text/javascript">
    $(document).ready(function(){
        var paid_invoice = {};
        var user_balance = 0;
        $('.date_calender .input-group.date').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            language: 'en',
            autoclose: true
        });

        $('#choose_customer').on('change',function(){
            var user_id = $(this).val();
            if (user_id != '') {
                getUserinfo(user_id);
                getUserInvoiceList(user_id);
                getUserBalanceAmount(user_id);
            }
        });

        $('.cancel_payment').on('click',function(){
            window.location.href = '<?php echo site_url("receive_payment");?>';
        });

        function getUserBalanceAmount(user_id){
            $.ajax({
                url: '<?php echo site_url('receive_payment/user_balance');?>',
                type: "POST",
                data:{
                    user_id   : user_id
                },
                success: function(data){ 
                    user_balance = data;
                    $('#balance_amount').html('');
                    $('#balance_amount').html('<strong>User Balance Amount : '+format(user_balance,'cost')+'</strong>');
                }
            });
        }

        function scroll_tr(){
            $(".selected_invoice").unbind().click(function() {
                var invoice_no = $(this).data('inv_no');
                // $(".inv_"+invoice_no).removeClass('select-invoice').addClass('point-invoice');
                $('html,body').animate({
                    scrollTop: $(".inv_"+invoice_no).offset().top},
                    'slow');
            });
        }
        
        $('.recived_payment').on('click',function(){
            if ($('#choose_customer').val() == '') {
                $('#choose_customer').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#choose_customer').parent().parent().removeClass('has-error');
            }

            if ($('#amount').val() == '') {
                $('#amount').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#amount').parent().parent().removeClass('has-error');
            }

            if ($('#payment_date').val() == '') {
                $('#payment_date').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#payment_date').parent().parent().removeClass('has-error');
            }

            if ($('#payment_type').val() == '') {
                $('#payment_type').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#payment_type').parent().parent().removeClass('has-error');
            }

            if (($('#payment_type').val() == 2) && ($('#reference').val() == '')) {
                $('#reference').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#reference').parent().parent().removeClass('has-error');
            }

            if ($('#deposit_to').val() == '') {
                $('#deposit_to').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#deposit_to').parent().parent().removeClass('has-error');
            }
            
            $('.recived_payment').prop('disabled',true);
            var customer_id = $('#choose_customer').val();
            var amount = parseFloat($('#amount').val());
            var bank_charges = $('#bank_charges').val();
            var payment_date = $('#payment_date').val();
            var payment_type = $('#payment_type').val();
            var reference = $('#reference').val();
            var deposit_to = $('#deposit_to').val();
            var note = $('#note').val();
            
            $.ajax({
                url: '<?php echo site_url('receive_payment/pay');?>',
                type: "POST",
                data:{
                    customer_id   : customer_id,
                    amount        : amount,
                    bank_charges  : bank_charges,
                    payment_date  : payment_date,
                    payment_type  : payment_type,
                    reference     : reference,
                    deposit_to    : deposit_to,
                    note          : note,
                    paid_invoice  : paid_invoice
                },
                success: function(data){ 
                    location.reload();
                }
            });
        });

        var paying_amount =0;
        $('.confirm_amount').on('click',function(){
            var invoice_id_text = '';
            paying_amount = (parseFloat($('#amount').val()) + parseFloat(user_balance));
            
            $(".payInvoice").each(function() {
                $(this).removeClass('select-invoice');
                $(this).find('.pay-bill-select').prop('disabled',false);
                $(this).find('.pay-bill-select').prop('checked',false);

                var invoice_amount = parseFloat($(this).data('amount'));
                if (invoice_amount <= paying_amount) {
                    paying_amount = parseFloat(paying_amount - invoice_amount);
                    $(this).addClass('select-invoice');
                    $(this).find('.pay-bill-select').prop('checked',true);
                    
                    paid_invoice[$(this).data('invoice_no')] = [];
                    
                    paid_invoice[$(this).data('invoice_no')].push($(this).data('inv_id'));
                    paid_invoice[$(this).data('invoice_no')].push(invoice_amount);
                    
                    invoice_id_text += '<span class="label label-warning-light m-l-xs m-t-xs selected_invoice" style="float: left;" data-inv_no="'+$(this).data('invoice_no')+'">'+$(this).data('invoice_no')+'</span>';
                } else {
                    $(this).find('.pay-bill-select').prop('disabled',true);
                    $(this).find('.pay-bill-select').prop('checked',false);
                }
            });
            if (paying_amount > 0) { //FOR LEFT AMOUNT
                invoice_id_text += '<span class="label label-danger-light m-l-xs m-t-xs" style="float: left;"> +'+format(paying_amount,'cost')+'</span>'
            }
            $('#invoice_ids').html(invoice_id_text);
            scroll_tr();
        });

        $(document).on('change','.pay-bill-select',function(){
            var invoice_id_text ='';
            var bill_amount = parseFloat($(this).closest('tr.payInvoice').data('amount'));
            if ($(this).is(':checked')) {
                paying_amount = parseFloat(paying_amount - bill_amount);
                $(this).closest('tr.payInvoice').addClass('select-invoice');
            } else {
                paying_amount = parseFloat(paying_amount + bill_amount);
                $(this).closest('tr.payInvoice').removeClass('select-invoice');
            }

            paid_invoice = {};
            $('.pay-bill-select').each(function(){
                var amount = parseFloat($(this).closest('tr.payInvoice').data('amount'));
                if ($(this).is(':checked')) {
                    paid_invoice[$(this).closest('tr.payInvoice').data('invoice_no')] = [];
                    paid_invoice[$(this).closest('tr.payInvoice').data('invoice_no')].push($(this).closest('tr.payInvoice').data('inv_id'));
                    paid_invoice[$(this).closest('tr.payInvoice').data('invoice_no')].push(amount);

                    invoice_id_text += '<span class="label label-warning-light m-l-xs m-t-xs selected_bill" style="float: left;" data-invoice_no="'+$(this).closest('tr.payInvoice').data('invoice_no')+'">'+$(this).closest('tr.payInvoice').data('invoice_no')+'</span>';
                } else {
                    if (paying_amount < amount) {
                        $(this).prop('disabled',true);
                    } else {
                        $(this).prop('disabled',false);
                    }
                }
            });
            if (paying_amount > 0) { //FOR LEFT AMOUNT
                invoice_id_text += '<span class="label label-danger-light m-l-xs m-t-xs" style="float: left;"> +'+format(paying_amount,'cost')+'</span>'
            }
            $('#invoice_ids').html('').html(invoice_id_text);
            scroll_tr();
        });

        function getUserInvoiceList(user_id){
            $.ajax({
                url: '<?php echo site_url('receive_payment/invoice_list');?>',
                type: "POST",
                data:{
                    'user_id' : user_id
                },
                success: function(data){ 
                    $('#invoices').html();
                    $('#invoices').html(data);
                }
            });
        }

        function getUserinfo(user_id){
            $.ajax({
                url: '<?php echo site_url('user/user_basic_info');?>',
                type: "POST",
                data:{
                    'user_id'       : user_id,
                    'request_from'  : 'ajax'
                },
                success: function(data){ 
                    var user_data = JSON.parse(data);
                    userState = user_data.shipping_state;
                    var address_html = '<div class="col-lg-2"></div>';
                        address_html +=     '<div class="col-lg-4">';
                        address_html +=        '<div class="col-lg-12"><strong>Billing Adress</strong></div>';
                        address_html +=        '<div class="col-lg-12"><strong>Phone :</strong>'+user_data.contact_phone+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Address :</strong>'+user_data.billing_address+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>City :</strong>'+user_data.billing_city+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>State-Zip :</strong>'+user_data.billing_state+' - '+user_data.billing_zip+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Country :</strong>'+user_data.billing_country+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Fax :</strong>'+user_data.billing_fax+'</div>';
                        address_html +=    '</div>';
                        address_html +=    '<div class="col-lg-4">';
                        address_html +=        '<div class="col-lg-12"><strong>Shipping Adress</strong></div>';
                        address_html +=        '<div class="col-lg-12"><strong>Phone :</strong>'+user_data.contact_phone+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Address :</strong>'+user_data.shipping_address+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>City :</strong>'+user_data.shipping_city+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>State-Zip :</strong>'+user_data.shipping_state+' - '+user_data.shipping_zip+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Country :</strong>'+user_data.shipping_country+'</div>';
                        address_html +=        '<div class="col-lg-12"><strong>Fax :</strong>'+user_data.   shipping_fax+'</div>';
                        address_html +=    '</div>';
                        address_html += '<div class="col-lg-2"></div>';
                    $('#customer_address').html(address_html);

                    if (user_data.shipping_state != 19) {
                        $('.igst_show').removeClass('hide');
                        $('.gst_show').addClass('hide');
                    }
                }
            });
        }

        function format(val, type) {
            if(type == 'cost' || type == 'per') {
                var va = parseFloat(val).toFixed(2);
            } else {
                var va = parseFloat(val);
            }
            var test = va.toString().replace('.', '.');
            String.prototype.reverse = function() {
                var s = "";
                var i = this.length;
                while (i>0) {
                    s += this.substring(i-1,i);
                    i--;
                }
                return s;
            };

            var n = test.reverse().replace(/(\d{3})/g, "$1 ").reverse();
            
            if(type == 'cost') {
                n = n;
            } else if(type == 'per') {
                n = n + ' %';
            } 
            return n;
        }
    });
</script>
