<?php
require "_header.php";
require "data/combo_student.php";
require "data/combo_semester.php";
require "data/combo_branchyear.php";
?>
<?php
$objFeeshead = new FeesheadMgmt();
$feeHeads = $objFeeshead->getAllRecords($limit = 0, $start = 0, $condition = "", $order_field = "", $order_type = "");
$headNames = [];

if (dbRows($feeHeads)) {
    while ($row = dbArray($feeHeads)) {
        $head = $row['head_name'];
        $headNames[] = [
            'name' => $head,
            'fee_field' => $head . "_fee"
        ];
    }
}
?>
<script type="text/javascript">
    var labelArray;
    labelArray = [
        ['Course Name '],
        ['Batch Year '],
        ['Course Year '],
        ['Semester '],
        ['Hostel Facility ']
    ];

    Ext.onReady(function () {
        Ext.QuickTips.init();

        var branchstore = new Ext.data.ArrayStore({
            fields: ['branch_id', 'branch_name'],
            data: Ext.semester.branch
        });

        var batchyearstore = new Ext.data.ArrayStore({
            fields: ['year_id', 'year_name'],
            data: Ext.semester.yearname
        });

        var semesterstore = new Ext.data.ArrayStore({
            fields: ['branch_id', 'semester_id', 'semester_name'],
            data: Ext.student.semester
        });

        var yearstore = new Ext.data.ArrayStore({
            fields: ['branch_id', 'branchyear_id', 'branchyear_name'],
            data: Ext.year.year
        });

        var transportstore = new Ext.data.ArrayStore({
            fields: ['transport_facility'],
            data: [['Updown Facility'], ['Hostel Facility']]
        });

        var headNames = <?php echo json_encode($headNames); ?>

        var col = ['student_id',
            'student_gturegno',
            'student_name'
        ];

        headNames.forEach(function (head) {
            col.push(head.fee_field)
        });

        var FeessetupStore = new Ext.data.JsonStore({
            url: 'data/feessetup-grid-data.php',
            totalProperty: 'count',
            idProperty: 'student_id',
            successProperty: 'success',
            fields: col,
            root: 'data',
            writer: new Ext.data.JsonWriter(),
            autoSave: false
        });

        var gridColumns = [
            new Ext.grid.RowNumberer(),
            {
                dataIndex: 'student_id',
                header: 'Student ID',
                id: 'student_id',
                hidden: true
            },
            {
                dataIndex: 'student_gturegno',
                header: 'GR No',
                sortable: true,
                width: 90
            },
            {
                dataIndex: 'student_name',
                header: 'Student Name',
                sortable: true,
                id: 'SurName',
                width: 320
            }
        ];

        var hostelFeeColumn;
        headNames.forEach(function (head) {
            var columnConfig = {
                dataIndex: head.fee_field,
                header: head.fee_field,
                sortable: true,
                width: 90,
                editor: {
                    xtype: 'numberfield',
                    allowBlank: false,
                    decimalPrecision: 2,
                    maxValue: 999999,
                },
            };

            if (head.name === "Hostel Facility") {
                hostelFeeColumn = columnConfig;
            } else {
                gridColumns.push(columnConfig);
            }
        });

        if (hostelFeeColumn) {
            gridColumns.push(hostelFeeColumn);
        }

        var grid = new Ext.grid.EditorGridPanel({
            store: FeessetupStore,
            clicksToEdit: 1,
            columns: gridColumns,
            height: 320,
            layout: 'fit',
            columnLines: true,
            stripeRows: true,
            loadMask: true,
            selModel: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        });

        FeessetupStore.on({
            'load': {
                fn: function () {
                    if (FeessetupStore.getCount() <= 0) {
                        Ext.MessageBox.show({
                            title: 'Error',
                            msg: 'There is no Student found in this Selection.',
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        });

                    } else {
                        grid.startEditing(0, 4);
                    }
                }
            }
        });

        var feessetupform = new Ext.FormPanel({
            id: 'feessetupform',
            frame: true,
            url: 'save-feessetup.php',
            labelAlign: 'left',
            bodyStyle: 'padding:5px',
            layout: 'column',
            items: [{
                xtype: 'container',
                autoEl: {},
                layout: 'form',
                columnWidth: .50,
                labelWidth: 90,
                items: [{
                    xtype: 'combo',
                    name: 'branch_name',
                    id: 'branch_name',
                    hiddenName: 'branch_hidden',
                    fieldLabel: labelArray[0],
                    displayField: 'branch_name',
                    valueField: 'branch_id',
                    width: 250,
                    tabIndex: 1,
                    triggerAction: 'all',
                    mode: 'local',
                    allowBlank: true,
                    store: branchstore,
                    listeners: {
                        'select': function (cmb, rec, idx) {
                            Ext.getCmp('year_name').reset();
                            Ext.getCmp('semester_name').reset();
                            Ext.getCmp('branchyear_name').reset();
                            FeessetupStore.removeAll();
                            semesterstore.filter('branch_id', cmb.getValue(), false, true, true);
                            yearstore.filter('branch_id', cmb.getValue(), false, true, true);
                            var semesterCombo = Ext.getCmp('semester_name');
                            if (cmb.getValue() == 3 || cmb.getValue() == 5) {
                                semesterCombo.enable();
                            } else {
                                semesterCombo.disable();
                                semesterCombo.reset();
                            }
                        }
                    }
                }, {
                    xtype: 'combo',
                    name: 'branchyear_name',
                    id: 'branchyear_name',
                    hiddenName: 'branchyear_hidden',
                    fieldLabel: labelArray[2],
                    displayField: 'branchyear_name',
                    valueField: 'branchyear_id',
                    lastQuery: '',
                    triggerAction: 'all',
                    mode: 'local',
                    width: 250,
                    tabIndex: 3,
                    allowBlank: true,
                    store: yearstore,
                    listeners: {
                        'select': function (cmb, rec, idx) {
                            if (Ext.getCmp('branch_name').getValue() != "") {
                            } else {
                                this.reset();
                            }
                        }
                    }
                },
                {
                    xtype: 'combo',
                    name: 'transport_facility',
                    id: 'transport_facility',
                    fieldLabel: labelArray[4],
                    forceSelection: false,
                    displayField: 'transport_facility',
                    valueField: 'transport_facility',
                    width: 250,
                    allowBlank: true,
                    triggerAction: 'all',
                    mode: 'local',
                    store: transportstore,
                    tabIndex: 3,
                   listeners: {
                        'select': function (cmb, rec, idx) {
                            if (Ext.getCmp('branch_name').getValue() != "") {
                            } else {
                                this.reset();
                            }
                        }
                    }
                }
                ]
            }, {
                xtype: 'container',
                autoEl: {},
                layout: 'form',
                columnWidth: .50,
                labelWidth: 90,
                items: [{
                    xtype: 'combo',
                    name: 'year_name',
                    id: 'year_name',
                    hiddenName: 'year_hidden',
                    fieldLabel: labelArray[1],
                    displayField: 'year_name',
                    valueField: 'year_id',
                    lastQuery: '',
                    triggerAction: 'all',
                    mode: 'local',
                    width: 250,
                    tabIndex: 2,
                    allowBlank: true,
                    store: batchyearstore,
                    listeners: {
                        'select': function (cmb, rec, idx) {
                            if (Ext.getCmp('branch_name').getValue() != "") {
                            } else {
                                this.reset();
                            }
                        }
                    }
                }, {
                    xtype: 'combo',
                    name: 'semester_name',
                    id: 'semester_name',
                    hiddenName: 'semester_hidden',
                    fieldLabel: labelArray[3],
                    displayField: 'semester_name',
                    valueField: 'semester_id',
                    disabled: true,
                    lastQuery: '',
                    triggerAction: 'all',
                    mode: 'local',
                    width: 250,
                    tabIndex: 3,
                    allowBlank: true,
                    store: semesterstore,
                    listeners: {
                        'select': function (cmb, rec, idx) {
                            if (Ext.getCmp('branch_name').getValue() != "") {
                            } else {
                                this.reset();
                            }
                        }
                    }
                }, {
                    buttons: [{
                        text: 'View',
                        handler: function () {
                            var varbranch_id = feessetupform.getForm().findField('branch_name').getValue();
                            var varyear_id = feessetupform.getForm().findField('year_name').getValue();
                            var varbranchyear_id = feessetupform.getForm().findField('branchyear_name').getValue();
                            var varsemester_id = feessetupform.getForm().findField('semester_name').getValue();
                            var vartransport_facility = feessetupform.getForm().findField('transport_facility').getValue();
                            if (varbranch_id != "" && varyear_id != "" && varbranchyear_id != "" && vartransport_facility != "") {
                                FeessetupStore.load({
                                    params: {
                                        branch_id: varbranch_id,
                                        year_id: varyear_id,
                                        branchyear_id: varbranchyear_id,
                                        transport_facility: vartransport_facility
                                    },
                                    callback: function () {
                                        if (vartransport_facility === 'Hostel Facility') {
                                            grid.getColumnModel().setHidden(gridColumns.length - 1, false); 
                                        } else {
                                            grid.getColumnModel().setHidden(gridColumns.length - 1, true);
                                        }
                                        if (FeessetupStore.getCount() <= 0) {
                                            Ext.MessageBox.show({
                                                title: 'Error',
                                                msg: 'There is no Student found in this Selection.',
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox.ERROR
                                            });
                                        } else {
                                            grid.startEditing(0, 4);
                                        }
                                    }
                                });
                            } else {
                                Ext.MessageBox.show({
                                    title: 'Error',
                                    msg: 'Please select section, standard, and division.',
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.ERROR
                                });
                            }
                        }
                    }, {
                        text: 'Reset',
                        name: 'btnReset',
                        id: 'btnReset',
                        handler: function () {
                            feessetupform.getForm().reset();
                            grid.stopEditing();
                            FeessetupStore.removeAll();
                        }
                    }]
                }]
            }, {
                xtype: 'container',
                autoEl: {},
                layout: 'form',
                columnWidth: 1,
                labelWidth: 40,
                items: [grid]
            }]
        });

        var SetupWindow = new Ext.Window({
            title: 'Fees Setup Master',
            width: 800,
            height: 400,
            frame: true,
            border: false,
            modal: true,
            layout: 'fit',
            closeAction: 'close',
            collapsible: true,
            items: feessetupform,
            buttons: [
                {
                    text: 'Save',
                    name: 'btnSave',
                    tabIndex: 3,
                    iconCls: 'icon-save',
                    id: 'btnSave',
                    handler: function () {
                        if (grid.store.getCount() >= 1) {
                            var sId = [];
                            var feeData = {};
                            var studentIds = [];
                            grid.store.each(function (record) {

                                var validate = false;
                                headNames.forEach(function (head) {
                                    if (record.get(head.fee_field) != null) {
                                        validate = true;
                                        feeData[head.fee_field] = feeData[head.fee_field] || [];
                                        feeData[head.fee_field].push(record.get(head.fee_field));
                                    } else {
                                        feeData[head.fee_field] = feeData[head.fee_field] || [];
                                        feeData[head.fee_field].push(0);
                                    }

                                });

                                studentIds.push(record.get('student_id'));
                            });
                            feessetupform.getForm().submit({
                                params: {
                                    student_ids: Ext.util.JSON.encode(studentIds),
                                    fee_data: Ext.util.JSON.encode(feeData)
                                },
                                waitMsg: 'Saving...',
                                success: function () {
                                    feessetupform.getForm().reset();
                                    grid.stopEditing();
                                    FeessetupStore.removeAll();
                                },
                                failure: function () {
                                    Ext.MessageBox.show({
                                        title: 'Error',
                                        msg: 'Please fill up the complete form.',
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }
                            });
                        } else {
                            Ext.MessageBox.show({
                                title: 'Error',
                                msg: 'Please click on view button to see the students record.',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.ERROR
                            });
                        }
                    }
                }, {
                    text: 'Close',
                    name: 'btnclose',
                    tabIndex: 8,
                    iconCls: 'icon-close',
                    id: 'btnclose',
                    handler: function () {
                        SetupWindow.close();
                    }
                }
            ]
        });

        var varWidth = (screen.width - SetupWindow.width) / 2;
        SetupWindow.setPosition(varWidth, ((screen.height / 4) - 85));
        SetupWindow.show();
    });
</script>
<?php require "_footer.php"; ?>
