<?php $currency_symbol = $this->customlib->getSchoolCurrencyFormat(); ?>
<!-- Content Wrapper. Contains page content -->

<style>
    /* Style the input to have space for the prefix */
    #supplier_invoice_wrapper {
        position: relative;
        display: inline-block;
        width: 100%;
    }

    #supplier_invoice_wrapper::before {
        content: "SUP";
        position: absolute;
        top: 50%;
        left: 10px; /* Adjust padding for the prefix */
        transform: translateY(-50%);
        font-weight: bold; /* Make the prefix bold */
        color: #555;
        pointer-events: none; /* Make sure it doesn't block input */
    }

    #inv_number {
        padding-left: 50px; /* Create space for the prefix */
    }
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="content-wrapper">

    <section class="content-header">
        <h1>
            <i class="fa fa-mortar-board"></i> Supplier Invoicing
        </h1>
        <a href="<?php  echo base_url(); ?>expenses_history" class="col-md pull-right">Expense History</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php  echo base_url(); ?>expenses_report" class="col-md pull-right">Expense Statement</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php  echo base_url(); ?>supplier/supplier_statement" class="col-md pull-right">Statement</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php  echo base_url(); ?>supplier/supplier_receipt" class="col-md pull-right">Receipts</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php  echo base_url(); ?>supplier/supplier_invoice" class="col-md pull-right">Invoice</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php  echo base_url(); ?>supplier" class="col-md pull-right">Add Supplier</a>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <?php
            if ($this->rbac->hasPrivilege('class', 'can_add')) {
                ?>
            <div class="col-md-4">
                <!-- Horizontal Form -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><?php echo $title;       ?></h3>
                    </div><!-- /.box-header -->
                    <form id="form1" action="<?php echo base_url() ?>supplier/supplier_invoice" method="POST"
                        accept-charset="utf-8">
                        <div class="box-body">
                            <?php if ($this->session->flashdata('msg')) { ?>
                            <?php echo $this->session->flashdata('msg') ?>
                            <?php } ?>
                            <?php
                                if (isset($error_message)) {
                                    echo "<div class='alert alert-danger'>" . $error_message . "</div>";
                                }    
                                ?>
                            <?php echo $this->customlib->getCSRF(); ?>

                             <div class="form-group">
                                <label for="inv_number">Supplier Invoice</label><small class="req">*</small>
                                <div id="supplier_invoice_wrapper">
                                    <input 
                                        id="inv_number" 
                                        name="inv_number" 
                                        placeholder="Enter invoice number" 
                                        type="text" 
                                        class="form-control" 
                                        value="" 
                                    />
                                </div>
                                <span class="text-danger"><?php echo form_error('inv_number'); ?></span>
                            </div>

                            <script>
                                document.getElementById('inv_number').addEventListener('input', function () {
                                    const prefix = 'SUP';
                                    const inputField = this;
                                    const value = inputField.value;

                                    // Ensure prefix remains intact
                                    if (!value.startsWith(prefix)) {
                                        inputField.value = prefix + value.replace(prefix, '');
                                    }
                                });
                            </script>
                            <div class="form-group">
                                <label for="colour">Date</label><small class="req"> *</small>
                                <input autofocus="" id="inv_date" name="inv_date" placeholder="" type="date"
                                    class="form-control" value="<?php echo date("Y-m-d")?>" />
                                <span class="text-danger"><?php echo form_error('inv_date'); ?></span>
                            </div>

                            <div class="form-group">
                                <label for="currency">Supplier Name</label><small class="req"> *</small>
                                <select id="name" name="name" placeholder="" type="text" class="form-control">
                                    <option><?php echo $this->lang->line('select') ?></option>
                                    <?php 
												foreach ($supplier->result() as $grup) {
												?>
                                    <option value="<?php echo $grup->name; ?>"> <?php echo $grup->name; ?></option>
                                    <?php }
											?>
                                </select>
                                <span class="text-danger"><?php echo form_error('currency'); ?></span>
                            </div>
                            
                            <div class="form-group">
                                <label for="module">Module Name</label><small class="req"> *</small>
                                <select id="module" name="module" placeholder="" type="text" class="form-control">
                                    <option value="select"><?php echo $this->lang->line('select') ?></option>
                                    <option value="ST">ST</option>
                                    <option value="GL">GL</option>
                                </select>
                                <span class="text-danger"><?php echo form_error('module'); ?></span>
                            </div>

                            <div class="form-group">
                                <label for="account_name">Account Name</label><small class="req"> *</small>
                                <select id="account_name" name="account_name" placeholder="" type="text" class="form-control">
                                    <option>Select Account</option>
                                </select>
                                <span class="text-danger"><?php echo form_error('account_name'); ?></span>
                            </div>

                            <div class="form-group">
                                <label for="description">Description</label><small> *</small>
                                <input autofocus="" id="description" name="description" placeholder="" readonly type="text"
                                    class="form-control" value="<?php echo set_value('description'); ?>" />
                                <span class="text-danger"><?php echo form_error('description'); ?></span>
                            </div>

                            <div class="form-group">
                                <label for="amount">Quantity Available</label><small> *</small>
                                <input autofocus="" id="originalquantity" name="originalquantity" placeholder="" readonly type="text"
                                    class="form-control" value="<?php echo set_value('originalquantity'); ?>" />
                                <span class="text-danger"><?php echo form_error('originalquantity'); ?></span>
                            </div>

                            <script>
                                // Add event listener for module selection
                                document.getElementById('module').addEventListener('change', function () {
                                    const accountDropdown = document.getElementById('account_name');
                                    accountDropdown.innerHTML = ''; // Clear existing options
                                    const selectedModule = this.value;

                                    if (selectedModule === 'GL') {
                                        accountDropdown.innerHTML = `<option>Select GL Account</option>`;
                                        <?php foreach ($glledger_accounts->result() as $grup11) { ?>
                                            accountDropdown.innerHTML += '<option value="<?php echo $grup11->name; ?>">' +
                                                '<?php echo $grup11->gl_code; ?> > <?php echo $grup11->name; ?>' +
                                                '</option>';
                                        <?php } ?>
                                    } else if (selectedModule === 'ST') {
                                        accountDropdown.innerHTML = `<option>Select ST Account</option>`;
                                        const items = <?php echo json_encode($uniformitem->result()); ?>;

                                        items.forEach(item => {
                                            accountDropdown.innerHTML += `<option value="${item.itemcode}" 
                                                data-description="${item.itemdescript}" 
                                                data-quantity="${item.quantity}">
                                                ${item.itemcode} > ${item.itemdescript}
                                            </option>`;
                                        });
                                    } else {
                                        accountDropdown.innerHTML = `<option>Select Account</option>`;
                                    }
                                });

                                // Add event listener for account selection
                                document.getElementById('account_name').addEventListener('change', function () {
                                    const selectedOption = this.options[this.selectedIndex];

                                    // Get data attributes from the selected option
                                    const description = selectedOption.getAttribute('data-description');
                                    const quantity = selectedOption.getAttribute('data-quantity');

                                    // Update the fields
                                    document.getElementById('description').value = description || '';
                                    document.getElementById('originalquantity').value = quantity || '';
                                });
                            </script>


                            <!-- Duplicate for ST Option -->

                            <div class="form-group">
                                <label for="currency">MV Expense</label><small class="req"> ( Optional )</small>
                                <select id="mv_expense" name="mv_expense" placeholder="" type="text"
                                    class="form-control">
                                    <option>Select Motor Vehicle</option>
                      .              <?php 
												foreach ($vehicle_list->result() as $grup) {
												?>
                                    <option value="<?php echo $grup->vehicle_no; ?>">
                                        <?php echo $grup->vehicle_model.' - '.$grup->manufacture_year; ?></option>
                                    <?php  }
											?>
                                </select>
                                <span class="text-danger"></span>
                            </div>
                            

                             
                            <div class="form-group">
                                <label for="module">Ware house</label><small > *</small>
                                <select id="class_id" name="warehouse" placeholder="select warehouse" type="text" class="form-control">
                                    <option value="select"><?php echo $this->lang->line('select') ?></option>
                                    <option>Tuckshop</option>
                                    <option>Storeroom</option>
                                    <option>Main Warehouse</option>
                                </select>
                                <span class="text-danger"><?php echo form_error('module'); ?></span>
                            </div>

                            <div class="form-group">
                                <label for="colour">Description</label><small class="req"> *</small>
                                <input autofocus="" id="descriptions" name="descriptions" placeholder="" type="text"
                                    class="form-control" value="<?php echo set_value('descriptions'); ?>" />
                                <span class="text-danger"><?php echo form_error('descriptions'); ?></span>
                            </div>
                            <div class="form-group">
                                <label for="colour">Quantity</label><small class="req"> </small>
                                <input autofocus="" id="quantity" name="quantity" placeholder="" type="number"
                                    class="form-control" value="<?php echo set_value('quantity'); ?>" />
                                <span class="text-danger"></span>
                            </div>
                            <div class="form-group">
                                <label for="colour">Cost</label><small clreq"> *</small>
                                <input autofocus="" id="price" name="price" placeholder="" type="text"
                                    class="form-control" value="<?php echo set_value('price'); ?>" />
                                <span class="text-danger"><?php echo form_error('price'); ?></span>
                            </div>
                            <div class="form-group">
                                <label for="colour">Discount (%)</label><small > </small>
                                <input autofocus="" id="discount" name="discount" placeholder="" type="text"
                                    class="form-control" value="<?php echo set_value('discount'); ?>" />
                                <span class="text-danger"></span>
                            </div>

                            <div class="form-group">
                                <label for="currency">Currency</label><small class="req"> *</small>
                                <select id="currency" name="currency" placeholder="" type="text" class="form-control">
                                    <option><?php echo $this->lang->line('select') ?></option>
                                    <?php 
												foreach ($currency->result() as $grup) {
												?>
                                    <option value="<?php echo $grup->currency; ?>"> <?php echo $grup->currency; ?>
                                    </option>
                                    <?php }
											?>
                                </select>
                                <span class="text-danger"><?php echo form_error('currency'); ?></span>
                            </div>
                        </div><!-- /.box-body -->

                        <div class="box-footer">
                            <button type="submit"
                                class="btn btn-info pull-right"><?php echo $this->lang->line('save'); ?></button>
                        </div>
                    </form>
                </div>
            </div>
            <!--/.col (right) -->
            <!-- left column -->
            <?php } ?>
            <div class="col-md-<?php
            if ($this->rbac->hasPrivilege('class', 'can_add')) {
                echo "8";
            } else {
                echo "12";
            }
            ?>">
                <!-- general form elements -->
                <div class="box box-primary">
                    <div class="box-header ptbnull">
                        <h3 class="box-title titlefix"><?php echo $title_list; ?></h3>
                        <div class="box-tools pull-right">
                        </div><!-- /.box-tools -->
                    </div><!-- /.box-header -->
                    <div class="box-body">
                        <div class="table-responsive mailbox-messages">
                            <div class="download_label"><?php echo $title_list; ?></div>
                            <table class="table table-striped table-bordered table-hover example">
                                <thead>
                                    <tr>
                                        				
                                        <th>Date</th>
                                        <th>Name</th>
                                        <th>Item Code</th>
                                        <th>Description</th>
                                        <th>Warehouse</th>
                                        <th>Quantity Received</th>
                                        <th>Cost Price</th>
                                        <th>Discount (%)</th>
                                       
                                        <th>Total Amt</th>
                                        <th>Currency</th>
                                       <!-- <th class="text-right"><?php echo $this->lang->line('action'); ?></th>-->
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php  
										 foreach ($tempsup_invoice->result() as $row)  
										 {   
                                        ?>
                                    <tr>
                                        <td class="mailbox-name"><?php echo $row->inv_date;?></td>
                                        <td class="mailbox-name"><?php echo $row->name;?></td>
                                        <td class="mailbox-name"><?php echo $row->account_name;?></td>
                                        <td class="mailbox-name"><?php echo $row->description;?></td>
                                        <td class="mailbox-name"><?php echo $row->warehouse;?></td>
                                        <td class="mailbox-name"><?php echo $row->quantity;?></td>
                                        <td class="mailbox-name"><?php echo $row->price;?></td>
                                        <td class="mailbox-name"><?php echo $row->discount;?></td>
                                        <td class="mailbox-name"><?php echo $row->total_amount;?></td>
                                        <td class="mailbox-name"><?php echo $row->currency;?></td>
                                        <td class="mailbox-date pull-right">
                                            <div class="btn-group pull-right">
                                                <button class="btn btn-xs btn-default printInv"
                                                    data-sup_id="<?php echo $row->id; ?>"
                                                    title="<?php echo $this->lang->line('print'); ?>"><i
                                                        class="fa fa-print"></i> </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                    <tr>
									   <td>           
                                       <div class="btn-group pull-right"> 													
                                            <button type="button" class="btn btn-xs btn-warning refreshTempTable" title="Refresh">
                                                <i class="fa fa-refresh"></i> Process Invoice
                                            </button>
                                        </div>


										</td>
									</tr>
                                </tbody>
                            </table><!-- /.table -->



                        </div><!-- /.mail-box-messages -->
                    </div><!-- /.box-body -->
                </div>
            </div>
            <!--/.col (left) -->
            <!-- right column -->

        </div>
       
    </section><!-- /.content -->
</div><!-- /.content-wrapper -->

<script>
    $(document).ready(function () {
        $('.refreshTempTable').on('click', function () {
            Swal.fire({
                title: 'Are you sure?',
                text: "This will clear all temporary supplier invoices!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, clear it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '<?= base_url('supplier/delete_temp') ?>',
                        method: 'POST',
                        success: function (response) {
                            const result = JSON.parse(response);
                            if (result.status === 'success') {
                                Swal.fire(
                                    'Cleared!',
                                    'Temporary supplier invoices have been removed.',
                                    'success'
                                ).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Error!', 'Failed to clear table.', 'error');
                            }
                        },
                        error: function () {
                            Swal.fire('Oops...', 'Server error occurred.', 'error');
                        }
                    });
                }
            });
        });
    });
</script>


<script type="text/javascript">
$(document).ready(function() {
    $(document).on('click', '.printDoc', function() {
        var main_invoice = $(this).data('main_invoice');
        var sub_invoice = $(this).data('sub_invoice');
        var student_session_id = '<?php echo $student['student_session_id'] ?>';
        $.ajax({
            url: '<?php echo site_url("studentfee/printFeesByName") ?>',
            type: 'post',
            data: {
                'student_session_id': student_session_id,
                'main_invoice': main_invoice,
                'sub_invoice': sub_invoice
            },
            success: function(response) {
                Popup(response);
            }
        }); 
    });
   
});
</script>


<script type="text/javascript">
$(document).on('click', '.save_button', function(e) {
    var $this = $(this);
    $this.button('loading');
    var form = $(this).attr('frm');
    var feetype = $('#feetype_').val();
    var date = $('#date').val();
    var amount = $('#amount').val();

    var amount_discount = $('#amount_discount').val();
    var amount_fine = $('#amount_fine').val();
    var description = $('#description').val();
    var guardian_phone = $('#guardian_phone').val();
    var guardian_email = $('#guardian_email').val();
    var student_fees_master_id = $('#student_fees_master_id').val();
    var fee_groups_feetype_id = $('#fee_groups_feetype_id').val();
    var payment_mode = $('input[name="payment_mode_fee"]:checked').val();
    var student_fees_discount_id = $('#discount_group').val();
    $.ajax({
        url: '<?php echo site_url("studentfee/addstudentfee") ?>',
        type: 'post',
        data: {
            date: date,
            type: feetype,
            amount: amount,
            amount_discount: amount_discount,
            amount_fine: amount_fine,
            description: description,
            student_fees_master_id: student_fees_master_id,
            fee_groups_feetype_id: fee_groups_feetype_id,
            payment_mode: payment_mode,
            guardian_phone: guardian_phone,
            guardian_email: guardian_email,
            student_fees_discount_id: student_fees_discount_id
        },
        dataType: 'json',
        success: function(response) {
            // console.log(response);
            $this.button('reset');
            if (response.status == "success") {
                location.reload(true);
            } else if (response.status == "fail") {
                $.each(response.error, function(index, value) {
                    var errorDiv = '#' + index + '_error';
                    $(errorDiv).empty().append(value);
                });
            }
        }
    });
});
</script>


<script>
var base_url = '<?php echo base_url() ?>';

function Popup(data) {

    var frame1 = $('<iframe />');
    frame1[0].name = "frame1";
    frame1.css({
        "position": "absolute",
        "top": "-1000000px"
    });
    $("body").append(frame1);
    var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0]
        .contentDocument.document : frame1[0].contentDocument;
    frameDoc.document.open();
    //Create a new HTML document.
    frameDoc.document.write('<html>');
    frameDoc.document.write('<head>');
    frameDoc.document.write('<title></title>');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/bootstrap/css/bootstrap.min.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/font-awesome.min.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/ionicons.min.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/AdminLTE.min.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/skins/_all-skins.min.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/iCheck/flat/blue.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/morris/morris.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url +
        'backend/plugins/jvectormap/jquery-jvectormap-1.2.2.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url +
    'backend/plugins/datepicker/datepicker3.css">');
    frameDoc.document.write('<link rel="stylesheet" href="' + base_url +
        'backend/plugins/daterangepicker/daterangepicker-bs3.css">');
    frameDoc.document.write('</head>');
    frameDoc.document.write('<body>');
    frameDoc.document.write(data);
    frameDoc.document.write('</body>');
    frameDoc.document.write('</html>');
    frameDoc.document.close();
    setTimeout(function() {
        window.frames["frame1"].focus();
        window.frames["frame1"].print();
        frame1.remove();
    }, 500);


    return true;
}
$(document).ready(function() {
    $('.delmodal').modal({
        backdrop: 'static',
        keyboard: false,
        show: false
    })
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $('.invoice_no', this).text("");
        $('#main_invoice', this).val("");
        $('#sub_invoice', this).val("");

        $('.invoice_no', this).text($(e.relatedTarget).data('invoiceno'));
        $('#main_invoice', this).val($(e.relatedTarget).data('main_invoice'));
        $('#sub_invoice', this).val($(e.relatedTarget).data('sub_invoice'));


    });

    $('#confirm-discountdelete').on('show.bs.modal', function(e) {
        $('.discount_title', this).text("");
        $('#discount_id', this).val("");
        $('.discount_title', this).text($(e.relatedTarget).data('discounttitle'));
        $('#discount_id', this).val($(e.relatedTarget).data('discountid'));
    });

    $('#confirm-delete').on('click', '.btn-ok', function(e) {
        var $modalDiv = $(e.delegateTarget);
        var main_invoice = $('#main_invoice').val();
        var sub_invoice = $('#sub_invoice').val(); 

        $modalDiv.addClass('modalloading');
        $.ajax({
            type: "post",
            url: '<?php echo site_url("studentfee/deleteFee") ?>',
            dataType: 'JSON',
            data: {
                'main_invoice': main_invoice,
                'sub_invoice': sub_invoice
            },
            success: function(data) {
                $modalDiv.modal('hide').removeClass('modalloading');
                location.reload(true);
            }
        });


    });

    $('#confirm-discountdelete').on('click', '.btn-discountdel', function(e) {
        var $modalDiv = $(e.delegateTarget);
        var discount_id = $('#discount_id').val();


        $modalDiv.addClass('modalloading');
        $.ajax({
            type: "post",
            url: '<?php echo site_url("studentfee/deleteStudentDiscount") ?>',
            dataType: 'JSON',
            data: {
                'discount_id': discount_id
            },
            success: function(data) {
                $modalDiv.modal('hide').removeClass('modalloading');
                location.reload(true);
            }
        });


    });


    $(document).on('click', '.btn-ok', function(e) {
        var $modalDiv = $(e.delegateTarget);
        var main_invoice = $('#main_invoice').val();
        var sub_invoice = $('#sub_invoice').val();

        $modalDiv.addClass('modalloading');
        $.ajax({
            type: "post",
            url: '<?php echo site_url("studentfee/deleteFee") ?>',
            dataType: 'JSON',
            data: {
                'main_invoice': main_invoice,
                'sub_invoice': sub_invoice
            },
            success: function(data) {
                $modalDiv.modal('hide').removeClass('modalloading');
                location.reload(true);
            }
        });


    });


    $('.detail_popover').popover({
        placement: 'right',
        title: '',
        trigger: 'hover',
        container: 'body',
        html: true,
        content: function() {
            return $(this).closest('td').find('.fee_detail_popover').html();
        }
    });
});
</script>


<script type="text/javascript">
var fee_amount = 0;

var date_format =
    '<?php echo $result = strtr($this->customlib->getSchoolDateFormat(), ['d' => 'dd', 'm' => 'mm', 'Y' => 'yyyy',]) ?>';

$(document).ready(function() {
    $(".date").datepicker({
        format: date_format,
        autoclose: true,
        endDate: '+0d',
        todayHighlight: true
    });
});
</script>
<script type="text/javascript">
$("#myFeesModal").on('shown.bs.modal', function(e) {
    console.log("sdrere");
    e.stopPropagation();
    var discount_group_dropdown = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
    var data = $(e.relatedTarget).data();
    $('#discount_group').html("");
    $("span[id$='_error']").html("");
    $('.fees_title').html("");
    $('#amount').val("");
    $('#amount_discount').val("0");
    $('#amount_fine').val("0");
    var type = data.type;
    var amount = data.amount;
    var group = data.group;
    var fee_groups_feetype_id = data.fee_groups_feetype_id;
    var student_fees_master_id = data.student_fees_master_id;
    var student_session_id = data.student_session_id;

    $('.fees_title').html("<b>" + group + ":</b> " + type);
    $('#fee_groups_feetype_id').val(fee_groups_feetype_id);
    $('#student_fees_master_id').val(student_fees_master_id);



    $.ajax({
        type: "post",
        url: '<?php echo site_url("studentfee/geBalanceFee") ?>',
        dataType: 'JSON',
        data: {
            'fee_groups_feetype_id': fee_groups_feetype_id,
            'student_fees_master_id': student_fees_master_id,
            'student_session_id': student_session_id
        },
        success: function(data) {

            if (data.status == "success") {
                fee_amount = data.balance;

                $('#amount').val(data.balance);
                console.log(data.discount_not_applied);

                $.each(data.discount_not_applied, function(i, obj) {
                    discount_group_dropdown += "<option value=" + obj
                        .student_fees_discount_id + " data-disamount=" + obj.amount + ">" +
                        obj.code + "</option>";
                });
                $('#discount_group').append(discount_group_dropdown);




            }
        }
    });


});
</script>

<script type="text/javascript">
$(document).ready(function() {
    $.extend($.fn.dataTable.defaults, {
        searching: false,
        ordering: false,
        paging: false,
        bSort: false,
        info: false
    });
})
$(document).ready(function() {
    $('.table-fixed-header').fixedHeader();
});

//  $(window).on('resize', function () {
//    $('.header-copy').width($('.table-fixed-header').width())
//});

(function($) {

    $.fn.fixedHeader = function(options) {
        var config = {
            topOffset: 50
            //bgColor: 'white'
        };
        if (options) {
            $.extend(config, options);
        }

        return this.each(function() {
            var o = $(this);

            var $win = $(window);
            var $head = $('thead.header', o);
            var isFixed = 0;
            var headTop = $head.length && $head.offset().top - config.topOffset;

            function processScroll() {
                if (!o.is(':visible')) {
                    return;
                }
                if ($('thead.header-copy').size()) {
                    $('thead.header-copy').width($('thead.header').width());
                }
                var i;
                var scrollTop = $win.scrollTop();
                var t = $head.length && $head.offset().top - config.topOffset;
                if (!isFixed && headTop !== t) {
                    headTop = t;
                }
                if (scrollTop >= headTop && !isFixed) {
                    isFixed = 1;
                } else if (scrollTop <= headTop && isFixed) {
                    isFixed = 0;
                }
                isFixed ? $('thead.header-copy', o).offset({
                    left: $head.offset().left
                }).removeClass('hide') : $('thead.header-copy', o).addClass('hide');
            }
            $win.on('scroll', processScroll);

            // hack sad times - holdover until rewrite for 2.1
            $head.on('click', function() {
                if (!isFixed) {
                    setTimeout(function() {
                        $win.scrollTop($win.scrollTop() - 47);
                    }, 10);
                }
            });

            $head.clone().removeClass('header').addClass('header-copy header-fixed').appendTo(o);
            var header_width = $head.width();
            o.find('thead.header-copy').width(header_width);
            o.find('thead.header > tr:first > th').each(function(i, h) {
                var w = $(h).width();
                o.find('thead.header-copy> tr > th:eq(' + i + ')').width(w);
            });
            $head.css({
                margin: '0 auto',
                width: o.width(),
                'background-color': config.bgColor
            });
            processScroll();
        });
    };

})(jQuery);


$(".applydiscount").click(function() {
    $("span[id$='_error']").html("");
    $('.discount_title').html("");
    $('#student_fees_discount_id').val("");
    var student_fees_discount_id = $(this).data("student_fees_discount_id");
    var modal_title = $(this).data("modal_title");
    student_fees_discount_id

    $('.discount_title').html("<b>" + modal_title + "</b>");

    $('#student_fees_discount_id').val(student_fees_discount_id);
    $('#myDisApplyModal').modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });



});




$(document).on('click', '.dis_apply_button', function(e) {
    var $this = $(this);
    $this.button('loading');

    var discount_payment_id = $('#discount_payment_id').val();
    var student_fees_discount_id = $('#student_fees_discount_id').val();
    var dis_description = $('#dis_description').val();

    $.ajax({
        url: '<?php echo site_url("admin/feediscount/applydiscount") ?>',
        type: 'post',
        data: {
            discount_payment_id: discount_payment_id,
            student_fees_discount_id: student_fees_discount_id,
            dis_description: dis_description
        },
        dataType: 'json',
        success: function(response) {
            $this.button('reset');
            if (response.status == "success") {
                location.reload(true);
            } else if (response.status == "fail") {
                $.each(response.error, function(index, value) {
                    var errorDiv = '#' + index + '_error';
                    $(errorDiv).empty().append(value);
                });
            }
        }
    });
});
</script>

<script type="text/javascript">
$(document).ready(function() {
    $(document).on('click', '.printSelected', function() {
        var array_to_print = [];
        $.each($("input[name='fee_checkbox']:checked"), function() {
            var fee_session_group_id = $(this).data('fee_session_group_id');
            var fee_master_id = $(this).data('fee_master_id');
            var fee_groups_feetype_id = $(this).data('fee_groups_feetype_id');
            item = {}
            item["fee_session_group_id"] = fee_session_group_id;
            item["fee_master_id"] = fee_master_id;
            item["fee_groups_feetype_id"] = fee_groups_feetype_id;

            array_to_print.push(item);
        });
        if (array_to_print.length == 0) {
            alert("no record selected");
        } else {
            $.ajax({
                url: '<?php echo site_url("invoicing/printFeesInvoiceByGroupArray") ?>',
                type: 'post',
                data: {
                    'data': JSON.stringify(array_to_print)
                },
                success: function(response) {
                    Popup(response);
                }
            });
        }
    });
});


$(function() {
    $(document).on('change', "#discount_group", function() {
        var amount = $('option:selected', this).data('disamount');

        var balance_amount = (parseFloat(fee_amount) - parseFloat(amount)).toFixed(2);
        if (typeof amount !== typeof undefined && amount !== false) {
            $('div#myFeesModal').find('input#amount_discount').prop('readonly', true).val(amount);
            $('div#myFeesModal').find('input#amount').val(balance_amount);

        } else {
            $('div#myFeesModal').find('input#amount').val(fee_amount);
            $('div#myFeesModal').find('input#amount_discount').prop('readonly', false).val(0);
        }

    });
});
</script>
<script>
    $(document).on('click', '.printInv', function () {
            var id = $(this).data('sup_id');
            $.ajax({
                url: '<?php echo site_url("supplier/printSupplierInvoice") ?>',
                type: 'post',
                data: {'id': id},
                success: function (response) {
                    Popup(response);
                }
            });
        });

</script>


