<?php require "_header.php";?>
<?php require "includeGridFilters.php";
	  require "data/combo_data.php";
?>

<!-- start custom CSS/JS -->
<style type="text/css">
        p {
            width: 750px;
        }
        .ext-ie .x-form-check-wrap, .ext-gecko .x-form-check-wrap {
            padding-top: 3px;
			
        }
        fieldset legend {
            white-space: nowrap;
        }
		label.myBold
		{
		   font-weight: bold;
		   color:#006;
		   font-size: 14px;
		}
		

</style>

<script type="text/javascript" src="jquery/ux/CheckColumn.js"></script>
<link href="jquery/ux/css/superboxselect.css" rel="Stylesheet" type="text/css" /> 
<link href="jquery/ux/css/summary.css"  rel="stylesheet" type="text/css"  />
<script type="text/javascript" src="jquery/ux/SuperBoxSelect.js"></script>
<script type="text/javascript" src="jquery/ux/GroupSummary.js"></script>
<script type="text/javascript" src="jquery/ux/RowExpander.js"></script>
<script type="text/javascript" language="javascript"> 

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


	var encode = false;
	var local = false;
	

 // release order grid start 	
store = new Ext.data.JsonStore({
       	autoDestroy: true,
        url:'data/customer-bill-grid-filter.php',
        remoteSort: true,
		autoLoad:true,  
        sortInfo: {
            field: 'invoice_no',
            direction: 'ASC'
        },        
        idProperty: 'invoice_id',
        root: 'data',
        totalProperty: 'total',
        fields: [
		{
            name: 'invoice_no', type: 'int'
        },
		{
            name: 'billdate',type: 'date',dateFormat: 'Y-m-d'
        },
		{
            name: 'salesby',
			type: 'string'
        }, 
		 {
            name: 'customer_name',type: 'string'
        },
		 {
            name: 'address',type: 'string'
        },
		{
            name: 'remark',type: 'string'
        }
		
		] 
    });
  /*  var filters = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,  
		filters: [{
				  type: 'numeric',
            dataIndex: 'customer_id',
			 phpMode: true
        }, {
			type: 'string',
            dataIndex: 'customer_orgname',
			phpMode: true

        }, {
            dataIndex: 'customer_address',
			type: 'string'
        }, {
            dataIndex: 'customer_phone1',
			type: 'string'
        }, {
            dataIndex: 'customer_phone2',
			type: 'string'
        }, {
            dataIndex: 'customer_email',
			type: 'string'
        }, {
            dataIndex: 'customer_website',
			type: 'string'
        }]
    }); //remaining
	*/
var createColModel = function (finish, start) {
        var columns = [
		new Ext.grid.RowNumberer(),
		{
            dataIndex: 'invoice_no',
			header: 'INo',
			width: 40,
			filterable: true,
			renderer:color
        },
		{
            dataIndex: 'invoice_id',
			header: 'InvoiceID',
			hidden:true,
			filterable: true
        },
		
		{
            dataIndex: 'customer_name',
			header: 'Customer',
			filterable: true,
			width:90
        },
		
		 {
            dataIndex: 'billdate',
			header: 'BillDate',
			filterable: true,
			
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width:70
			
        },
		
		{
            dataIndex: 'address',
			header: 'Address',
			filterable: true,
			hidden:true,
			width: 0
			
        },
		{
            dataIndex: 'salesby',
			header: 'Sales By',
			hidden:true,
			filterable: true,
			width: 0
			
        }];
		return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
	
var hidden_invoice_num = new Ext.form.TextField({
		name: 'hidden_invoice_num',
		id:'hidden_invoice_num',
		value:'0',
		hidden:true
	});	
	var griddata = new Ext.form.TextField({
    name: 'griddata',
	id:'griddata',
	hidden:true
});	
var grid = new Ext.grid.GridPanel({
        store: store,
        colModel: createColModel(40), 
		frame: true,
		enableColLock:false,
		height:440,   
        width: 240,
        //layout: 'fit',
		columnLines: true,
		loadMask:true,
		stripeRows: true,
		selModel:  new Ext.grid.RowSelectionModel({
		singleSelect: true,
		listeners: {
			rowselect: function(sm, row, rec) {
				Ext.getCmp("CustomergridForm").getForm().loadRecord(rec);
				x=rec.get('invoice_no');
				  	Ext.getCmp('btn-perreport').enable();
				Ext.getCmp('hidden_invoice_num').setValue(x); //use for just edit the record in save file if it 0 then new record save otherwise edit	
				Ext.getCmp('btnDelete').enable();
				Ext.getCmp('btnAddItem').disable();
				Ext.getCmp('btn-blankreport').disable();
				Ext.getCmp('btnRemoveItem').disable();
					InvoiceproductDataStore.removeAll();
					
  				   InvoiceproductDataStore.load({params:{
												task:'getdata',
												invoice_no :x
												}});
				
			}
		 }
		}),
       // plugins: [filters]
    });

	
	store.on({
		'beforeload': {
    		fn: function(store, options){
            	options.params || (options.params = {}); 
            	Ext.apply(options.params, {
            		pageNo: this.pageNumber
            	});
        	},
        	scope: this
    	}
	});
		


var Customerstore = new Ext.data.Store({
		url: 'data/customer-grid-data.php',
		totolProperty:'count',
		reader: new Ext.data.JsonReader({			
        	fields: [{name:'customer_name',type:'string'}],
            root: 'data'
       	}),autoLoad:true
    });	

 var Productdata = Ext.data.Record.create([
	 		{name: 'invoice_id', type: 'int'},
			{name: 'invoice_no', type: 'int'},
            {name: 'product_name', type: 'string'},
			{name: 'qty', type: 'int'},
			/*{name: 'measurement_id', type: 'int'},*/
          	{name: 'rate', type: 'float'},
			{name: 'vat', type: 'float'},
			{name: 'discount', type: 'float'},
		    {name: 'tamount', type: 'float'}		
           ]);
			
	
	 var reader = new Ext.data.JsonReader({
		//idProperty: 'nro_id',
		root: 'data',
		//idProperty: 'ip',
        fields: [
			{name: 'invoice_id', type: 'int'},
            {name: 'product_name', type: 'string'},
			{name: 'qty', type: 'int'},
			/*{name: 'measurement_id', type: 'int'},*/
          	{name: 'rate', type: 'float'},
			{name: 'vat', type: 'float'},
			{name: 'discount', type: 'float'},
		    {name: 'tamount', type: 'float'},

			{name:'grouptype',	type:'string'}
				
        ]
    });



var productstore = new Ext.data.Store({
		url: 'data/billproducts-grid-data.php',
		totolProperty:'count',
		reader: new Ext.data.JsonReader({			
        	fields: [{name:'product_name',type:'string'}],
            root: 'data'
       	}),autoLoad:true
    });	

	
var product_name = new Ext.form.ComboBox({
				name:'product_name',
				id:'product_name',
				displayField:'product_name',
				valueField: 'product_name',
				width:60,	
				allowBlank:false,
				triggerAction:'all',
				mode:'local',
				store: productstore,
				editable:true,
				forceSelection:false,
				 listeners: {
				  
							specialkey: function(f,e){
								if (e.getKey() == e.ENTER){
									return (false);
								}
							}
						}
				
	});
	

		
var InvoiceproductDataStore = new Ext.data.GroupingStore({
    url: 'data/customerbill-product-grid-data.php',
	reader: reader,
	successProperty: 'success',
	sortInfo: {field: 'invoice_id', direction: 'ASC'},
	groupField: 'grouptype'
});


    var summary = new Ext.grid.GroupSummary();

    Ext.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
		var amount=record.data.qty * record.data.rate;
		var discount=(amount*record.data.discount)/100;
		var vat=(amount*record.data.vat)/100;
		Ext.getCmp('releaseorder_netamount').setValue(Ext.util.Format.indianMoney (v + (amount)+(vat)-(discount)));
		return (v + (amount)+(vat)-(discount));
		
    };
	
	/*var chek = new Ext.ux.grid.CheckColumn
	         ({
				 id: 'status',
			dataIndex: 'selected',
			width:25	
			 });*/

    var invoicegrid = new Ext.grid.EditorGridPanel({
        ds:InvoiceproductDataStore,
		forceValidation: true,
		selModel:  new Ext.grid.RowSelectionModel({singleSelect: true}),
		columns: [
		  new Ext.grid.RowNumberer,
		  {
                header: 'Id',
                dataIndex: 'invoice_id',
				width: 0,
				hidden:true
				
            },
			  {
                header: 'invoice_no',
                dataIndex: 'invoice_no',
				width: 0,
				hidden:true
            },
			 {
                header: 'grouptype',
                dataIndex: 'grouptype',
				width: 0,
				hidden:true
            },
			
			{
                header: 'Product Desc.',
                width: 70,
                dataIndex: 'product_name',
                renderer : function(v){
                    return v;
                },
                editor: product_name
            },
				
			{
                header: 'Qty',
                width: 15,
                dataIndex: 'qty',
                renderer : function(v){
                    return v;
                },
                editor: new Ext.form.NumberField({
                   allowBlank: false,
                   allowNegative: false
                })
            },
			{
                header: 'Rate',
                width: 20,
                sortable: true,
                dataIndex: 'rate',
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false
                })
            },
			{
                header: 'Vat(%)',
                width: 15,
                sortable: true,
                dataIndex: 'vat',
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false
                })
            },{
                header: 'Dis(%)',
                width: 15,
                sortable: true,
                dataIndex: 'discount',
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false
                })
            },{
                id: 'tamount',
                header: 'Cost',
            	 dataIndex: 'tamount',
                width: 70,
                sortable: false,
                groupable: false,
			    renderer: function(v, params, record){
					var amount=record.data.qty  * record.data.rate;
					var vat=(amount*record.data.vat)/100;
					var discount=(amount*record.data.discount)/100;
					
					return Ext.util.Format.indianMoney ((amount)+(vat)-(discount));
					
                },
				
                 summaryType: 'totalCost',
                summaryRenderer: Ext.util.Format.indianMoney 
            }
        ],
		

        view: new Ext.grid.GroupingView({
            /*forceFit: true,
            showGroupName: false,
            enableNoGroups: false,
			enableGroupingMenu: false,
            hideGroupedColumn: true,
			hideHeaders:true*/
			forceFit:true,
		showGroupName: false,
		enableNoGroups:false,
		hideGroupedColumn: true


        }),

      plugins: summary,
	   tbar: [{
             iconCls: 'icon-add',
            text: 'Add item',
			id:'btnAddItem',
			name:'btnAddItem',
			//tabIndex:5,
            handler: function(){
			var e = new Productdata({
					invoice_id:0,
					invoice_no:0,
					product_name:'',
					qty:'',
					rate:'',
					vat:'',
                    discount:'',
					tamount:'',
					status:''
					
                });
				
                invoicegrid.stopEditing();
				
				var insert=(invoicegrid.store.getCount());
                invoicegrid.store.insert(insert, e);
                invoicegrid.getView().refresh();
                invoicegrid.getSelectionModel().selectRow(insert);
				
              
            }
        },{
            ref: '../removeBtn',
            iconCls:'remove',
			//tabIndex:6,
			id:'btnRemoveItem',
			name:'btnRemoveItem',
            text: 'Delete item',
            disabled: true,
            handler: function(){
                invoicegrid.stopEditing();
                var s = invoicegrid.getSelectionModel().getSelections();
                for(var i = 0, r; r = s[i]; i++){
					      	 invoicegrid.store.remove(r);
				}
				var remove=(invoicegrid.store.getCount()-1);
				if(remove!=-1)
				{
						invoicegrid.getSelectionModel().selectRow(remove);
				        invoicegrid.startEditing(remove,2);
				}
				if(remove==-1)
				{
				 invoicegrid.store.removeAll();	
				 Ext.getCmp('customerinvoice_grosstotal').setValue(0);
				}
			           
				
            }
        },
		{
											  xtype:'button',
											  text:'View-Report',
											  id:'btn-perreport',
											   name:'btn-perreport',
											 // tabIndex:5,
											   disabled:true,  	
											  iconCls:'icon-view',
											  handler: function(){
												
											//  Ext.getCmp('type').setValue('performance');
											//  Ext.getCmp('grade').setValue(Ext.getCmp('per_grade').getValue());
											 
			
											  var form = Ext.getCmp('CustomergridForm').getForm(); // or inputForm.getForm();
												    

												 var el = form.getEl().dom;
												 var target = document.createAttribute("target");
												 target.nodeValue = "_blank";
												 el.setAttributeNode(target);
												 if(Ext.getCmp('headerflag').getValue() == true)
												 	el.action = "report-customerbill-result1.php";
												 else
												 	el.action = "report-customerbill-result.php";
												 el.submit(); 
										

													
											      }	
										     },
		{
											  xtype:'button',
											  text:'Blank Report',
											  id:'btn-blankreport',
											   name:'btn-blankreport',
										 	
											  iconCls:'icon-view',
											  handler: function(){
												
											//  Ext.getCmp('type').setValue('performance');
											//  Ext.getCmp('grade').setValue(Ext.getCmp('per_grade').getValue());
											 
			
											  var form = Ext.getCmp('CustomergridForm').getForm(); // or inputForm.getForm();
												    

												 var el = form.getEl().dom;
												 var target = document.createAttribute("target");
												 target.nodeValue = "_blank";
												 el.setAttributeNode(target);
												 if(Ext.getCmp('headerflag').getValue() == true)
												 	el.action = "report-customerbill-result1.php";
												 else
												 	el.action = "report-customerbill-result.php";
												 el.submit(); 
										

													
											      }	
										     }
		], 
        width: 680,
        height: 250,
        clicksToEdit:1,
		enableHdMenu: false,
		columnLines: true,
		loadMask:true,
		stripeRows: true
    });
	 invoicegrid.getSelectionModel().on('selectionchange', function(sm){
     invoicegrid.removeBtn.setDisabled(sm.getCount() < 1);
    });
	
	
	
 var CustomergridForm = new Ext.FormPanel({
        id: 'CustomergridForm',
        frame: true,
		url:'save-customerbill.php',
        layout: 'column', 
		autoHeight:true,
		
        items: [{
            columnWidth: 0.3,
          
            items:[grid]
        },{
            columnWidth: 0.7,
            xtype: 'fieldset',
			
			defaults: {border:false},
			bodyStyle: 'padding:8px;',
            items: [{
          	layout: 'column', 
			items: [{
				columnWidth: 0.55,
				labelWidth:85,
				layout: 'form',
				items:[
				{
							xtype: 'datefield',
							name: 'billdate',
							id:'billdate',
							labelSeparator:'',	
							fieldLabel :'Date:<span class="comp">*</span>',
							width:100,
							value:new Date(),
							allowBlank:true
					 },{
							xtype:'combo',
							name: 'customer_name',
							id:'customer_name',
							labelSeparator:'',	
							fieldLabel :'Customer:<span class="comp">*</span>' ,
							forceSelection:false,				
							displayField:'customer_name',
							valueField: 'customer_name'
							,allowBlank:false
							,triggerAction:'all'
							,mode:'local'
							,store: Customerstore
							,width:200
							,selectOnFocus: true
							,listeners: {'select': function(cmb, rec, idx){}}
					},{
							xtype: 'textarea',
							name: 'address',
							id:'address',
							labelSeparator:'',	
							fieldLabel :'Address:',
							width:200,
							allowBlank:true
					 },
					 {
								xtype:'checkbox',
								id: 'headerflag',
								name: 'headerflag',
								fieldLabel: 'Print Header',
								checked :false
							}
		
		]
			},{	
            columnWidth: 0.45,
			layout: 'form',
			labelWidth:70,
			items: [{
							xtype: 'textfield',
							name: 'invoice_no',
							id:'invoice_no',
							labelSeparator:'',	
							fieldLabel :'Invoice No:',
							width:158,
							allowBlank:true,
							readOnly:true
					 },
					 {
							xtype: 'textfield',
							name: 'salesby',
							id:'salesby',
							labelSeparator:'',	
							fieldLabel :'Sales By:',
							width:158,
							
							allowBlank:true
					 },{
							xtype: 'textarea',
							name: 'remark',
							id:'remark',
							labelSeparator:'',	
							fieldLabel :'Remark:',
							width:158,
							allowBlank:true
					 },hidden_invoice_num,griddata]
			},
			{
            columnWidth: 1,
			layout: 'form', 
            items:[invoicegrid,{
							xtype: 'textfield',
							name: 'releaseorder_netamount',
							id:'releaseorder_netamount',
							labelStyle: 'margin-left:300px;margin-top:5px;font-weight: bold; color:#F12536',
							style:'margin-top:5px;',
							fieldLabel :'Net Total ',
							readOnly:true,
							width:150
						}]
        }]			     
        }]},
		
		]
    });
	
 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 CustomerWindow = new Ext.Window({
        title: 'Customer Information',
		width:850,		
		autoHeight:true,	
        frame: true,
		border: false,
		modal:true,
		layout: 'fit',
		closeAction:'hide',
		collapsible:true,
		items: CustomergridForm,
		buttonAlign: 'center',
		buttons:[
		    {
            	text: 'Save',
				iconCls: 'icon-save',
			//	tabIndex:19,
				handler: function () {
				var p=0;
				var t=0;
		/*	var product_name 	= new Array();	
			var qty 	= new Array();	
		
			var rate 	= new Array();	
			var discount 	= new Array();	
			var vat 	= new Array();	
			var tamount 	= new Array();	
			var invoice_id 	= new Array();	*/
			
			/*var measurement_id = new Array();*/

				if(invoicegrid.store.getCount()!=0)
					{
						/*for(var i = 0, len = invoicegrid.store.getCount(); i < len; i++){
							
							record = invoicegrid.store.getAt(i);
							product_name[p]= record.data.product_name;
							qty[p]= record.data.qty;
						
							rate[p]= record.data.rate;
							discount[p]= record.data.discount;
							vat[p]= record.data.vat;
							tamount[p]= record.data.tamount;
					      
							invoice_id[p] = record.data.invoice_id;
						
							
							                            
							p++;
						}*/
						CopyStoreToForm(InvoiceproductDataStore);
						
						CustomergridForm.getForm().submit({
						waitMsg: 'Saving...',
					/*	params:{
							product_name: Ext.util.JSON.encode(product_name), 	
							qty: Ext.util.JSON.encode(qty), 	
						
							rate: Ext.util.JSON.encode(rate), 	
							discount: Ext.util.JSON.encode(discount), 	
							vat: Ext.util.JSON.encode(vat), 	
							tamount: Ext.util.JSON.encode(tamount), 	
							invoice_id: Ext.util.JSON.encode(invoice_id), 	
							},*/
									
						success: function () {
										CustomergridForm.getForm().reset();
										store.load();
										InvoiceproductDataStore.removeAll();
										Ext.getCmp('btnDelete').disable();
										grid.getSelectionModel().clearSelections();
									Customerstore.reload();
									productstore.reload();
										get_BillNo();	
						},
						failure: function () {		
							Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please fill complete form.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });
						}
					});
					
					}
					else
					{
						alert("please select atlist one product");	
					}
					
				
				
					
				}
          	},
			{
				text: 'Delete',
				iconCls:'remove',
				disabled:true,
				id: 'btnDelete',
				name: 'btnDelete',
				handler: function(){
								Ext.MessageBox.confirm('Confirmation', ' Are you sure want to delete This Record.?', deleterecord);
							
				}
			},
			{
		    	text: 'Reset',
				iconCls: 'icon-reset',
				//tabIndex:20,
				handler: function () {
						CustomergridForm.getForm().reset();
						grid.getSelectionModel().clearSelections();
						Ext.getCmp('btnDelete').disable();
						Ext.getCmp('btn-perreport').disable();
						InvoiceproductDataStore.removeAll();
						Ext.getCmp('btn-blankreport').enable();
						Ext.getCmp('hidden_invoice_num').setValue('0');
						Ext.getCmp('btnAddItem').enable();
						get_BillNo();	
						
				}	
        	},
			{
            	text: 'Close',
				iconCls: 'icon-close',
				//tabIndex:21,
				handler: function(){
						CustomerWindow.hide();
				}
        	}
		]
		

	});
	
function color(v, params, record){
				
				
				var nro_status=record.data.nro_status;
			    if(nro_status =='revised'){
						return '<span style="color:green;">' + v + '</span>';
					}
					
					else if(nro_status =='canceled') {
						return '<span style="color:red;">' + v + '</span>';
					}
					else
					 {
						 return (v) ;
					 }
				
				}


	get_BillNo();
	
	function get_BillNo(){
			
	Ext.Ajax.request({
		loadMask: true,
		sync : true,
		url: 'data/get_billNo.php',
		
		success: function(resp){
			var value=Ext.decode(resp.responseText).count;
			
			if(value==','){
				
			 Ext.MessageBox.show({
					title: 'Error',
					msg: 'Ro.No Not Found.',
					buttons: Ext.MessageBox.OK,
					icon:Ext.MessageBox.ERROR
				});
			} 
			else{
				var arr_data = new Array();
				arr_data =  value.split(",");
				Ext.getCmp('invoice_no').setValue(arr_data[0]);
				
			}					
		}				
	});	}	
	
	
	
	
	function deleterecord(btn){
    	if(btn=='yes'){
	   		CustomergridForm.getForm().submit({
				waitMsg: 'Saving...',
				params:{act:'del'},
				success: function () {	
					CustomergridForm.getForm().reset();
					store.load();
					InvoiceproductDataStore.removeAll();
					Ext.getCmp('btnDelete').disable();
					get_BillNo();
					grid.getSelectionModel().clearSelections();	
							
				}
			});
	 	}  
  	}
	function CopyStoreToForm(store){
  var json = '[';
  store.each(function(store){
      json += Ext.util.JSON.encode(store.data) + ',';
  });
  json = json.substring(0, json.length - 1);
  json += ']';
  Ext.getDom('griddata').value = json;
 
};
	var varWidth =  (screen.width - CustomerWindow.width)/2;
	CustomerWindow.setPosition(varWidth,((screen.height/4)-140));
	CustomerWindow.show();

});
</script>
<!-- end custom CSS/JS -->
<div id="main-content"></div>
<?php require "_footer.php";?>