<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");


$dbConfigCapi = configLoader::loadConfig('capi');
	
$sql = "SELECT  translate_key, translate_text 
				FROM  ".DB_WARPIT_MAIN."._languagePack 
					WHERE id_programme = 2 AND id_language = ".$dbConfigCapi['default-language']." AND sub_page = 'capi'";
	//echo $sql;
$res = $db->SQLexecute($sql);
while ($zad = $db->fetchAssoc($res)) $languagePack[$zad['translate_key']] = $zad['translate_text'];

//var_dump($_SESSION);


if (!$_SESSION['capi']['id_project']) {
	echo "	Ext.Msg.show({
				title:'".$languagePack['project-status']."',
				msg: '".$languagePack['no-project-is-selected']."',
				buttons: Ext.Msg.OK,
				animEl: 'elId',
				icon: Ext.MessageBox.QUESTION
			});";
	exit;
}


$sql = "SELECT * FROM  ".DB_WARPIT_WEBCATI_BASE."._Projects WHERE id = ".$_SESSION['capi']['id_project'];
//echo $sql;
$res = $db->SQLexecute($sql);
$projectINFO = $db->fetchAssoc($res);

$sql = " SELECT a.id_sampleTable, name FROM ".DB_WARPIT_WEBCATI_BASE.".".$projectINFO['proj_name']."___sample as a
			LEFT JOIN  ".DB_WARPIT_WEBCATI_BASE."._CapiTables as b ON a.id_sampleTable = b.id
		 WHERE a.user_id = ".$_SESSION['UserInfo']['id']." AND  a.user_type = ".$_SESSION['UserInfo']['user_type']."
			GROUP BY a.id_sampleTable ";
//echo $sql;
//$db->LogMe($sql);
$res = $db->SQLexecute($sql);
while ($zad = $db->fetchAssoc($res)) {
	$sql = "  
						SELECT a.id as IDsample, b.* FROM ".DB_WARPIT_WEBCATI_BASE.".".$projectINFO['proj_name']."___sample as a
							LEFT JOIN ".DB_WARPIT_WEBCATI_BASE.".capi___".$zad['name']." as b 
								ON a.id_sample = b.id AND a.id_sampleTable = ".$zad['id_sampleTable']." LIMIT 1
					 ";
	
	$res = $db->SQLexecute($sql);
	$zad = $db->fetchAssoc($res);
	foreach ( $zad as $key => $val ) $polja[$key] = $key;
	
	
}

$sql = "SELECT * FROM  ".DB_WARPIT_WEBCATI_BASE."._CapiProperties 
			WHERE 		id_project IN (0, ".$_SESSION['capi']['id_project']." )
					AND setting_name = 'show-sample-fields'
			ORDER BY id_project DESC LIMIT 1 ";
$res = $db->SQLexecute($sql);
$zad = $db->fetchAssoc($res);

$showFields = json_decode($zad['setting_value'],true);

/*

if ($zad['setting_value']) $showFields = explode(",",$zad['setting_value']);
	else $showFields = explode(",","street,address,addon_address,zip,town,name");

$showFields['visit_time'] = "visit_time";
$showFields['appointment_date'] = "appointment_date";
$showFields['number_of_contacts'] = "number_of_contacts";
$showFields['contact_person'] = "contact_person";
$showFields['comment'] = "comment";
$showFields['interview_status_label'] = "interview_status_label"; */

	
?>   // create the Grid
    var CapiSamplePointsGrid = new Ext.grid.EditorGridPanel({
        
    	store: new Ext.data.Store({
			url: '_ajax/ajax.capi.select-sample-points.php',
			remoteGroup:true,
			
			reader: new Ext.data.JsonReader({		
				root:'rows',
				totalProperty : "results",
				idProperty:"id"
				
			},
				new Ext.data.Record.create(
					[
					<?php 
					
						foreach ($polja as $v) {
							if ($v == "IDsample") $p[] = "{ name: \"".$v."\", type: 'int'}";
								elseif ($showFields[$v]) $p[] = "{ name: \"".$v."\", type: 'string'}";
						}
						$p[] = "{ name: \"projName\", type: 'string'}";
						$p[] = "{ name: \"IDsampleTable\", type: 'int'}";
						$p[] = "{ name: \"IDsampleMain\", type: 'int'}";
						$p[] = "{ name: \"visit_time\", type: 'string'}";
						$p[] = "{ name: \"appointment_date\", type: 'string'}";
						$p[] = "{ name: \"number_of_contacts\", type: 'string'}";
						$p[] = "{ name: \"contact_person\", type: 'string'}";
						$p[] = "{ name: \"comment\", type: 'string'}";
						$p[] = "{ name: \"interview_status_label\", type: 'string'}";
						$p[] = "{ name: \"interview_status\", type: 'int'}";
						echo implode(",",$p);
					?>				 	
					]
				)

			)
    	}),
        id: 'CapiSamplePointsGrid',
        border: false,
        title: '<?php echo $languagePack['sample-points'];?>',
    	sm: new Ext.grid.RowSelectionModel({
             singleSelect: true,
              listeners: {
               	  rowselect: function(smObj, rowIndex, record) {
               	  		 if (isTerminatedStatus(record.get('interview_status'))) {
               	  		 	Ext.getCmp('ButtonStartInterview').disable();
               	  		 	Ext.getCmp('ButtonAddVisit').disable();
               	  		 } else  {
               	  		 	Ext.getCmp('ButtonStartInterview').enable();
               	  		 	Ext.getCmp('ButtonAddVisit').enable();
               	  		 }
               	  }
              }
             
       	}),
  		closable : true,
    
        viewConfig: {    
        			getRowClass: function(record, rowIndex, rp, ds){    	
		        			str = '';
		        			//console.log(record.get('interview_status'));
		        			if (record.get('interview_status') == 9) str = 'interrupt'; 
		        			else if (record.get('interview_status') == 8) str = 'appointment';
		        			else if (record.get('interview_status') == 1) str = 'finished';
		        			return 'x-grid3-row-collapsed ' + str;   
	        		}
        },
       	
       	
      	columns: [
      	<?php 
					unset($p);
						foreach ($showFields as $k=>$v) {
						 	 if (!$v['width']) $v['width'] = "100";
							 $p[] = "{header: '".$v['label']."', width:".$v['width'].", sortable: true, dataIndex: '".$k."'  }";
						}
						
						echo implode(",",$p);
		?>
        ],
       // autoExpandColumn: 'idComment',
		
    
       listeners: {
       		
						
			close : function(p) {
						
				showTools();
				hideSampleFunctions();
				
			},
						
       		afteredit : function(e) {
       		
       			Ext.Ajax.request({
       				url:'_ajax/ajax.capi.select-sample-points.php',
       				params: { action: 'update' ,
       								
       							  id: e.record.data.id,
							   field: e.field,
								value : e.value
								
       				},
					success : function(resp,opt){ 
						
						e.record.commit();  
						
					}							  							
				})
			}	
		}
		,
		 tbar: [
		 /*{
        		
        			 text: 'Start',
		           	 handler: function() {
		           	 	rec = CapiSamplePointsGrid.getSelectionModel().getSelected();
		           	 	CallScript("_ajax/ajax.project-actions.php",{ action: 'start-with-interview-sample',  id_sample: rec.get('IDsample')  });
		           	 	if (tb.isVisible())  tb.hide();  Ext.getCmp('MainPanel').doLayout();
		           	 	<?php 

							if ($_POST['mode'] == "form") {
								echo "CapiSamplePointsGrid.destroy();";
							} else {
								echo "WindowAppointment.close();";
							} 
						?>
		             }
			 },
			 
			 {
        		
        			 text: 'Add visit',
		           	 handler: function() {
		           	 	rec = CapiSamplePointsGrid.getSelectionModel().getSelected();
		           	 	CallScript("_forms/window.capi.add-visit.php",{ action: 'start-with-interview-sample',  id_sample: rec.get('IDsample')  });
		             }
			 },'->',*/
				 new Ext.form.ComboBox({
					    typeAhead: true,
					    triggerAction: 'all',
					    fieldLabel: 'Visit Status',
	                    name: 'status_obiska_fake',	                 		                
					    mode: 'local',  
					    store: new Ext.data.ArrayStore({
					        fields: [
					            'status_code',
					            'status_text'
					        ],
					        data: [	
					        		<?php 
					        		$statusGroup[] = "[0, '-----------------']";
					        		$sql = "SELECT * FROM  ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits_status WHERE parent_id = 0 ORDER BY orderBy";
					        		$res = $db->SQLexecute($sql);
					        		while ($zad = $db->fetchAssoc($res)) $statusGroup[] = "[".$zad['id'].", '".$zad['status_group_name']."']";
					        		echo implode(",",$statusGroup);
					        		unset($statusGroup);
					        		
					        		?>
					        		
					        	  ]
					        	   	
					    }),
					   	 valueField: 'status_code',
					   	 displayField: 'status_text',
					   	 hiddenName  : 'status_obiska',
					   	 hiddenValue  : 'status_code',
					   	 listeners: {
					   	 
					   	 	select: function(t) {
					   	 		CapiSamplePointsGrid.getStore().removeAll();
					   	 		CapiSamplePointsGrid.getStore().reload({ params: { StatusConditionGroup: t.getValue() }});
					   	 	}
					   	 }
					   	
				})
			 ]
        	
    });
    
    
CapiSamplePointsGrid.getStore().load();


<?php 

if ($_POST['mode'] == "form") {
?>
	mainTabPanel.add(CapiSamplePointsGrid).show();
<?php
} else {
?>
WindowAppointment = new Ext.Window({
	id:'WindowSelectSamplePoint',
	layout:'fit',
	title: 'Select sample point',
	width:700,
	height:340,
	closeAction:'close',
    plain: true,
    modal: true,
    items:CapiSamplePointsGrid
}).show()    
<?php } ?>


showSampleFunctions();	
hideTools();