<?php
require "_header.php";
require "data/combo_student.php";
require "data/combo_semester.php";
require "data/combo_branchyear.php";
?>
<script type="text/javascript" src="<?php echo $ModuleFolder; ?>jquery/ux/CheckColumn.js"></script>
<?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">
	if(flgDelete == "true") flgDelete1 = true;
			 else flgDelete1 = false;
		if(flgAdd == "true") flgAdd1 = true;
			 else flgAdd1 = false;
	var labelArray;
	labelArray = [
		['Course Name '],
		['Batch Year '],
		['Course Year '],
		['Semester '],

	];

	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 headNames = <?php echo json_encode($headNames); ?>

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

		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: 'Enrollment No',
				sortable: true,
				width: 130
			},
			{
				dataIndex: 'student_name',
				header: 'Student Name',
				sortable: true,
				id: 'SurName',
				width: 320
			},
			{
				header: 'Hostel Facility',
				id: 'transport_facility',
				dataIndex: 'transport_facility',
				width: 120,
				hidden: true,
			}
		];

		headNames.forEach(function (head) {
			var headerText = head.fee_field.split('_').map(function(part, index) {
        			return index === 0 ? part.charAt(0).toUpperCase() + part.slice(1) : part.charAt(0).toUpperCase() + part.slice(1);
   				}).join(' '); 
			gridColumns.push({
				dataIndex: head.fee_field,
				header: headerText,
				sortable: true,
				width: 90,
				editor: {
					xtype: 'numberfield',
					allowBlank: false,
					decimalPrecision: 2,
					maxValue: 999999,
					tabIndex:1,
				},
				renderer: function (value, metaData, record, rowIndex, colIndex, store) {
					var transportFacilityValue = record.get('transport_facility');
					if (transportFacilityValue !== 'Yes' && head.fee_field === 'Hostel_fee') {
						metaData.style = 'background-color:rgb(217, 217, 217); color: #ccc;';
					} else {
						metaData.style = '';  // Reset the style if it's editable
					}
					return value;
				}
			});
		});

		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 }),

		});

		grid.on('beforeedit', function (e) {
			if (e.field === 'Hostel_fee') {
				var transportFacilityValue = e.record.get('transport_facility');
				if (transportFacilityValue !== 'Yes') {
					e.cancel = true;
					var nextCell = grid.getView().getCell(e.row, e.column + 1); // Get the next cell
            if (nextCell) {
                nextCell.click(); // Focus on the next cell
            }
				}

			}
		});

		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: '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();
							if (varbranch_id != "" && varyear_id != "" && varbranchyear_id != "" && varsemester_id == "") {
								FeessetupStore.load({
									params: {
										branch_id: varbranch_id,
										year_id: varyear_id,
										branchyear_id: varbranchyear_id,

									}
								});
							}
							else if (varbranch_id != "" && varyear_id != "" && varsemester_id != "" && varbranchyear_id == "") {
								FeessetupStore.load({
									params: {
										branch_id: varbranch_id,
										year_id: varyear_id,
										semester_id: varsemester_id,

									}
								});
							}
							else if (varbranch_id != "" && varyear_id != "" && varsemester_id != "" &&  varbranchyear_id != "") {
								FeessetupStore.load({
									params: {
										branch_id: varbranch_id,
										year_id: varyear_id,
										semester_id: varsemester_id,
										branchyear_id: varbranchyear_id,
									}
								});
							}
							else {
								Ext.MessageBox.show({
									title: 'Error',
									msg: 'Please select Branch, Batch year.',
									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: 900,
			height: 450,
			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) {
									var feeValue = record.get(head.fee_field);

                    // Check if the Hostel Fee is being processed and if transport_facility is "No"
                    if (head.fee_field === 'Hostel_fee') {
                        var transportFacilityValue = record.get('transport_facility');
                        if (transportFacilityValue !== 'Yes') {
                            feeValue = null;  // Set Hostel Fee to null if transport_facility is not "Yes"
                        }
                    }

                    // Push the value to the feeData array, ensuring null for Hostel Fee when required
                    if (feeValue != null) {
                        feeData[head.fee_field] = feeData[head.fee_field] || [];
                        feeData[head.fee_field].push(feeValue);
                    } else {
                        feeData[head.fee_field] = feeData[head.fee_field] || [];
                        feeData[head.fee_field].push(0); // For other fields, store as 0 if null
                    }
                });

								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"; ?>