<?php
require "_header.php";
require "data/combo_student.php";
require "data/combo_semester.php";
require "data/combo_branchyear.php";

?>
<div id="main-content">
    <script type="text/javascript">

        var labelArray;
        labelArray = [
            ['Course '],
            ['Batch Year '],
            ['Course Year '],
            ['Semester '],
            ['Student Name '],
            ['Name of Document '],
            ['No of Document '],
            ['Document Recive Date ']
        ];

        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 studentstore = new Ext.data.JsonStore({
            url: 'data/getstudent-feesrecive.php',
            root: 'data',
            totalProperty: 'total',
            fields: [
                { name: 'student_id', type: 'int' },
                { name: 'student_name', type: 'string' }
            ]
        });
        Ext.onReady(function () {
            Ext.QuickTips.init();

            Ext.ns('Ext.ux.grid');

            Ext.ux.grid.PagingRowNumberer = Ext.extend(Ext.grid.RowNumberer, {
                renderer: function (v, p, record, rowIndex, colIndex, store) {
                    if (this.rowspan) {
                        p.cellAttr = 'rowspan="' + this.rowspan + '"';
                    }
                    var so = store.lastOptions;
                    var sop = so ? so.params : null;
                    return ((sop && sop.start) ? sop.start : 0) + rowIndex + 1;
                }
            });
            var dt = new Date();
            var xg = Ext.grid;
            var DocumentStore = new Ext.data.JsonStore({
                url: 'data/get-student-document.php',
                root: 'data',
                totalProperty: 'count',
                idProperty: 'studentdocument_id',
                successProperty: 'success',
                fields: [
                    { name: 'studentdocument_id', type: 'int' },
                    { name: 'student_id', type: 'int' },
                    { name: 'doc_id', type: 'int' },
                    { name: 'branch_id' },
                    { name: 'document_name' },
                    { name: 'noofdocument' },
                    { name: 'docrecive_date' }
                ],
                writer: new Ext.data.JsonWriter(),
                autoSave: false,
                batch: true,
                listeners: {
                    load: function (store, records, successful, operation) {
                        if (!successful) {
                            Ext.Msg.alert('Error', 'Failed to load document data.');
                        }
                    }
                }
            });

            var grid = new Ext.grid.EditorGridPanel({
                store: DocumentStore,
                clicksToEdit: 1,
                height: 350,
                border: true,
                width: 850,
                loadMask: true,
                stripeRows: true,
                columnLines: true,
                stripeRows: true,

                selModel: new Ext.grid.RowSelectionModel({ singleSelect: true }),
                columns: [
                    new Ext.ux.grid.PagingRowNumberer(),
                    {
                        dataIndex: 'doc_id',
                        header: ' Document id',
                        sortable: true,
                        hidden: true,
                        width: 180
                    },
                    {
                        dataIndex: 'branch_id',
                        header: ' Document type',
                        sortable: true,
                        hidden: true,
                        width: 180
                    },
                    {
                        dataIndex: 'document_name',
                        header: 'Name of Document',
                        sortable: true,
                        width: 180
                       
                    },
                    {
                        dataIndex: 'noofdocument',
                        header: 'No of Document',
                        width: 180,
                        sortable: true,
                        editor: {
                            xtype: 'numberfield',
                            style: 'text-align:left',
                            allowNegative: false,
                        }
                    },
                    {
                        dataIndex: 'docrecive_date',
                        header: 'Document Recive Date',
                        sortable: true,
                        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
                        width: 180,
                        editor: {
                            xtype: 'datefield',
                            format: 'Y-m-d',
                            allowBlank: false
                        }
                    },

                ]

            });


            grid.on('render', function () {
                grid.tip = new Ext.ToolTip({
                    view: grid.getView(),
                    target: grid.getView().mainBody,
                    delegate: '.x-grid3-row',
                    trackMouse: true,
                    renderTo: document.body,
                    listeners: {
                        beforeshow: function updateTipBody(tip) {
                            tip.body.dom.innerHTML = "Please click here to edit record.";
                        }
                    }
                });
            });

            var documentform = new Ext.FormPanel({
                id: 'documentform',
                frame: true,
                url: 'save-studentdocument.php',
                labelAlign: 'left',
                autoHeight: true,
                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();
                                    Ext.getCmp('student_name').reset();
                                    studentstore.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() != "") {
                                        Ext.getCmp('student_name').reset();
                                    } else {
                                        this.reset();
                                    }
                                }
                            }
                        },
                        {
                            xtype: 'combo',
                            name: 'student_name',
                            id: 'student_name',
                            hiddenName: 'student_hidden',
                            labelSeparator: '',
                            fieldLabel: labelArray[4],
                            displayField: 'student_name',
                            valueField: 'student_id',
                            width: 250,
                            tabIndex: 5,
                            triggerAction: 'all',
                            mode: 'local',
                            allowBlank: true,
                            store: studentstore,
                            listeners: {
                                'select': function (cmb, rec, idx) {
                                    if (Ext.getCmp('branch_name').getValue() != "" && Ext.getCmp('year_name').getValue() != "") {
                                    }
                                    else if (Ext.getCmp('branch_name').getValue() != "" && Ext.getCmp('branchyear_name').getValue() != "") {
                                    }
                                    else if (Ext.getCmp('branch_name').getValue() != "" && Ext.getCmp('semester_name').getValue() != "") {
                                    }
                                    else {
                                        this.reset();
                                    }

                                    grid.getStore().removeAll();
                                    var branch_name = Ext.getCmp('branch_name').getValue();
                                    var student_name = Ext.getCmp('student_name').getValue();

                                    if (branch_name != '' && student_name != '') {
                                        DocumentStore.load({
                                            params: {
                                                branch_hidden: branch_name,
                                                student_hidden: student_name
                                            },
                                            callback: function (records, operation, success) {
                                                if (!success || records.length === 0) {
                                                    // If no records are found, display an empty grid for new entries
                                                    grid.getStore().removeAll();
                                                }
                                            }
                                        });
                                    } else {
                                        grid.getStore().removeAll();
                                    }
                                }
                            }
                        },
                    ]
                },
                {
                    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() != "") {
                                    Ext.getCmp('student_name').reset();
                                    studentstore.load({ params: { 'branch_id': Ext.getCmp('branch_name').getValue(), 'year_id': Ext.getCmp('year_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: 4,
                        allowBlank: true,
                        store: semesterstore,
                        listeners: {
                            'select': function (cmb, rec, idx) {
                                if (Ext.getCmp('branch_name').getValue() != "") {
                                    Ext.getCmp('student_name').reset();
                                } else {
                                    this.reset();
                                }
                            }
                        }
                    }, {
                        xtype: 'textfield',
                        name: 'studentdocument_id',
                        id: 'studentdocument_id',
                        value: '0',
                        hidden: true
                    }
                    ]
                },
                {
                    xtype: 'container',
                    autoEl: {},
                    layout: 'form',
                    columnWidth: 1,
                    labelWidth: 40,
                    items: [grid]
                }]
            });
            var DocumentWindow = new Ext.Window({
                title: 'Student Document Master',
                width: 880,
                height: 500,
                frame: true,
                border: false,
                modal: true,
                layout: 'fit',
                closeAction: 'close',
                collapsible: true,
                items: documentform,
                buttons: [{
                    text: 'Save',
                    name: 'btnSave',
                    iconCls: 'icon-save',
                    id: 'btnSave',
                    handler: function () {
                        var form = documentform.getForm();

                        if (form.isValid()) {
                            if (grid.getStore().getCount() >= 1) {
                                // Collect data from the grid
                                var documentids = [];
                                var noofdocuments = [];
                                var docrecive_dates = [];
                                var student_id = form.findField('student_hidden').getValue();

                                var studentdocument_ids = [];

                                for (var i = 0, len = grid.getStore().getCount(); i < len; i++) {
                                    var record = grid.getStore().getAt(i);
                                    var doc_id = record.get('doc_id');
                                    var noofdocument = record.get('noofdocument');
                                    var docrecive_date = record.get('docrecive_date');
                                    var studentdocument_id = record.get('studentdocument_id'); // Default to 0 for new records

                                    if (noofdocument !== null && noofdocument !== '' && docrecive_date !== null && docrecive_date !== '') {
                                        documentids.push(doc_id);
                                        noofdocuments.push(noofdocument);
                                        docrecive_dates.push(docrecive_date);
                                        studentdocument_ids.push(studentdocument_id);
                                    }
                                }

                                // Prepare the data for submission
                                form.submit({
                                    waitMsg: 'Saving...',
                                    params: {
                                        documentids: Ext.encode(documentids),
                                        noofdocument: Ext.encode(noofdocuments),
                                        docrecive_date: Ext.encode(docrecive_dates),
                                        student_id: student_id,
                                        studentdocument_ids: Ext.encode(studentdocument_ids)
                                    },
                                    success: function (form, action) {
                                        // Handle successful save
                                        Ext.Msg.alert('Success', 'Data saved successfully.');
                                        documentform.getForm().reset();
                                        DocumentStore.removeAll();

                                    },
                                    failure: function (form, action) {
                                        // Handle errors during save
                                        Ext.MessageBox.show({
                                            title: 'Error',
                                            msg: action.result ? action.result.message : 'Failed to save data.',
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.ERROR
                                        });
                                    }
                                });
                            }
                        } else {
                            Ext.MessageBox.show({
                                title: 'Validation Error',
                                msg: 'Please correct the errors in the form.',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                        }
                    }
                },
                {
                    text: 'Reset',
                    tabIndex: 11,
                    name: 'btnreset',
                    iconCls: 'icon-reset',
                    id: 'btnreset',
                    handler: function () {
                        documentform.getForm().reset();
                        DocumentStore.removeAll();
                    }
                },
                {
                    text: 'Close',
                    name: 'btnclose',
                    iconCls: 'icon-close',
                    id: 'btnclose',
                    handler: function () {
                        DocumentWindow.close();
                    }
                }
                ],
            });

            function deleterecord(btn) {
                if (btn == 'yes') {
                    subjectform.getForm().submit({
                        waitMsg: 'Saving...',
                        params: { act: 'del' },
                        success: function () {
                            Ext.getCmp('branch_name').reset();
                            Ext.getCmp('subject_name').reset();
                            Ext.getCmp('course_name').reset();
                            Ext.getCmp('subject_code').reset();
                            Ext.getCmp('short_name').reset();
                            Ext.getCmp('btnDelete').disable();
                            Ext.getCmp('subject_id').setValue('0');
                            LoadData();
                            Ext.getCmp('subject_name').focus(true, 500);
                        }
                    });
                }
            }
            var varWidth = (screen.width - DocumentWindow.width) / 2;
            DocumentWindow.setPosition(varWidth, ((screen.height / 5) - 85));
            DocumentWindow.show();
            Ext.getCmp('studentdocument_id').focus(true, 500);
            if (flgAdd == "true") {
                Ext.getCmp('btnSave').enable();
            }
        });
    </script>
    <div id="abcd"></div>
</div>
<?php require "_footer.php"; ?>