<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."CRM/class/class.Language-Pack.php");
include_once (PATH_TO_ROOT."CRM/_CRM_config.php");

$LangPack = new LanguagePack($db, $aLanguage);
$compName = "Orders".$suffix;
$tabName = "OrdersTab";

$ajaxOrders = CRM_RPATH."_forms/orders/_ajax/ajax.orders.php";
$ajaxFilter = CRM_RPATH."_forms/filter/_ajax/ajax.filter.php";
$export = CRM_RPATH."_forms/filter/_ajax/ajax.filter.php";
$exportHtml = CRM_RPATH."_forms/orders/_ajax/ajax.exportHtml.php";
$suffix = uniqid();
$orders = true;

?>

var ordersPageLimit = 10;

var orderStore = new Ext.data.Store({
	remoteSort: true,
	url: '<?php echo $ajaxOrders;?>',			
	baseParams:{
		action: 'get',
		start: 0,
		limit: ordersPageLimit
	},
	pageSize: ordersPageLimit,
	reader: new Ext.data.JsonReader({		
			root:'rows',
			totalProperty : 'results'
		},
		new Ext.data.Record.create([
		 	{ name:"id", type: 'int' },
		 	{ name:"order_status", type:'int'},
		 	{ name:"location_data", type:'string'},
		 	{ name:"team_data", type:'string'},
		 	{ name:"purchaser_data", type:'string' },
		 	{ name:"delivery_data_customer", type:'string' },
		 	{ name:"delivery_data_company", type:'string' },
		 	{ name:"avans_amount", type:'string' },
		 	{ name:"avans_credit_amount", type:'string' },
			{ name:"product_price", type: 'string' },
			{ name:"purchase_data", type: 'string' },
			{ name:"presentation_date", type: 'string' },
			{ name:"delivery_date", type: 'string' },
			{ name:"actuall_delivery_date", type: 'string' },
			{ name:"order_date", type: 'string' },
			{ name:"dan", type: 'int' },
			{ name:"ura", type: 'int' },
			{ name:"projectId", type: 'int' },
			{ name:"telId", type: 'int' },
			{ name:"cati_location", type: 'int' },
			{ name:"tip_narocila", type: 'int' },
			{ name:"status_history", type: 'string' }
			
		])
	),
	listeners:{
		load: function(){
			var grid = Ext.getCmp('<?php echo $compName;?>');
			if(grid.getEl().isMasked){
				grid.getEl().unmask();
			}
		}
	}
}); 

var <?php echo $compName;?> = new Ext.grid.EditorGridPanel({
        
    	store: orderStore,
        id: '<?php echo $compName;?>',
        border: false,
        closable: true,
        region: 'center',
         viewConfig: {    
        			getRowClass: function(record, rowIndex, rp, ds){    	
        			str = '';
        			//console.log(record.get('order_status'));
        			if (record.get('order_status') == 4) str = 'OrderStatusRed'; 
        			else if (record.get('order_status') == 5) str = 'OrderStatusRed';
        			else if (record.get('order_status') == 6) str = 'OrderStatusRed';
        			else if (record.get('order_status') == 7) str = 'OrderStatusRed';
        			
        			else if (record.get('order_status') == 2) str = 'OrderStatusGreen';
        			
        			
        				if(this.showPreview){                   
        					 return 'x-grid3-row-expanded ' + str;       
        				}
        				return 'x-grid3-row-collapsed ' + str;    
        			}
        },
      	columns: [
      		{
      			header: '#ID', 
      			width: 20, 
      			dataIndex: 'id',
      			hidden: true
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "location_data","Lokacija");?>', 
      			width: 200, 
      			sortable: true,
      			dataIndex: 'location_data',
      			cls: 'crmGridItem'
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "lteam_data","Ekipa");?>', 
      			width: 100, 
      			sortable: true,
      			dataIndex: 'team_data'
      			
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "purchaser_data","Kupec");?>', 
      			width: 200, 
      			sortable: true,
      			dataIndex: 'purchaser_data'
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "delivery_data_customer","Podatki o dostavi (Stranka)");?>', 
      			width: 150, 
      			sortable: true,
      			dataIndex: 'delivery_data_customer',
      			hidden: true
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "delivery_data_company","Podatki o dostavi (Podjetje)");?>', 
      			width: 150, 
      			sortable: true,
      			dataIndex: 'delivery_data_company',
      			hidden: true
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "avans_cash_amount","Avans");?>', 
      			width: 100, 
      			sortable: true,
      			dataIndex: 'avans_amount'
      		},
      		{
                header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "avans_credit_amount","Credit Avans");?>', 
                width: 100, 
                sortable: true,
                dataIndex: 'avans_credit_amount'
            },
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "purchase_price","Cena");?>', 
      			width: 90, 
      			sortable: true,
      			dataIndex: 'product_price'
      			<?php if(!isset($_SESSION['CRM_login'])){?>
        		,editor: new Ext.form.NumberField()
        		<?php } ?>
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "purchase_data","Podatki o nakupu");?>', 
      			width: 200, 
      			sortable: true,
      			dataIndex: 'purchase_data'
      			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "order_status","Status");?>', 
      			width: 200, 
      			sortable: true,
      			dataIndex: 'order_status',
      			renderer: function(a){
                	if (a == 1 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "ordered","Naročeno");?>';
                	else if ( a == 2 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "delivered","Dostavljeno");?>';
                	else if ( a == 3 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "date_delivery_change","Sprememba datuma");?>';
                	else if ( a == 4 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "storno_team","Storno ekipa");?>';
                	else if ( a == 5 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "storno_delivery","Storno dostava");?>';
                	else if ( a == 6 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "product_refund","Vračilo izdelek");?>';
                	else if ( a == 7 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "credit_refusal","Zavrnitev kredita");?>';
                	else if ( a == 8 ) return '<?php echo $LangPack->GetLabel("CRM_order_status", "opened","Odprt") ?>';
                },
                editor:{
	        	 	xtype: 'combo',
	        	 	typeAhead: true,
	        	 	listeners:{
	        	 		select: function(combo, record, index) {
	        	 		
	        	 			var store = <?php echo $compName; ?>.getSelectionModel().getSelections();
							var id_order = store[0].data.id;
					    	if(combo.getValue() == 2 && store[0].data.tip_narocila > 0){
					    		CallScript('<?php echo CRM_RPATH; ?>_forms/delivery/window.delivery-finish.php', { id: id_order, gridName: '<?php echo $compName;?>', start_state: combo.startValue, state: record.data.field1, tip_narocila: store[0].data.tip_narocila });
					    		combo.fireEvent('blur', combo);
					    	}
					    	if(combo.getValue() == 3){
					    		CallScript('<?php echo CRM_RPATH; ?>_forms/orders/window.change_date.php', { id: id_order, gridName: '<?php echo $compName;?>', start_state: combo.startValue, state: record.data.field1 });
					    		combo.fireEvent('blur', combo);
					    	}
					    	if(combo.getValue() == 4 || combo.getValue() == 5 || combo.getValue() == 6 || combo.getValue() == 7){
					    		CallScript('<?php echo CRM_RPATH; ?>_forms/orders/window.note.php', { id: id_order, gridName: '<?php echo $compName;?>',  start_state: combo.startValue, state: record.data.field1 });
					    		combo.fireEvent('blur', combo);
					    	}
						},
	      				focus: function(combo){
	      					if(combo.getValue() == 0 || combo.getValue == null)
	      						combo.setValue('<?php echo $LangPack->GetLabel("CRM_all", "select_option_title","Izberite...");?>');
	      				}
	      			},
	                triggerAction: 'all',
	                selectOnTab: true,
	        		store: [ 
	        		<?php 
	        		if(intval($_SESSION['UserInfo']['user_type']) == 0){
	        			echo "[2, '". $LangPack->GetLabel("CRM_order_status", "delivered","Dostavljeno") ."'],";
						echo "[3, '". $LangPack->GetLabel("CRM_order_status", "date_delivery_change","Sprememba datuma") ."'],";
						echo "[4, '". $LangPack->GetLabel("CRM_order_status", "storno_team","Storno ekipa") ."'],";
						echo "[5, '". $LangPack->GetLabel("CRM_order_status", "storno_delivery","Storno dostava") ."']";
	        		} else {
	        			echo "[1, '". $LangPack->GetLabel("CRM_order_status", "ordered","Naročeno") ."'],";
						echo "[2, '". $LangPack->GetLabel("CRM_order_status", "delivered","Dostavljeno") ."'],";
						echo "[3, '". $LangPack->GetLabel("CRM_order_status", "date_delivery_change","Sprememba datuma") ."'],";
						echo "[4, '". $LangPack->GetLabel("CRM_order_status", "storno_team","Storno ekipa") ."'],";
						echo "[5, '". $LangPack->GetLabel("CRM_order_status", "storno_delivery","Storno dostava") ."'],";
						echo "[6, '". $LangPack->GetLabel("CRM_order_status", "product_refund","Vračilo izdelek") ."'],";
						echo "[7, '". $LangPack->GetLabel("CRM_order_status", "credit_refusal","Zavrnitev kredita") ."'],";
						echo "[8, '". $LangPack->GetLabel("CRM_order_status", "opened","Odprt") ."']";
	        		}
	        		?>
                   ]
        		} 		 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "state_note","Zgodovina sprememb");?>', 
      			width: 340, 
      			sortable: true,
      			dataIndex: 'status_history'   			 
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "presentation_date","Datum prezentacije");?>', 
      			width: 130, 
      			sortable: true,
      			dataIndex: 'presentation_date'
      		},
      		{
      			header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "delivery_date","Previden datum dostave");?>', 
      			width: 130, 
      			sortable: true,
      			editor: new Ext.form.DateField({ format: 'd.m.Y', allowBlank: false}),
      			dataIndex: 'delivery_date'
      		},
            {
                header: '<?php echo $LangPack->GetLabel("CRM_order_panel", "actuall_delivery_date","Dejanski datum dostave");?>', 
                width: 130, 
                sortable: true,
                editor: new Ext.form.DateField({ format: 'd.m.Y', allowBlank: false}),
                dataIndex: 'actuall_delivery_date'
            }
        ],
     	sm: new Ext.grid.RowSelectionModel({
                			singleSelect: true                			
       	}),
        flex: 1,
        tbar:[
        {
			xtype: 'button',
			text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "search_button","Iskanje / Filter"); ?>',
			iconCls:'RMicon_search',
			handler: function(){				
					CallScript('<?php echo CRM_RPATH; ?>_forms/orders/window.search-filter.php', { grid: '<?php echo $compName;?>', suffix: '<?php echo $suffix;?>'});
			}
		},{
            xtype: 'button',
            text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "reclamation_button","Reklamacija"); ?>',
            handler: function(){
                
                
                if(<?php echo $compName ?>.getSelectionModel().hasSelection())
                {
                    var selected = <?php echo $compName ?>.getSelectionModel().getSelections()[0];
                    CallScript('<?php echo CRM_RPATH; ?>_forms/delivery/window.reclamation.php',
                    {
                        orderId: selected.get('id'),
                        gridName: '<?php echo $compName ?>'
                    });
                } else {
                	Ext.MessageBox.alert('Obvestilo','Izbrati je potrebno naročilo!');
                }
                
            }
        },'->',{
        	xtype: 'button',
        	text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "export_button","Izvozi"); ?>',
        	id: 'export_button_o',
        	flex: 1,
        	menu: {
        		xtype: 'menu',
        		items: [{
        			xtype: 'menuitem',
        			text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "export_excell_button","Izvozi v excell"); ?>',
        			handler: function(){
		        		var form = Ext.getCmp('FilterPanel<?php echo $suffix; ?>').getForm();
			            var formValues = form.getValues();
			            var store = Ext.getCmp('<?php echo $compName;?>').getStore().lastOptions.params;
		        		window.open('<?php echo $export; ?>?dataExport=true&orders=true&filterValues=' + Ext.encode(formValues)+'&lastParams='+Ext.encode(store), '_blank').focus();
		        	}
        		},{
        			xtype: 'menuitem',
        			text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "export_html_button","Izvozi v html tabelo"); ?>',
        			handler: function(){
        				var form = Ext.getCmp('FilterPanel<?php echo $suffix; ?>').getForm();
			            var formValues = form.getValues();
			            var store = Ext.getCmp('<?php echo $compName;?>').getStore().lastOptions.params;
			            window.open('<?php echo $exportHtml; ?>?exportHtml=true&orders=true&filterValues=' + Ext.encode(formValues)+'&lastParams='+Ext.encode(store), '_blank').focus();
        			}
        		}]
        	}
        }
        <?php 
        	if(!isset($_SESSION['CRM_login'])){
        		?>
        		,{
        			xtype: 'button',
        			text: '<?php echo $LangPack->GetLabel("CRM_order_panel", "change_order_title","Spremeni naročilo"); ?>',
        			handler:function(){
        				if(<?php echo $compName ?>.getSelectionModel().hasSelection())
               			{	
	        				var selected = <?php echo $compName ?>.getSelectionModel().getSelections()[0];
	        				CallScript("<?php echo CRM_RPATH;?>_forms/prisotnost/window.editOrder.php", {
	        					dan: selected.get('dan'), 
	        					ura: selected.get('ura'), 
	        					projectId: selected.get('projectId'), 
	        					id_tel: selected.get('telId'), 
	        					cati_location:selected.get('cati_location')
	        				});
	        			}
        			}
        		}
        		<?php
        	}
        ?>
        ],
        bbar: new Ext.PagingToolbar({
	        pageSize: ordersPageLimit,
	        store: orderStore,
	        displayInfo: true,
	        listeners:{
	        	beforechange: function(pagger){
	        		Ext.getCmp('<?php echo $compName;?>').getEl().mask('<?php echo $LangPack->GetLabel("CRM_all", "loading_mask_text","Posodabljanje...");?>');
	        		Ext.getCmp('<?php echo $compName;?>').getStore().proxy.setApi({read : '<?php echo $ajaxFilter;?>' });
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('action','dataFilter');
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('form','orders');
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('disable_pagging', Ext.getCmp('disablePagging_<?php echo $suffix;?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('all_checked',Ext.getCmp('all_checkboxes_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('time_from',Ext.getCmp('time_from_<?php echo $suffix; ?>').getRawValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('time_to',Ext.getCmp('time_to_<?php echo $suffix; ?>').getRawValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('all_states',Ext.getCmp('check_all_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_ordered',Ext.getCmp('ordered_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_delivered',Ext.getCmp('delivered_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_date_changed',Ext.getCmp('date_changed_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_storno_team',Ext.getCmp('storno_team_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_storno_delivery',Ext.getCmp('storno_delivery_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_product_return',Ext.getCmp('product_return_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_credit_denial',Ext.getCmp('credit_denial_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('state_reclamation',Ext.getCmp('reclamation_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('all_storage',Ext.getCmp('check_all_storage_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('storage_own_delivery',Ext.getCmp('own_delivery_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('storage_central_delivery',Ext.getCmp('central_delivery_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('teams',Ext.getCmp('teams_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('assistant',Ext.getCmp('assistant_<?php echo $suffix; ?>').getValue());
	        		Ext.getCmp('<?php echo $compName;?>').getStore().setBaseParam('ppid',Ext.getCmp('ppid_<?php echo $suffix; ?>').getValue());	
	        	}
	        },
	        displayMsg: '<?php echo $LangPack->GetLabel("CRM_order_panel", "pagger_display_msg","Naročila ");?> {0} - {1} of {2}',
	        emptyMsg: "<?php echo $LangPack->GetLabel("CRM_order_panel", "pagger_empty_msg","Ni naročil");?>"
	    }),
       	listeners: {
       		afteredit : function(e) {
       			if(e.field == "order_status"){
       				if(e.value == 1 || e.value == 8){
		       			Ext.Ajax.request({
		       				url:'<?php echo $ajaxOrders;?>',
		       				params: { 
		       					action: 'update' ,
								id		: e.record.data.id,
							    field	: e.field,
								value 	: e.value,
								oldValue: e.originalValue					
		       				},
							success : function(resp,opt){ 
								e.record.commit();
								Ext.getCmp('<?php echo $compName;?>').getEl().mask('<?php echo $LangPack->GetLabel("CRM_all", "loading_mask_text","Posodabljanje...");?>');
								var store = Ext.getCmp('<?php echo $compName;?>').getStore();
								store.load(store.lastOptions);
							}							  							
						})
					}
				}else{
					Ext.Ajax.request({
	       				url:'<?php echo $ajaxOrders;?>',
	       				params: { 
	       					action: 'update' ,
							id		: e.record.data.id,
						    field	: e.field,
							value 	: e.value,
							oldValue: e.originalValue					
	       				},
						success : function(resp,opt){ 
							e.record.commit();
							
						}							  							
					})
				}
			}	
		}     
    });

var <?php echo $tabName;?> = new Ext.Panel({
	id:'<?php echo $tabName;?>',
	title: '<?php echo $LangPack->GetLabel("CRM_order_panel", "tab_title","Naročila");?>',
	defaults:{split:true,border:false, bodyStyle: 'padding: 10px'},
	layout:'border',
	border: false,
	autoSroll: true,
	closable:true,
	items:[ <?php include(PATH_TO_ROOT."CRM/_forms/filter/panell.filter.php"); ?>, <?php echo $compName;?> ]
});
  
Ext.getCmp('mainTabPanel').add(<?php echo $tabName; ?>).show();
Ext.getCmp('<?php echo $compName;?>').getEl().mask('<?php echo $LangPack->GetLabel("CRM_all", "loading_mask_text","Posodabljanje...");?>');
<?php echo $compName; ?>.getStore().load({params:{ time_from: '<?php echo date("d.m.Y");?>', time_to: '<?php echo date("d.m.Y");?>' }, callback: function(resp, opt, success){
	if(success){
		Ext.getCmp('<?php echo $compName;?>').getEl().unmask();
	}
}}); 
<?php if(isset($_POST['CRM'])) {?>
Ext.getCmp('mainTabPanel').on('tabchange',function(panel, tab){
	if(tab != null){
		if(tab.id == "Orders" || tab.id == "Delivery" || tab.id == "Financial"){
			if(!Ext.getCmp('west-panel').collapsed){
				Ext.getCmp('west-panel').collapse();
			}	
		}else{
			if(Ext.getCmp('west-panel').collapsed){
				Ext.getCmp('west-panel').expand();
			}
			var data = tab.id.split('_');
			var title = tab.title.split(' - ');
			Ext.getCmp('StatisticGrid').getEl().mask('<?php echo $LangPack->GetLabel("CRM_all", "loading_mask_text","Posodabljanje..."); ?>');
			Ext.getCmp('StatisticGrid').getStore().load({
				params: { 
					action: 'get',
					project_id: data[1],
					dan: data[3],
					ura: data[4],
					cati_location: data[2]
				},
				callback: function(store, opt, success){
					if(success){
						Ext.getCmp('StatisticGrid').getEl().unmask();
					}
				}
			});
		}
	}
});
<?php }?>