<?php 
	require "_header.php";
	require "includeGridFilters.php";	
	if($_SESSION['cCompany_id']!="" && isset($_SESSION['cCompany_id'])){
		$objQuotationMgmt = new QuotationMgmt();
		
		$formMode = "";
		
		$quotation_id= Escape($_REQUEST["ID"]);
		if($quotation_id !="" && isset($quotation_id)){
		
			$formMode = "edit";
		
			$condition   = " AND quotation_id = '".$quotation_id."' ";
			$order_field = "quotation_id";
			$order_type  = "ASC";
			
			$result = $objQuotationMgmt->quotation_getAllRecords(0,0,$condition,$order_field,$order_type);		
			if(dbRows($result)>0){
				$row=dbArray($result);
				extract($row);
			}
			
			$result_product_ids = $objQuotationMgmt->quotation_getProductIds(0,0,$condition,$order_field,$order_type);		
			if(dbRows($result_product_ids)>0){
				$row_product_ids = dbArray($result_product_ids);
				$product_ids = $row_product_ids['product_ids'];
			}
		} else{
		
			$formMode = "add";
		
			$objQuotationMgmt->quotationtemplate_getRecordById();
		}		
	}	
?>
<style type="text/css">
    .movie-item {
        font:normal 12px tahoma, arial, helvetica, sans-serif;
        line-height:150%;
        padding:5px 20px 5px 10px;
        border:1px solid #fff;
        border-bottom:1px solid #eeeeee;
        white-space:normal;
        color:#555;
    }
    
	.movie-item h2 {
        display:block;
        font:inherit;
        font-weight:bold;
        color:#336699;
    }

    .movie-item h2 span {
        float: right;
        font-weight:normal;
        color:#555;
        margin:0 0 5px 5px;
        width:100px;
        display:block;
        clear:none;
    }
    
	.panel-icon {
        background:url(img/folder-movie.png) 0 no-repeat !important;
    }
</style>
<!-- start custom CSS/JS -->
<script type="text/javascript" language="javascript"> 
	var inquiry_id = '<?php  echo $inquiry_id; ?>';
	var formMode = '<?php echo $formMode; ?>';</script>
<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" src="jquery/ux/CheckColumn.js"></script>
<script type="text/javascript" src="js/product-inquiry.js"></script>
<script type="text/javascript">


Ext.QuickTips.init();

var gross_bill = 0;

var quotation_id = '<?php echo $_REQUEST['ID']; ?>';

var labelArray;
labelArray = [
	['To,'],
	['Reference:'],
	['Subject:'],
	['Date']
];

var QuotationDataStore = new Ext.data.JsonStore({
    url: 'data/quotation_combo_data.php',
	baseParams: {cmd:'quotation'},
    root: 'quotation',
    totalProperty: 'count',
    id: 'inquiry_id',
    fields: [
		{ name:'inquiry_id',      mapping:'inquiry_id'      },
		{ name:'inquierorg_name', mapping:'inquierorg_name' },
		{ name:'contactperson',	  mapping:'contactperson'   },
		{ name:'product_ids',	  mapping:'product_ids'   	},
		{ name:'inquier_address', mapping:'inquier_address' },
        { name:'appointmentdate', mapping:'appointmentdate' },
        { name:'appointmenttime', mapping:'appointmenttime' }
    ]
});

var quotationTpl = new Ext.XTemplate(
	'<tpl for="."><div class="movie-item">',
    	'<h2><span>Date: {appointmentdate}<br/>Time: {appointmenttime}</span>{inquierorg_name},{inquierorg_name1}</h2>',
        '{inquier_address}',
    '</div></tpl>'
);

var reader = new Ext.data.JsonReader({
	   root: 'griddata',
       idProperty: 'product_id',
        fields: [
			{name: 'grouping', type: 'string'},
            {name: 'product_id', type: 'int'},
             {name: 'product_measurement', type: 'string'},
            {name: 'product_name', type: 'string'},
            {name: 'product_qty', type: 'int'},
            {name: 'product_price', type: 'float'},
			{name: 'product_amt', type: 'float'},
			{name: 'product_vat1', type: 'float'},
			{name: 'product_vat2', type: 'float'},
			{name: 'product_servicetax', type: 'float'}            
        ]

    });
	
var gridDataStore = new Ext.data.GroupingStore({
    url: 'data/quotation-grid-data.php',
	reader: reader,
    successProperty: 'success',
    sortInfo: {field: 'product_id', direction: 'ASC'},
    groupField: 'grouping'
});
	
var reference_store = new Ext.data.Store({
	reader: new Ext.data.JsonReader({
	fields:['quotation_referenceby'],
	root: 'rows'
	}),
	proxy: new Ext.data.HttpProxy({
		url: 'data/get-distinct-reference.php',
		param:{reference:'reference11'}
	})
});

reference_store.load({params:{action:'reference'}});

var subject_store = new Ext.data.Store({
	reader: new Ext.data.JsonReader({
		fields:['quotation_subject'],
	root: 'rows'
	}),
	proxy: new Ext.data.HttpProxy({
		url: 'data/get-distinct-reference.php'
	})
});


var product_store = new Ext.data.Store({
	reader: new Ext.data.JsonReader({
		fields:['product_subject'],
	root: 'rows'
	}),
	proxy: new Ext.data.HttpProxy({
		url: 'data/get-distinct-reference.php'
	})
});


product_store.load({params:{action:'product'}});
reference_store.load({params:{action:'reference'}});
subject_store.load({params:{action:'subject'}});

var titleSearch = {
    xtype: 'combo',
	fieldLabel:'Inquier Organization',
    store: QuotationDataStore,
    displayField: 'inquier_address',
    typeAhead: false,
    loadingText: 'Searching...',
    emptyText: 'Type three or more letters of the title',
    minChars: 3,
    anchor: '99%',
    pageSize: 15,
	
	name:'organization',
	id:'organization',
	triggerAction: 'all',
	tpl: quotationTpl,
    itemSelector: 'div.movie-item',
    onSelect: function(record) {
		this.setValue(record.data.inquierorg_name);
        this.collapse();
		
		Ext.getCmp('inquiry_id').setValue(record.data.inquiry_id);
//		Ext.getCmp('quotation_toname').setValue(record.data.contactperson);
		
		var str_add = record.data.inquier_address;
		str_add = str_add.replace(/<br\/>/g,"\r\n");
		
//		Ext.getCmp('quotation_toaddress').setValue(str_add);
		
		gridDataStore.load({params:{
			product_ids:record.data.product_ids,
			formMode: 'add'
		}});
		
	}
}


Ext.onReady(function() {
	
	var dt = new Date();
	
	var fieldset = { 
		xtype: 'fieldset',
		autoHeight: true,
		items: [{
						xtype       : 'container',
						autoEl      : {},
						border      : false,
						layout      : 'column',
						anchor      : '98%',
						items       : [{
										xtype  : 'container',
										autoEl : {},
										layout : 'form',
										columnWidth :.85,
										labelWidth: 120,
										items  : [titleSearch
										
									
										]
									   },
									   {
										xtype       : 'container',
										autoEl      : {},
										layout      : 'form',
										columnWidth : .15,
										items       : [{
											xtype:'button',
											text:'New Inquiry',
											name: 'btnInquiry',
											id: 'btnInquiry',
											handler: function (){
											inquiryWindow.show();
											Ext.getCmp('btnQuotationClose').hide();
											}
										}]
									   }]}
			
		]
	}
	
	var quotation_colModel = new Ext.grid.ColumnModel([
		{
			header:'Product Name',
			width: 80,
			sortable: true,
			dataIndex:'grouping'
			 
		},{
			header:'Product Name',
			width: 100,
			sortable: true,
			dataIndex:'product_name1',
			summaryRenderer: function(v, params, data){
				return ('<b> Total :</b>');
			}
		}
		,{
			header: 'Qty',
			width: 25,
			sortable: true,
			dataIndex: 'product_qty',
			renderer : function(v){
			return v;
			},
			editor: new Ext.form.NumberField({
			   allowBlank: false,
			   allowNegative: false,
			   style: 'text-align:right'
			})
		},{
			header: 'Measure',
			width: 40,
			sortable: true,
			dataIndex: 'product_measurement'
		 },{
			header: 'Rate',
			width: 40,
			sortable: true,
			dataIndex: 'product_price',
			editor: new Ext.form.NumberField({
			   allowBlank: false,
			   allowNegative: false,
			   style: 'text-align:right'
			})
		 },{
			id: 'cost',
			header: 'Cost',
			width: 50,
			sortable: false,
			groupable: false,
			renderer: function(v, params, record){
				return record.data.product_qty * record.data.product_price;
			},
			dataIndex: 'product_amt',
			summaryType: 'total_Cost',
			summaryRenderer: function(v, params, data){
				gross_bill = gross_bill + parseFloat(v);
				return "<b>" + v.toFixed(2) + "</b>";
			}
		},{
			id: 'vat1',
			header: 'VAT1',
			width: 50,
			sortable: false,
			groupable: false,
			renderer: function(v, params, record){
				num = (record.data.product_qty * record.data.product_price * record.data.product_vat1)/100;
				return num.toFixed(2);
			},
			dataIndex: 'product_vat1',
			summaryType: 'total_Vat1',
			summaryRenderer: function(v, params, data){
				gross_bill = gross_bill + parseFloat(v);
				return "<b>" + v.toFixed(2) + "</b>";
			},
			editor: new Ext.form.NumberField({
			   allowBlank: false,
			   allowNegative: false,
			   style: 'text-align:right'
			})
		},{
			id: 'vat2',
			header: 'VAT2',
			width: 50,
			sortable: false,
			groupable: false,
			renderer: function(v, params, record){
				var num = (record.data.product_qty * record.data.product_price * record.data.product_vat2)/100;
				return num.toFixed(2);
			},
			dataIndex: 'product_vat2',
			summaryType: 'total_Vat2',
			summaryRenderer: function(v, params, data){
				gross_bill = gross_bill + parseFloat(v);
				return "<b>" + v.toFixed(2) + "</b>";
			},
			editor: new Ext.form.NumberField({
			   allowBlank: false,
			   allowNegative: false,
			   style: 'text-align:right'
			})
		},{
			id: 'service_tax',
			header: 'Serv.Tax',
			width: 50,
			sortable: false,
			groupable: false,
			renderer: function(v, params, record){
				var num = (record.data.product_qty * record.data.product_price * record.data.product_servicetax)/100;
				return num.toFixed(2);
			},
			dataIndex: 'product_servicetax',
			summaryType: 'total_ServTax',
			editor: new Ext.form.NumberField({
			   allowBlank: false,
			   allowNegative: false,
			   style: 'text-align:right'
			}),
			summaryRenderer: function(v, params, data){
				gross_bill = gross_bill + parseFloat(v);
				Ext.getCmp('lblgross').setText("Gross Rs. "+gross_bill.toFixed(2)+"/-");
				Ext.getCmp('gross').setValue(gross_bill.toFixed(2));
				gross_bill = 0;
				return "<b>" + v.toFixed(2) + "</b>";
			}
		}   
	]);

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

    var grid = new xg.EditorGridPanel({
		id:'grid',
		hidden:true,
        ds:gridDataStore,
        cm: quotation_colModel,
	    view: new Ext.grid.GroupingView({
            forceFit:true,
			showGroupName: false,
			enableNoGroups:false,
			hideGroupedColumn: true,
			groupTextTpl:"" 

        }),
		bbar:({
			items: [
				new Ext.form.Label({
					name: 'lblgross',
					id: 'lblgross',
					text: "",
					style: {
						color: '#ff0000'
					}
				})
			]
        }),
        plugins: summary,
        frame: true,
        width: 550,
        height: 250,
        clicksToEdit: 1
    });
	
	var varquotation_header = new Ext.form.HtmlEditor({
		name:'quotation_header',
		id:'quotation_header',
		width: 550,
		height:150,
		hidden:true
	});
	
	var varquotation_footer = new Ext.form.TextField({
		name:'quotation_footer',
		id:'quotation_footer',
		labelSeparator:'',	
	//fieldLabel :'Type:',
	allowBlank:false,
	hidden:true,
	width:400,
	});
	
	var Quotation_form = new Ext.FormPanel({
    	iconCls: 'panel-icon',
        frame: true,
		url:'save-quotation.php',
		autoHeight: true,
		autoScroll:true,
        id: 'movies-form',
        bodyStyle: 'padding:5px 5px 5px 5px',
        items:[
			{
				layout:'column',
				items:[
					{
						columnWidth: .7,
						layout: 'form',	
						align: 'right',
						labelWidth: 30,
						items:[
							{
								xtype:'textfield',
								name: 'inquiry_id',
								id:'inquiry_id',
								hidden: true
							},
							{
								xtype:'textfield',
								name: 'gross',
								id:'gross',
								hidden: true
							},
							{
								xtype: 'textfield',
								name: 'griddata',
								id:'griddata',
								hidden:true
							},
							{
								xtype: 'textfield',
								name: 'quotation_id',
								id: 'quotation_id',
								value: quotation_id,
								hidden: true
							}
						]				
					},
					{
						columnWidth: .3,
						layout: 'form',	
						align: 'right',
						labelWidth: 30,
						items:[
							{
								xtype: 'datefield',
								name: 'quotation_date',
								id:'quotation_date',
								value: dt.format('m-d-Y'),	
								fieldLabel:labelArray[3] ,
								allowBlank:false								    					
							}
						]				
					}						   
				]
			},
			{
				layout:'column',
				items:[
					{
						columnWidth: .5,
						layout: 'form',	
						labelWidth: 20,
						items:[
							{
								xtype:'textfield',
								name: 'quotation_toname',
								id:'quotation_toname',
								tabIndex:1,
								allowBlank:false,
								maxLength:50,
								width:158,
								labelSeparator:'',	
								fieldLabel :labelArray[0],
								autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							},{ 
								xtype: 'textarea',
								growAppend: "",
								name: 'quotation_toaddress',
								id:'quotation_toaddress',
								maxLength: 200,
								tabIndex:2,
								maxLengthText: 'max 200 characters',
								width: 158
							}
						]				
					}						   
				]
			},
			{
				height:30
			},
			{
				layout:'column',
				items:[
					{
						columnWidth: 1,
						layout: 'form',	
						labelWidth: 70,
						items:[
							{
								xtype: 'combo',
								name: 'quotation_reference',
								id:'quotation_reference',
								blankText : 'Please Enter or select Reference.',
								labelSeparator:'',	
								fieldLabel :labelArray[1] ,
								displayField:'quotation_referenceby',	
								tabIndex:3,										
								width: 400,
								allowBlank:false,
								triggerAction:'all',
								autoSelect:false,
								store: reference_store,
								mode:'local',
								selectOnFocus: true							
							},
							{ 
								xtype: 'combo',
								name: 'quotation_sub',
								id:'quotation_sub',
								blankText : 'Please Enter or select Subject.',
								labelSeparator:'',	
								fieldLabel :labelArray[2] ,
								displayField:'quotation_subject',	
								tabIndex:4,										
								width: 400,
								allowBlank:false,
								triggerAction:'all',
								autoSelect:false,
								store: subject_store,
								mode:'local',
								selectOnFocus: true
							},
							{ 
								xtype: 'combo',
								name: 'product_name',
								id:'product_name',
								blankText : 'Please select Product.',
								labelSeparator:'',	
								fieldLabel :'Product' ,
								displayField:'product_subject',	
								tabIndex:4,										
								width: 400,
								allowBlank:false,
								triggerAction:'all',
								autoSelect:false,
								store: product_store,
								mode:'local',
								selectOnFocus: true
							},
								{
								xtype:'textfield',
								name: 'quotation_quantity',
								id:'quotation_quantity',
								tabIndex:1,
								allowBlank:false,
								maxLength:50,
								width:158,
								labelSeparator:'',	
								fieldLabel :'Quntity',
								autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							},
							{
								xtype:'textfield',
								name: 'quotation_cost',
								id:'quotation_cost',
								tabIndex:1,
								allowBlank:false,
								maxLength:50,
								width:158,
								labelSeparator:'',	
								fieldLabel :'Cost',
								autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							},
							{
								xtype:'textfield',
								name: 'quotation_tax',
								id:'quotation_tax',
								tabIndex:1,
								allowBlank:false,
								maxLength:50,
								width:158,
								labelSeparator:'',	
								fieldLabel :'Tax(%)',
								autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							},
							{
								xtype:'textfield',
								name: 'quotation_total',
								id:'quotation_total',
								tabIndex:1,
								allowBlank:false,
								maxLength:50,
								width:158,
								labelSeparator:'',	
								fieldLabel :'Total',
								autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							}
						]				
					}						   
				]
			},
			{
				height:30
			},
			{
				layout:'column',
				items:[
					{
						columnWidth: 1,
						layout: 'form',	
						labelWidth:1,
						items:[ varquotation_header]				
					}						   
				]
			},
			{
				height:30
			},
			{
				layout:'column',
				items:[
					{
						columnWidth: 1,
						layout: 'form',	
						items:[ grid ]				
					}						   
				]
			},
			{
				height:30
			},
			{
				layout:'column',
				items:[
					{
						xtype:'container',
						columnWidth: 1,
						layout: 'form',	
						autoEl:{},
				
						labelWidth:1,
						items:[ varquotation_footer ]				
					}						   
				]
			}
		]	
    });

	var win = new Ext.Window({
		title: 'QUOTATION INFORMATION',
		height: 490,
		width: 630,
		closeAction:'hide',
		collapsible:'true',
		resizable:true,
		bodyStyle: 'padding:10px 10px 10px 10px',
		border:false,
		items: [fieldset,Quotation_form],
		buttonAlign:'center',
//		autoScroll: true,
		buttons: [
			{
				text:'Save',
				iconCls:'icon-save',
				handler: function () {  
					CopyStoreToForm(gridDataStore);
					Quotation_form.getForm().submit({
						waitMsg: 'Saving...',		
						success: function () {		
							Ext.MessageBox.show({
								title: 'Message',
								msg: 'Data has been saved..',
								buttons: Ext.MessageBox.OK,
								icon:Ext.MessageBox.INFO
							});
							
							if(formMode == "edit"){
								location.href="view-quotation.php";
							} else{
								Quotation_form.getForm().reset();
								grid.getSelectionModel().clearSelections();
								gridDataStore.removeAll();
								Ext.getCmp('lblgross').setText("");
								reference_store.load({params:{action:'reference'}});
								subject_store.load({params:{action:'subject'}});
							}
						},
						failure: function () {	
							Ext.MessageBox.show({
								title: 'Error',
								msg: 'Please fill complete form!',
								buttons: Ext.MessageBox.OK,
								icon:Ext.MessageBox.ERROR
							});
						}
					});
				}
			},
			{
				text: 'Reset', 
				iconCls:'icon-reset',
				handler: function () {   
					Quotation_form.getForm().reset();
					grid.getSelectionModel().clearSelections();
					gridDataStore.removeAll();
					Ext.getCmp('lblgross').setText("");

				}
			},
			{
				text: 'Close',
				iconCls:'icon-close',
				handler: function(){    
					win.close();
				}
			}
		]
	});
	
		Quotation_form.getForm().findField('quotation_tax').on('blur',function (){
	
		//alert(0);
		var quotation_quantity =Quotation_form.getForm().findField('quotation_quantity').getValue();
		
		var quotation_cost =Quotation_form.getForm().findField('quotation_cost').getValue();
		
		var quotation_tax =Quotation_form.getForm().findField('quotation_tax').getValue();
			
	var total=(quotation_quantity * quotation_cost);
	var total1=(total * quotation_tax)/100;
	var total2=(total + total1);
	
	var set =Quotation_form.getForm().findField('quotation_total').setValue(total2);
		
	});
	
	
	
    Ext.grid.GroupSummary.Calculations['total_Cost'] = function(v, record, field){
        return v + (record.data.product_qty * record.data.product_price);
    };
    
	Ext.grid.GroupSummary.Calculations['total_Vat1'] = function(v, record, field){
        return v + (record.data.product_qty * record.data.product_price * record.data.product_vat1)/100;
    };
    
	Ext.grid.GroupSummary.Calculations['total_Vat2'] = function(v, record, field){
        return v + (record.data.product_qty * record.data.product_price * record.data.product_vat2)/100;
    };
    
	Ext.grid.GroupSummary.Calculations['total_ServTax'] = function(v, record, field){
        return v + (record.data.product_qty * record.data.product_price * record.data.product_servicetax)/100;
    };

	if(formMode == "edit"){
	
		Ext.getCmp('btnInquiry').hide();
	
		Ext.getCmp('quotation_date')		.setValue('<?php print $quotation_date; ?>');
		Ext.getCmp('quotation_toname')		.setValue('<?php print $quotation_toname; ?>');
		Ext.getCmp('quotation_toaddress')	.setValue('<?php print replaceSpecial($quotation_toaddress); ?>');
		Ext.getCmp('quotation_reference')	.setValue('<?php print $quotation_referenceby; ?>');
		Ext.getCmp('quotation_sub')			.setValue('<?php print $quotation_subject; ?>');
		Ext.getCmp('quotation_header')		.setValue("<?php print $quotation_header; ?>");
		Ext.getCmp('quotation_footer')		.setValue("<?php print $quotation_footer; ?>");
		
		Ext.getCmp('quotation_tax')	.setValue('<?php print $quotation_tax; ?>');
		Ext.getCmp('quotation_cost')			.setValue('<?php print $quotation_cost; ?>');
		Ext.getCmp('quotation_quantity')		.setValue("<?php print $quotation_quantity; ?>");
		Ext.getCmp('quotation_total')		.setValue("<?php print $quotation_total; ?>");
		Ext.getCmp('product_name')		.setValue("<?php print $product_name; ?>");
		
		gridDataStore.load({params:{
			product_ids:'<?php echo $product_ids; ?>',
			quotation_id:quotation_id,
			formMode: 'edit'
		}});
		Ext.getCmp('inquiry_id').setValue("<?php print $inquiry_id; ?>");
		Ext.getCmp('organization').setValue("<?php print $inquierorg_name; ?>");
		Ext.getCmp('organization').disable();
	}
	else{
		Ext.getCmp('quotation_header').setValue("<?php print $objQuotationMgmt->quotation_header; ?>");
		Ext.getCmp('quotation_footer').setValue("<?php print $objQuotationMgmt->quotation_footer; ?>");
	}

	inquiryWindow.on('hide',function(){
		QuotationDataStore.load();
	});

	var varWidth =  (screen.width - win.width)/2;
	win.setPosition(varWidth,((screen.height/4)-110));
	win.show();
});

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
};
</script>
<!-- end custom CSS/JS -->
<div id="main-content" align="center"></div>
<?php require "_footer.php";?>