<?php

class  program_data {
	
	private $market;
	
	//****************************************************************************************************************************************//
	
	function __construct() {
		
		try {
			// Get Markets
			$market = array(); 
			$mstmkt_sql  = "select mkt_code,mkt_name,mkt_gmt,mkt_cur from mst_market";
			$mstmkt_rslt = mysql_query($mstmkt_sql);
			if(mysql_num_rows($mstmkt_rslt) >0) {		
				while($mrw = mysql_fetch_assoc($mstmkt_rslt)) {
					$market[$mrw['mkt_code']] = $mrw;
				}
			}
			$this->market = $market;
			mysql_free_result($mstmkt_rslt);
		}
		catch (Exception $e) {

		}
	}
	
	//****************************************************************************************************************************************//
		
	public function fetchdata($srv_mrkt,$srv_type,$chnl_lst,$pstDate,$pedDate,$StTime="0000",$EdTime="3000",$Myresp_SQL="",$TimeZone=8,$pLevel=1,$pBreak=0,$progname="",$sort=1,$sortby='Avg_Rat',$time_slots=array(),$weekanalysis=0) {
		$program_data =array();
		//$progname="LAHZA";
		
		try {		
			// 0. Fetch Respondents - If there is no targets Take full responsents for this survey  otherwise take SQL from parameter
			if(strlen($Myresp_SQL) <=0) {  
				$Myresp_SQL = 'select respid,weight,srv_dt,DATE_FORMAT(srv_dt,"%w") as wday from survey_resp 
								where srv_mrkt = ' . $srv_mrkt . ' 
									  and srv_type = ' . $srv_type . ' 
									  and srv_dt>= "' . $pstDate . '" and srv_dt <=  "' . $pedDate . '"';
			}
			else {
				$Myresp_SQL = 'select respid,weight,srv_dt,DATE_FORMAT(srv_dt,"%w") as wday from survey_resp 
								where respid in ('. $Myresp_SQL . ')
									  and srv_mrkt = ' . $srv_mrkt . ' 
									  and srv_type = ' . $srv_type . ' 
									  and srv_dt>= "' . $pstDate . '" and srv_dt <=  "' . $pedDate . '"';
			}
			
			$Resp_Array = array();
			$Resp_Data_Array = array();
			$Myresp_Rslt = mysql_query($Myresp_SQL);
			while($MResp = mysql_fetch_assoc($Myresp_Rslt)) {
				$Resp_Array[] = $MResp['respid'];
				$Resp_Data_Array[$MResp['srv_dt']][] = $MResp;
			}
			

			mysql_free_result($Myresp_Rslt);
			
			// Extract time slots from starting time and ending time
			if(count($time_slots) >0) {
				$SEL_TTime_Seg = array();
				foreach($time_slots as $ts) {
					$ts_ary = explode("_",$ts);
					for($i=$ts_ary[0];$i<=$ts_ary[1];$i++) {
						$SEL_TTime_Seg[$i] = $i;
					}
				}
			}
			else {
				$SEL_TTime_Seg = array();
				for($i=1;$i<=96;$i++) {
					$SEL_TTime_Seg[$i] = $i;
				}
			}
			
			
			// 1. Extract Channel Viewer Data for targeted audience
			$Viewers_Data = array();
			$sql_7 = 'select srv_dt,DATE_FORMAT(srv_dt,"%w") as wday,chid,tsid,sum(survey_resp.weight) as weight
					  from survey_resp,survey_timesegment
					  where survey_resp.respid=survey_timesegment.respid 
						  and survey_resp.srv_mrkt = ' . $srv_mrkt . ' 
						  and survey_resp.srv_type = ' . $srv_type . ' 
						  and survey_resp.srv_dt  >= "' . $pstDate . '" and srv_dt <=  "' . $pedDate . '" 
						  and survey_resp.respid in (' . implode(",",$Resp_Array) .') 						  
					  group by srv_dt,chid,tsid'; 
					  
			$rslt_7 = mysql_query($sql_7);
			while($rw_pw=mysql_fetch_assoc($rslt_7)) {
				$Viewers_Data[$rw_pw['srv_dt']][$rw_pw['chid']][] = $rw_pw;
			}
			mysql_free_result($rslt_7);	
			
			// Extarct data for filter respondents
			$Viewers_Info = array();
			$sql_7b = 'select survey_resp.respid,survey_resp.weight,chid,tsid,srv_dt,DATE_FORMAT(srv_dt,"%w") as wday
					  from survey_resp,survey_timesegment
					  where survey_resp.respid=survey_timesegment.respid 
						  and survey_resp.srv_mrkt = ' . $srv_mrkt . ' 
						  and survey_resp.srv_type = ' . $srv_type . ' 
						  and survey_resp.srv_dt  >= "' . $pstDate . '" and srv_dt <=  "' . $pedDate . '" 
						  and survey_resp.respid in (' . implode(",",$Resp_Array) .') ';						  

			$rslt_7b = mysql_query($sql_7b);
			while($rw_pw=mysql_fetch_assoc($rslt_7b)) {
				$Viewers_Info[$rw_pw['srv_dt']][$rw_pw['chid']][] = $rw_pw;
			}
			mysql_free_result($rslt_7b);	

			

			// 2. Extract Program data from Program file for specified set of channels ($chnl_lst) for specified starting and ending time
			$pg_sql = "select prog.chid,
						prog.medcd,prog.progname,prog.typoalp,prog.typocode,prog.pdate,prog.pday-1 as pday,prog.l_sttime,prog.l_edtime,
						prog.gmt_sttime,prog.gmt_edtime,prog.mktid,prog.mth,prog.yr,prog.level,
						mst_typo.descript,mst_channels.chname 
						from prog 
						left join mst_typo on left(prog.typocode,2) = mst_typo.code
						left join mst_channels on prog.chid = mst_channels.chid
						where 1=1 ";
			
			if($pLevel!=0) $pg_sql .= ' and level=1 ';
			if($pBreak==0) $pg_sql .= ' and TypoAlp not in ("AA","AB") ';
			if(count($chnl_lst)>0) $pg_sql .= ' and prog.chid in ('. implode(',',$chnl_lst) . ') ';
			if(strlen(trim($progname)) >0)  $pg_sql .= ' and progname like "'. $progname . '" ';
						
						if(count($time_slots) <=0) {
							$pg_sql .= ' and (gmt_sttime between "'. $StTime .'" and "' . $EdTime .'") ';
						}
						
						$pg_sql .= ' and rtrim(ltrim(lower(progname))) != "system abort" ';
						$pg_sql .= ' and left(typocode,2) != "17" ';
						$pg_sql .= ' and left(typocode,4) != "0802" ';
						$pg_sql .= ' and (pdate between "' . $pstDate . '" and "' . $pedDate . '") ';
			$pg_sql .= ' order by prog.chid,pdate,gmt_sttime ';
			
			
			$pg_rslt = mysql_query($pg_sql);
			while($rw_pg=mysql_fetch_assoc($pg_rslt)) {
				if($weekanalysis==0) {
					$PG_DATA_DB[$rw_pg['chid']][$rw_pg['progname']][$rw_pg['pdate']][] = $rw_pg;
				}
				elseif($weekanalysis==1) {
					$PG_DATA_DB[$rw_pg['chid']][$rw_pg['progname']][$rw_pg['pday']][] = $rw_pg;	
				}
				elseif($weekanalysis==2) {
					$mthyr = $rw_pg['yr'].$rw_pg['mth'];
					$PG_DATA_DB[$rw_pg['chid']][$rw_pg['progname']][$mthyr][] = $rw_pg;	
				}
			}
			mysql_free_result($pg_rslt);	


			if($weekanalysis==0) { // Analysis by Date
				$program_data = $this->Analysis_By_Date($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg); 
			}
			elseif($weekanalysis==1) { // Analysis by Week
				$program_data = $this->Analysis_By_Week($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg); 
			}
			elseif($weekanalysis==2) { // Analysis by Month
				$program_data = $this->Analysis_By_Month($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg); 
			}
		


			// Sort Result
			$program_rat = array();
			foreach ($program_data as $prgdata) {    
				$program_rat[] = $prgdata[$sortby];
			}
	
			if($sort==1) {
				if($sortby == "grp" || $sortby == "reach" ||  $sortby == "Avg_Rat") {
					array_multisort($program_rat, SORT_DESC, $program_data);
				}
				else {
					array_multisort($program_rat, SORT_ASC, $program_data);	
				}
			}			
				
			
			
		} 
		catch (Exception $e) {

		}
		
		return $program_data;
	}

	//****************************************************************************************************************************************//
		
	public function Analysis_By_Date($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg) {
		$program_data = array();
		try {

			// 3. Loop through program data for calculating other factors
			$mslno = 1;
			$chid  = 0;

			foreach($PG_DATA_DB as $key_chid=>$rw_chid) {
				foreach($rw_chid as $key_progs=>$rw_progs) {
					foreach($rw_progs as $key_date=>$rw_dates) { 
						foreach($rw_dates as $rw_pg) {
						//---------------//
						
							if($chid != $rw_pg['chid']) {  // For reseting counter on channel change.
								$mslno = 1;
								$chid  = $rw_pg['chid'];
							}
							
							$rw_pg['chname'] = $rw_pg['chname'];
							$rw_pg['progname'] = $rw_pg['progname'];
							$rw_pg['pdate'] = $rw_pg['pdate'];
							$rw_pg['pday'] = $rw_pg['pday'];
							$rw_pg['typology'] = $rw_pg['descript'];
							
							$rw_pg['slno']    = $mslno;
							$pg_date = new DateTime($rw_pg['pdate']);
							
							$rw_pg['pmonth']  = $pg_date->format("m");
							$rw_pg['pcmonth'] = $pg_date->format("F");
							
							$mStime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_sttime']);
							$rw_pg['StTime']  = substr($mStime,0,2) . ":" . substr($mStime,2,2);
							$mEtime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_edtime']);
							$rw_pg['EndTime'] = substr($mEtime,0,2) . ":" . substr($mEtime,2,2);
						
							$mTimeSegSlots = $this->get_time_slots($mStime,$mEtime);
			
							$rw_pg['Tseg1']	   = $mTimeSegSlots[0];
							$rw_pg['Tseg2']	   = $mTimeSegSlots[1];
							
							$rw_pg['mDur'] = $this->calculate_duration($mStime,$mEtime);
			
			
							$ShowThisPrg =false;
							if(in_array($rw_pg['Tseg1'],$SEL_TTime_Seg)) {  //For starting time
								$ShowThisPrg =true;
							}
							else {
								if(in_array($rw_pg['Tseg2'],$SEL_TTime_Seg)) {  //For program already playing in this time slot whose end time is in this time slot
									$ShowThisPrg =true;
								}
							}
							
							
							$OPT_PG_DURS = true;
							if($OPT_PG_DURS == true) { // print only duraion  >5 mins
								$mMins = intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2));
								if($mMins <=5) {
									$ShowThisPrg =false;
								}
							}
			
			
							// 4. Calculate Ratings
							//$ShowThisPrg = true;
							
							$rw_pg['Avg_Rat'] = 0;
							$rw_pg['Reach']   = 0;
							$rw_pg['Share']   = 0;
							$rw_pg['Total_Tv']= 0;
							$rw_pg['Grp']     = 0;
							$rw_pg['Ats_Perc']= 0;
							$rw_pg['Ats']     = 0;
							$rw_pg['Share_Ch']= 0;
							$rw_pg['Share_T'] = 0;
							
							if($ShowThisPrg == true) {
								
								$All_Viewers = $this->filter_resp_weight_sum($rw_pg['pdate'],$Resp_Data_Array);
								$All_Viewers_resp_sql = $this->filter_resp($rw_pg['pdate'],$Resp_Data_Array);
								
								if($All_Viewers <= 0) {  // As there is no Survey Consider data as a weekday
									$prog_date = new DateTime($rw_pg['pdate']);
									$wday = $prog_date->format("w");
			
									$All_Viewers = $this->filter_resp_weight_sum($rw_pg['pdate'],$Resp_Data_Array,$wday);
									$All_Viewers_resp_sql = $this->filter_resp($rw_pg['pdate'],$Resp_Data_Array,$wday);
								}
								
								// Extract viewership data for selected respondents
								if($All_Viewers > 0) { 
									
									$PeopleWatched  = $this->filter_viewers_info_data($Viewers_Info,$rw_pg['pdate'],0,0,0,0,1);
									$PeopleWatchedChnl = $this->filter_viewers_info_data($Viewers_Info,$rw_pg['pdate'],$rw_pg['chid'],0,0,0,1);
									$no_of_Viewers = $this->filter_viewers_info_data($Viewers_Info,$rw_pg['pdate'],$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],0,1);
									$no_of_Dist_Viewers = $this->filter_viewers_info_data($Viewers_Info,$rw_pg['pdate'],$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
									$no_of_Dist_Viewers_totaltv = $this->filter_viewers_info_data($Viewers_Info,$rw_pg['pdate'],0,$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
									
									$reach = 0;
									$Tot_Tv = 0;
									$pShare = 0;
									$Ats	= "00:00";
									$ats_perc = 0;
			
									$mAvg_Rat = 0;
									$mreach   = 0;
									$mpShare  = 0;
									$xAvg_Rat = 0;						
									$xreach   = 0;
									$xpShare  = 0;						
			
									$reach = round(($no_of_Dist_Viewers * 100 ) / $All_Viewers,2);
									$Tot_Tv= round(($no_of_Dist_Viewers_totaltv * 100 ) / $All_Viewers,2);
									if($no_of_Dist_Viewers_totaltv >0) {
										$pShare= round(($no_of_Dist_Viewers * 100 ) / $no_of_Dist_Viewers_totaltv,2);
									}
									
									$rw_pg['Reach'] = $reach;
									$rw_pg['Share'] = $pShare;
									$rw_pg['Total_Tv'] = $Tot_Tv;
									
									$View_Data = $this->filter_viewers_data($Viewers_Data,$rw_pg['pdate'],$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2']);
									$nospots = count($View_Data);
									$Grp = 0;
									$TotSeen = 0;
									foreach($View_Data as $rw_pw) {
											$mPerc = round(($rw_pw['weight'] * 100) / $All_Viewers,2);
											$Grp = $Grp + $mPerc;
											$TotSeen = $TotSeen + $rw_pw['weight'];
									}
			
									$rw_pg['Grp'] = $Grp;
			
									if($nospots >0) {
										$Avg_Rat  = round($Grp / $nospots,2);
									}
									else {
										$Avg_Rat  = 0;
									}
									
									$rw_pg['Avg_Rat'] = $Avg_Rat;
									
									if($no_of_Dist_Viewers >0) {
											$ats_perc = round(($TotSeen * 100) / ($nospots * $no_of_Dist_Viewers),2);
											$mDurMins   = round(intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2)),0);
											$mAts_mins  = round($mDurMins * ($ats_perc/100),0);
											
											$mAtsHrs    = intval(round($mAts_mins / 60,2));
											$mAtsMins   = $mAts_mins - ($mAtsHrs * 60);
											$Ats	    = str_pad($mAtsHrs,2,"0",STR_PAD_LEFT) . ":" . str_pad($mAtsMins,2,"0",STR_PAD_LEFT);
									}
									
									
									$rw_pg['Ats_Perc'] = $ats_perc;
									$rw_pg['Ats'] = $Ats;
									
			
										
									if($PeopleWatchedChnl >0 && $All_Viewers >0) {
											$Share_Ch = round(($Grp * 100) /(($PeopleWatchedChnl * 100) / $All_Viewers),2);
									}
									else {
											$Share_Ch = 0;
									}
										
									if($PeopleWatched >0 && $All_Viewers >0) {
											$Share_T  = round(($Grp * 100) /(($PeopleWatched * 100) / $All_Viewers),2);
									}
									else {
											$Share_T  = 0;
									}
									
									$rw_pg['Share_Ch'] = $Share_Ch;
									$rw_pg['Share_T']  = $Share_T;
									
									
								}
								
								
								$program_data[] = $rw_pg;
								
							}
							// End Calculation
			
							
							
							$mslno++;
					
						
						//---------------//
						} // End of Data array
					} // End of Date loop
				} // End of Programs loop
			} // End of Channels loop			

		}
		catch (Exception $e) {
			
			
		}
			
		return $program_data;

	}
	
	//****************************************************************************************************************************************//	

	public function Analysis_By_Week($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg) {
		$program_data = array();
		try {

			// 3. Loop through program data for calculating other factors
			$mslno = 1;
			$chid  = 0;

			foreach($PG_DATA_DB as $key_chid=>$rw_chid) {
				foreach($rw_chid as $key_progs=>$rw_progs) {
					foreach($rw_progs as $key_date=>$rw_days) { 
						
						$pdates = array();
						foreach($rw_days as $rw_pg_dt) {
							$pdates[$rw_pg_dt['pdate']] =$rw_pg_dt['pdate'];
						}
					
						foreach($rw_days as $rw_pg) {
						//---------------//
						
							if($chid != $rw_pg['chid']) {  // For reseting counter on channel change.
								$mslno = 1;
								$chid  = $rw_pg['chid'];
							}
							
							$rw_pg['chname'] = $rw_pg['chname'];
							$rw_pg['progname'] = $rw_pg['progname'];
							$rw_pg['pdate'] = $rw_pg['pdate'];
							$rw_pg['pday'] = $rw_pg['pday'];
							$rw_pg['typology'] = $rw_pg['descript'];
							
							$rw_pg['slno']    = $mslno;
							$pg_date = new DateTime($rw_pg['pdate']);
							
							$rw_pg['pmonth']  = $pg_date->format("m");
							$rw_pg['pcmonth'] = $pg_date->format("F");
							
							$mStime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_sttime']);
							$rw_pg['StTime']  = substr($mStime,0,2) . ":" . substr($mStime,2,2);
							$mEtime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_edtime']);
							$rw_pg['EndTime'] = substr($mEtime,0,2) . ":" . substr($mEtime,2,2);
						
							$mTimeSegSlots = $this->get_time_slots($mStime,$mEtime);
			
							$rw_pg['Tseg1']	   = $mTimeSegSlots[0];
							$rw_pg['Tseg2']	   = $mTimeSegSlots[1];
							
							$id = $rw_pg['chid'] . "_" . $rw_pg['progname'] . "_" . $rw_pg['pday'] . "_" . $rw_pg['Tseg1'];
							if (array_key_exists($id, $program_data)) {
								$program_data[$id]['episode'] = $program_data[$id]['episode']+1;
							}
							else {
								$rw_pg['episode'] = 1;
								$rw_pg['mDur'] = $this->calculate_duration($mStime,$mEtime);
				
				
								$ShowThisPrg =false;
								if(in_array($rw_pg['Tseg1'],$SEL_TTime_Seg)) {  //For starting time
									$ShowThisPrg =true;
								}
								else {
									if(in_array($rw_pg['Tseg2'],$SEL_TTime_Seg)) {  //For program already playing in this time slot whose end time is in this time slot
										$ShowThisPrg =true;
									}
								}
								
								
								$OPT_PG_DURS = true;
								if($OPT_PG_DURS == true) { // print only duraion  >5 mins
									$mMins = intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2));
									if($mMins <=5) {
										$ShowThisPrg =false;
									}
								}
				
				
								// 4. Calculate Ratings
								//$ShowThisPrg = true;
								
								$rw_pg['Avg_Rat'] = 0;
								$rw_pg['Reach']   = 0;
								$rw_pg['Share']   = 0;
								$rw_pg['Total_Tv']= 0;
								$rw_pg['Grp']     = 0;
								$rw_pg['Ats_Perc']= 0;
								$rw_pg['Ats']     = 0;
								$rw_pg['Share_Ch']= 0;
								$rw_pg['Share_T'] = 0;
								
								if($ShowThisPrg == true) {
									
									if(count($pdates) > 0) {
										$pdates_array = $pdates;
									}
									else {
										$pdates_array = array($rw_pg['pdate']);
									}
									
									$All_Viewers = $this->filter_resp_weight_sum($pdates_array,$Resp_Data_Array);
									$All_Viewers_resp_sql = $this->filter_resp($pdates_array,$Resp_Data_Array);
									
									if($All_Viewers <= 0) {  // As there is no Survey Consider data as a weekday
										$prog_date = new DateTime($rw_pg['pdate']);
										$wday = $prog_date->format("w");
				
										$All_Viewers = $this->filter_resp_weight_sum($pdates_array,$Resp_Data_Array,$wday);
										$All_Viewers_resp_sql = $this->filter_resp($pdates_array,$Resp_Data_Array,$wday);
									}
									
									// Extract viewership data for selected respondents
									if($All_Viewers > 0) { 
										
										$PeopleWatched  = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,0,0,0,0,1);
										$PeopleWatchedChnl = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],0,0,0,1);
										$no_of_Viewers = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],0,1);
										$no_of_Dist_Viewers = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
										$no_of_Dist_Viewers_totaltv = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,0,$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
										
										$reach = 0;
										$Tot_Tv = 0;
										$pShare = 0;
										$Ats	= "00:00";
										$ats_perc = 0;
				
										$mAvg_Rat = 0;
										$mreach   = 0;
										$mpShare  = 0;
										$xAvg_Rat = 0;						
										$xreach   = 0;
										$xpShare  = 0;						
				
										$reach = round(($no_of_Dist_Viewers * 100 ) / $All_Viewers,2);
										$Tot_Tv= round(($no_of_Dist_Viewers_totaltv * 100 ) / $All_Viewers,2);
										if($no_of_Dist_Viewers_totaltv >0) {
											$pShare= round(($no_of_Dist_Viewers * 100 ) / $no_of_Dist_Viewers_totaltv,2);
										}
										
										$rw_pg['Reach'] = $reach;
										$rw_pg['Share'] = $pShare;
										$rw_pg['Total_Tv'] = $Tot_Tv;
										
										$View_Data = $this->filter_viewers_data($Viewers_Data,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2']);
										$nospots = count($View_Data);
										$Grp = 0;
										$TotSeen = 0;
										foreach($View_Data as $rw_pw) {
												$mPerc = round(($rw_pw['weight'] * 100) / $All_Viewers,2);
												$Grp = $Grp + $mPerc;
												$TotSeen = $TotSeen + $rw_pw['weight'];
										}
				
										$rw_pg['Grp'] = $Grp;
				
										if($nospots >0) {
											$Avg_Rat  = round($Grp / $nospots,2);
										}
										else {
											$Avg_Rat  = 0;
										}
										
										$rw_pg['Avg_Rat'] = $Avg_Rat;
										
										if($no_of_Dist_Viewers >0) {
												$ats_perc = round(($TotSeen * 100) / ($nospots * $no_of_Dist_Viewers),2);
												$mDurMins   = round(intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2)),0);
												$mAts_mins  = round($mDurMins * ($ats_perc/100),0);
												
												$mAtsHrs    = intval(round($mAts_mins / 60,2));
												$mAtsMins   = $mAts_mins - ($mAtsHrs * 60);
												$Ats	    = str_pad($mAtsHrs,2,"0",STR_PAD_LEFT) . ":" . str_pad($mAtsMins,2,"0",STR_PAD_LEFT);
										}
										
										
										$rw_pg['Ats_Perc'] = $ats_perc;
										$rw_pg['Ats'] = $Ats;
										
				
											
										if($PeopleWatchedChnl >0 && $All_Viewers >0) {
												$Share_Ch = round(($Grp * 100) /(($PeopleWatchedChnl * 100) / $All_Viewers),2);
										}
										else {
												$Share_Ch = 0;
										}
											
										if($PeopleWatched >0 && $All_Viewers >0) {
												$Share_T  = round(($Grp * 100) /(($PeopleWatched * 100) / $All_Viewers),2);
										}
										else {
												$Share_T  = 0;
										}
										
										$rw_pg['Share_Ch'] = $Share_Ch;
										$rw_pg['Share_T']  = $Share_T;
										
										
									}
									
									
									$program_data[$id] = $rw_pg;
									
								}
							}
							// End Calculation
			
							
							
							$mslno++;
					
						
						//---------------//
						} // End of Data array
					} // End of Date loop
				} // End of Programs loop
			} // End of Channels loop			

		}
		catch (Exception $e) {
			
			
		}
			
		return $program_data;

	}
	
	//****************************************************************************************************************************************//	

	public function Analysis_By_Month($PG_DATA_DB,$Resp_Data_Array,$Viewers_Info,$Viewers_Data,$srv_mrkt,$SEL_TTime_Seg) {
		$program_data = array();
		try {

			// 3. Loop through program data for calculating other factors
			$mslno = 1;
			$chid  = 0;

			foreach($PG_DATA_DB as $key_chid=>$rw_chid) {
				foreach($rw_chid as $key_progs=>$rw_progs) {
					foreach($rw_progs as $key_date=>$rw_days) { 
						
						$pdates = array();
						foreach($rw_days as $rw_pg_dt) {
							$pdates[$rw_pg_dt['pdate']] =$rw_pg_dt['pdate'];
						}
						
						foreach($rw_days as $rw_pg) {
						//---------------//
						
							if($chid != $rw_pg['chid']) {  // For reseting counter on channel change.
								$mslno = 1;
								$chid  = $rw_pg['chid'];
							}
							
							$rw_pg['chname'] = $rw_pg['chname'];
							$rw_pg['progname'] = $rw_pg['progname'];
							$rw_pg['pdate'] = $rw_pg['pdate'];
							$rw_pg['pday'] = $rw_pg['pday'];
							$rw_pg['typology'] = $rw_pg['descript'];
							
							$rw_pg['slno']    = $mslno;
							$pg_date = new DateTime($rw_pg['pdate']);
							
							$rw_pg['pmonth']  = $pg_date->format("m");
							$rw_pg['pcmonth'] = $pg_date->format("F");
							
							$mStime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_sttime']);
							$rw_pg['StTime']  = substr($mStime,0,2) . ":" . substr($mStime,2,2);
							$mEtime = $this->gmttolocal($srv_mrkt,$rw_pg['gmt_edtime']);
							$rw_pg['EndTime'] = substr($mEtime,0,2) . ":" . substr($mEtime,2,2);
						
							$mTimeSegSlots = $this->get_time_slots($mStime,$mEtime);
			
							$rw_pg['Tseg1']	   = $mTimeSegSlots[0];
							$rw_pg['Tseg2']	   = $mTimeSegSlots[1];
							
							$Tesg1Plus  = $rw_pg['Tseg1'] +1;
							$Tesg1Minus = $rw_pg['Tseg1'] -1;
							
							$id = $rw_pg['chid'] . "_" . $rw_pg['progname'] . "_" . $rw_pg['pmonth'] . "_" . $rw_pg['Tseg1'];
							$id1 = $rw_pg['chid'] . "_" . $rw_pg['progname'] . "_" . $rw_pg['pmonth'] . "_" . $Tesg1Plus;
							$id2 = $rw_pg['chid'] . "_" . $rw_pg['progname'] . "_" . $rw_pg['pmonth'] . "_" . $Tesg1Minus;
							

							if (!array_key_exists($id, $program_data)) {
								if (array_key_exists($id1, $program_data)) {
									$id = $id1;
								}
								else {
									if (array_key_exists($id2, $program_data)) {
										$id = $id2;
									}
								}
							}
							
							
							if (array_key_exists($id, $program_data)) {
								$program_data[$id]['episode'] = $program_data[$id]['episode']+1;
							}
							else {
								$rw_pg['episode'] = 1;
								$rw_pg['mDur'] = $this->calculate_duration($mStime,$mEtime);
				
				
								$ShowThisPrg =false;
								if(in_array($rw_pg['Tseg1'],$SEL_TTime_Seg)) {  //For starting time
									$ShowThisPrg =true;
								}
								else {
									if(in_array($rw_pg['Tseg2'],$SEL_TTime_Seg)) {  //For program already playing in this time slot whose end time is in this time slot
										$ShowThisPrg =true;
									}
								}
								
								
								$OPT_PG_DURS = true;
								if($OPT_PG_DURS == true) { // print only duraion  >5 mins
									$mMins = intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2));
									if($mMins <=5) {
										$ShowThisPrg =false;
									}
								}
				
				
								// 4. Calculate Ratings
								//$ShowThisPrg = true;
								
								$rw_pg['Avg_Rat'] = 0;
								$rw_pg['Reach']   = 0;
								$rw_pg['Share']   = 0;
								$rw_pg['Total_Tv']= 0;
								$rw_pg['Grp']     = 0;
								$rw_pg['Ats_Perc']= 0;
								$rw_pg['Ats']     = 0;
								$rw_pg['Share_Ch']= 0;
								$rw_pg['Share_T'] = 0;
								
								if($ShowThisPrg == true) {
									
									if(count($pdates) > 0) {
										$pdates_array = $pdates;
									}
									else {
										$pdates_array = array($rw_pg['pdate']);
									}
									
									$All_Viewers = $this->filter_resp_weight_sum($pdates_array,$Resp_Data_Array);
									$All_Viewers_resp_sql = $this->filter_resp($pdates_array,$Resp_Data_Array);
									
									
									if($All_Viewers <= 0) {  // As there is no Survey Consider data as a weekday
										$prog_date = new DateTime($rw_pg['pdate']);
										$wday = $prog_date->format("w");
				
										$All_Viewers = $this->filter_resp_weight_sum($pdates_array,$Resp_Data_Array,$wday);
										$All_Viewers_resp_sql = $this->filter_resp($pdates_array,$Resp_Data_Array,$wday);
									}
									
									// Extract viewership data for selected respondents
									if($All_Viewers > 0) { 
										
										$PeopleWatched  = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,0,0,0,0,1);
										$PeopleWatchedChnl = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],0,0,0,1);
										$no_of_Viewers = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],0,1);
										$no_of_Dist_Viewers = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
										$no_of_Dist_Viewers_totaltv = $this->filter_viewers_info_data($Viewers_Info,$pdates_array,0,$rw_pg['Tseg1'],$rw_pg['Tseg2'],1,1);
										
										$reach = 0;
										$Tot_Tv = 0;
										$pShare = 0;
										$Ats	= "00:00";
										$ats_perc = 0;
				
										$mAvg_Rat = 0;
										$mreach   = 0;
										$mpShare  = 0;
										$xAvg_Rat = 0;						
										$xreach   = 0;
										$xpShare  = 0;						
				
										$reach = round(($no_of_Dist_Viewers * 100 ) / $All_Viewers,2);
										$Tot_Tv= round(($no_of_Dist_Viewers_totaltv * 100 ) / $All_Viewers,2);
										if($no_of_Dist_Viewers_totaltv >0) {
											$pShare= round(($no_of_Dist_Viewers * 100 ) / $no_of_Dist_Viewers_totaltv,2);
										}
										
										$rw_pg['Reach'] = $reach;
										$rw_pg['Share'] = $pShare;
										$rw_pg['Total_Tv'] = $Tot_Tv;
										
										$View_Data = $this->filter_viewers_data($Viewers_Data,$pdates_array,$rw_pg['chid'],$rw_pg['Tseg1'],$rw_pg['Tseg2']);
										
										$nospots = count($View_Data);
										$Grp = 0;
										$TotSeen = 0;
										foreach($View_Data as $rw_pw) {
												$mPerc = round(($rw_pw['weight'] * 100) / $All_Viewers,2);
												$Grp = $Grp + $mPerc;
												$TotSeen = $TotSeen + $rw_pw['weight'];
										}
				
										$rw_pg['Grp'] = $Grp;
				
										if($nospots >0) {
											$Avg_Rat  = round($Grp / $nospots,2);
										}
										else {
											$Avg_Rat  = 0;
										}
										
										$rw_pg['Avg_Rat'] = $Avg_Rat;
										
										if($no_of_Dist_Viewers >0) {
												$ats_perc = round(($TotSeen * 100) / ($nospots * $no_of_Dist_Viewers),2);
												$mDurMins   = round(intval(substr($rw_pg['mDur'],0,2)) * 60 + intval(substr($rw_pg['mDur'],3,2)),0);
												$mAts_mins  = round($mDurMins * ($ats_perc/100),0);
												
												$mAtsHrs    = intval(round($mAts_mins / 60,2));
												$mAtsMins   = $mAts_mins - ($mAtsHrs * 60);
												$Ats	    = str_pad($mAtsHrs,2,"0",STR_PAD_LEFT) . ":" . str_pad($mAtsMins,2,"0",STR_PAD_LEFT);
										}
										
										
										$rw_pg['Ats_Perc'] = $ats_perc;
										$rw_pg['Ats'] = $Ats;
										
				
											
										if($PeopleWatchedChnl >0 && $All_Viewers >0) {
												$Share_Ch = round(($Grp * 100) /(($PeopleWatchedChnl * 100) / $All_Viewers),2);
										}
										else {
												$Share_Ch = 0;
										}
											
										if($PeopleWatched >0 && $All_Viewers >0) {
												$Share_T  = round(($Grp * 100) /(($PeopleWatched * 100) / $All_Viewers),2);
										}
										else {
												$Share_T  = 0;
										}
										
										$rw_pg['Share_Ch'] = $Share_Ch;
										$rw_pg['Share_T']  = $Share_T;
										
										
									}
									
									
									$program_data[$id] = $rw_pg;
									
								}
							}
							// End Calculation
			
							
							
							$mslno++;
					
						
						//---------------//
						} // End of Data array
					} // End of Date loop
				} // End of Programs loop
			} // End of Channels loop			

		}
		catch (Exception $e) {
			
			
		}
			
		return $program_data;

	}

	//****************************************************************************************************************************************//	
	
	public function Average_Monthwise($PG_Data_Array) {
		
		$Avg_PG = array();
		
		try {
			foreach($PG_Data_Array as $PG_Data) {
				
				$id = $PG_Data['chid'] . "_" . $PG_Data['medcd'] . "_" . $PG_Data['progname'] . "_" . $PG_Data['pmonth'];
				
				if (array_key_exists($id, $Avg_PG)) {
					
					$Avg_PG[$id]['episode']	 = $Avg_PG[$id]['episode'] + 1;

					if($PG_Data['Avg_Rat']>0) {
						
						$Avg_PG[$id]['pg_episode']	 = $Avg_PG[$id]['pg_episode'] + 1;

						
						if($Avg_PG[$id]['Min_Avg_Rat'] > $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Min_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Min_Reach'] > $PG_Data['Reach']) {
							$Avg_PG[$id]['Min_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Min_Share'] > $PG_Data['Share']) {
							$Avg_PG[$id]['Min_Share']  = $PG_Data['Share'];
						}

						if($Avg_PG[$id]['Max_Avg_Rat'] < $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Max_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Max_Reach'] < $PG_Data['Reach']) {
							$Avg_PG[$id]['Max_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Max_Share'] < $PG_Data['Share']) {
							$Avg_PG[$id]['Max_Share']  = $PG_Data['Share'];
						}

						$Avg_PG[$id]['Avg_Rat']  = $Avg_PG[$id]['Avg_Rat'] + $PG_Data['Avg_Rat'];
						$Avg_PG[$id]['Reach']    = $Avg_PG[$id]['Reach'] + $PG_Data['Reach'];
						$Avg_PG[$id]['Share']    = $Avg_PG[$id]['Share'] + $PG_Data['Share'];
						$Avg_PG[$id]['Grp']  	 = $Avg_PG[$id]['Grp'] 	   + $PG_Data['Grp'];
						$Avg_PG[$id]['Total_Tv']  	 = $Avg_PG[$id]['Total_Tv'] 	   + $PG_Data['Total_Tv'];
						$Avg_PG[$id]['Ats_Perc']  	 = $Avg_PG[$id]['Ats_Perc'] 	   + $PG_Data['Ats_Perc'];
						$Avg_PG[$id]['Share_Ch']  	 = $Avg_PG[$id]['Share_Ch'] 	   + $PG_Data['Share_Ch'];
						$Avg_PG[$id]['Share_T']  	 = $Avg_PG[$id]['Share_T'] 	   	   + $PG_Data['Share_T'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min']  	 = $Avg_PG[$id]['Ats_Min'] 	   + $MinDur;
						
					}
				}
				else {
					$PG_Data['episode'] = 1;
					
					if($PG_Data['Avg_Rat']>0) {
						$PG_Data['pg_episode'] = 1;
						$PG_Data['Min_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Min_Reach']   = $PG_Data['Reach'];
						$PG_Data['Min_Share']   = $PG_Data['Share'];

						$PG_Data['Max_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Max_Reach']   = $PG_Data['Reach'];
						$PG_Data['Max_Share']   = $PG_Data['Share'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min'] = $MinDur;
						
						foreach($PG_Data as $KYPG => $PGDT) {
							$Avg_PG[$id][$KYPG] = $PGDT;
						}
					}
				}
			}

			foreach($Avg_PG as $ky=>$Avg_PG_Data) {
				$Avg_PG[$ky]['Avg_Rat'] = round($Avg_PG_Data['Avg_Rat'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Reach']   = round($Avg_PG_Data['Reach'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share']   = round($Avg_PG_Data['Share'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Grp'] 	= round($Avg_PG_Data['Grp'] / $Avg_PG_Data['pg_episode'],2);
				
				$Avg_PG[$ky]['Total_Tv'] 	= round($Avg_PG_Data['Total_Tv'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Ats_Perc'] 	= round($Avg_PG_Data['Ats_Perc'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share_Ch'] 	= round($Avg_PG_Data['Share_Ch'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share_T'] 	= round($Avg_PG_Data['Share_T'] / $Avg_PG_Data['pg_episode'],2);

				$Ats = round($Avg_PG_Data['Ats_Min'] / $Avg_PG_Data['pg_episode'],0);
				
				$hr = intval($Ats / 60);
				$min = $Ats - ($hr * 60);
				$Avg_PG[$ky]['Ats']			= str_pad($hr,2,"0",STR_PAD_RIGHT) . ":" . str_pad($min,2,"0",STR_PAD_RIGHT);
				
			}			
			
			// Sort Result
			$sortby = "Avg_Rat";
			$sort=1;
			$program_data = array();
			foreach ($Avg_PG as $prgdata) {    
				$program_data[] = $prgdata[$sortby];
			}
	
			if($sort==1) {
				if($sortby == "grp" || $sortby == "reach" ||  $sortby == "Avg_Rat") {
					array_multisort($program_data, SORT_DESC, $Avg_PG);
				}
				else {
					array_multisort($program_data, SORT_ASC, $Avg_PG);	
				}
			}				
			
		}
		catch (Exception $e) {

		}		

		return $Avg_PG;
	}


	//****************************************************************************************************************************************//	
	
	public function Average_Weekwise($PG_Data_Array) {
		
		$Avg_PG = array();
		
		try {
			foreach($PG_Data_Array as $PG_Data) {
				
				$id = $PG_Data['chid'] . "_" . $PG_Data['medcd'] . "_" . $PG_Data['progname'] . "_" . $PG_Data['pday'];
				
				if (array_key_exists($id, $Avg_PG)) {
					
					$Avg_PG[$id]['episode']	 = $Avg_PG[$id]['episode'] + 1;

					if($PG_Data['Avg_Rat']>0) {
						
						$Avg_PG[$id]['pg_episode']	 = $Avg_PG[$id]['pg_episode'] + 1;

						
						if($Avg_PG[$id]['Min_Avg_Rat'] > $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Min_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Min_Reach'] > $PG_Data['Reach']) {
							$Avg_PG[$id]['Min_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Min_Share'] > $PG_Data['Share']) {
							$Avg_PG[$id]['Min_Share']  = $PG_Data['Share'];
						}

						if($Avg_PG[$id]['Max_Avg_Rat'] < $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Max_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Max_Reach'] < $PG_Data['Reach']) {
							$Avg_PG[$id]['Max_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Max_Share'] < $PG_Data['Share']) {
							$Avg_PG[$id]['Max_Share']  = $PG_Data['Share'];
						}

						$Avg_PG[$id]['Avg_Rat']  = $Avg_PG[$id]['Avg_Rat'] + $PG_Data['Avg_Rat'];
						$Avg_PG[$id]['Reach']    = $Avg_PG[$id]['Reach'] + $PG_Data['Reach'];
						$Avg_PG[$id]['Share']    = $Avg_PG[$id]['Share'] + $PG_Data['Share'];
						$Avg_PG[$id]['Grp']  	 = $Avg_PG[$id]['Grp'] 	   + $PG_Data['Grp'];
						$Avg_PG[$id]['Total_Tv']  	 = $Avg_PG[$id]['Total_Tv'] 	   + $PG_Data['Total_Tv'];
						$Avg_PG[$id]['Ats_Perc']  	 = $Avg_PG[$id]['Ats_Perc'] 	   + $PG_Data['Ats_Perc'];
						$Avg_PG[$id]['Share_Ch']  	 = $Avg_PG[$id]['Share_Ch'] 	   + $PG_Data['Share_Ch'];
						$Avg_PG[$id]['Share_T']  	 = $Avg_PG[$id]['Share_T'] 	   	   + $PG_Data['Share_T'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min']  	 = $Avg_PG[$id]['Ats_Min'] 	   + $MinDur;
						
					}
				}
				else {
					$PG_Data['episode'] = 1;
					
					if($PG_Data['Avg_Rat']>0) {
						$PG_Data['pg_episode'] = 1;
						$PG_Data['Min_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Min_Reach']   = $PG_Data['Reach'];
						$PG_Data['Min_Share']   = $PG_Data['Share'];

						$PG_Data['Max_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Max_Reach']   = $PG_Data['Reach'];
						$PG_Data['Max_Share']   = $PG_Data['Share'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min'] = $MinDur;
						
						foreach($PG_Data as $KYPG => $PGDT) {
							$Avg_PG[$id][$KYPG] = $PGDT;
						}
					}
				}
			}

			foreach($Avg_PG as $ky=>$Avg_PG_Data) {
				$Avg_PG[$ky]['Avg_Rat'] = round($Avg_PG_Data['Avg_Rat'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Reach']   = round($Avg_PG_Data['Reach'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share']   = round($Avg_PG_Data['Share'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Grp'] 	= round($Avg_PG_Data['Grp'] / $Avg_PG_Data['pg_episode'],2);
				
				$Avg_PG[$ky]['Total_Tv'] 	= round($Avg_PG_Data['Total_Tv'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Ats_Perc'] 	= round($Avg_PG_Data['Ats_Perc'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share_Ch'] 	= round($Avg_PG_Data['Share_Ch'] / $Avg_PG_Data['pg_episode'],2);
				$Avg_PG[$ky]['Share_T'] 	= round($Avg_PG_Data['Share_T'] / $Avg_PG_Data['pg_episode'],2);

				$Ats = round($Avg_PG_Data['Ats_Min'] / $Avg_PG_Data['pg_episode'],0);
				
				$hr = intval($Ats / 60);
				$min = $Ats - ($hr * 60);
				$Avg_PG[$ky]['Ats']			= str_pad($hr,2,"0",STR_PAD_RIGHT) . ":" . str_pad($min,2,"0",STR_PAD_RIGHT);
				
			}			
			
			// Sort Result
			$sortby = "Avg_Rat";
			$sort=1;
			$program_data = array();
			foreach ($Avg_PG as $prgdata) {    
				$program_data[] = $prgdata[$sortby];
			}
	
			if($sort==1) {
				if($sortby == "grp" || $sortby == "reach" ||  $sortby == "Avg_Rat") {
					array_multisort($program_data, SORT_DESC, $Avg_PG);
				}
				else {
					array_multisort($program_data, SORT_ASC, $Avg_PG);	
				}
			}				
			
		}
		catch (Exception $e) {

		}		

		return $Avg_PG;
	}

	//****************************************************************************************************************************************//	
	
	public function Average_Datewise($PG_Data_Array) {
		
		$Avg_PG = array();
		
		try {
			foreach($PG_Data_Array as $PG_Data) {
				
				$id = $PG_Data['chid'] . "_" . $PG_Data['medcd'] . "_" . $PG_Data['progname'] . "_" . $PG_Data['pdate'];
				
				if (array_key_exists($id, $Avg_PG)) {
					if($PG_Data['Avg_Rat']>0) {
						$Avg_PG[$id]['episode']	 = $Avg_PG[$id]['episode'] + 1;

						if($Avg_PG[$id]['Min_Avg_Rat'] > $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Min_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Min_Reach'] > $PG_Data['Reach']) {
							$Avg_PG[$id]['Min_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Min_Share'] > $PG_Data['Share']) {
							$Avg_PG[$id]['Min_Share']  = $PG_Data['Share'];
						}

						if($Avg_PG[$id]['Max_Avg_Rat'] < $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Max_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Max_Reach'] < $PG_Data['Reach']) {
							$Avg_PG[$id]['Max_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Max_Share'] < $PG_Data['Share']) {
							$Avg_PG[$id]['Max_Share']  = $PG_Data['Share'];
						}

						$Avg_PG[$id]['Avg_Rat']  = $Avg_PG[$id]['Avg_Rat'] + $PG_Data['Avg_Rat'];
						$Avg_PG[$id]['Reach']    = $Avg_PG[$id]['Reach'] + $PG_Data['Reach'];
						$Avg_PG[$id]['Share']    = $Avg_PG[$id]['Share'] + $PG_Data['Share'];
						$Avg_PG[$id]['Grp']  	 = $Avg_PG[$id]['Grp'] 	   + $PG_Data['Grp'];
						$Avg_PG[$id]['Total_Tv']  	 = $Avg_PG[$id]['Total_Tv'] 	   + $PG_Data['Total_Tv'];
						$Avg_PG[$id]['Ats_Perc']  	 = $Avg_PG[$id]['Ats_Perc'] 	   + $PG_Data['Ats_Perc'];
						$Avg_PG[$id]['Share_Ch']  	 = $Avg_PG[$id]['Share_Ch'] 	   + $PG_Data['Share_Ch'];
						$Avg_PG[$id]['Share_T']  	 = $Avg_PG[$id]['Share_T'] 	   	   + $PG_Data['Share_T'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min']  	 = $Avg_PG[$id]['Ats_Min'] 	   + $MinDur;
						
					}
				}
				else {
					if($PG_Data['Avg_Rat']>0) {
						$PG_Data['episode'] = 1;
						$PG_Data['Min_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Min_Reach']   = $PG_Data['Reach'];
						$PG_Data['Min_Share']   = $PG_Data['Share'];

						$PG_Data['Max_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Max_Reach']   = $PG_Data['Reach'];
						$PG_Data['Max_Share']   = $PG_Data['Share'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min'] = $MinDur;
						
						foreach($PG_Data as $KYPG => $PGDT) {
							$Avg_PG[$id][$KYPG] = $PGDT;
						}
					}
				}
			}

			foreach($Avg_PG as $ky=>$Avg_PG_Data) {
				$Avg_PG[$ky]['Avg_Rat'] = round($Avg_PG_Data['Avg_Rat'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Reach']   = round($Avg_PG_Data['Reach'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share']   = round($Avg_PG_Data['Share'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Grp'] 	= round($Avg_PG_Data['Grp'] / $Avg_PG_Data['episode'],2);
				
				$Avg_PG[$ky]['Total_Tv'] 	= round($Avg_PG_Data['Total_Tv'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Ats_Perc'] 	= round($Avg_PG_Data['Ats_Perc'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share_Ch'] 	= round($Avg_PG_Data['Share_Ch'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share_T'] 	= round($Avg_PG_Data['Share_T'] / $Avg_PG_Data['episode'],2);

				$Ats = round($Avg_PG_Data['Ats_Min'] / $Avg_PG_Data['episode'],0);
				
				$hr = intval($Ats / 60);
				$min = $Ats - ($hr * 60);
				$Avg_PG[$ky]['Ats']			= str_pad($hr,2,"0",STR_PAD_RIGHT) . ":" . str_pad($min,2,"0",STR_PAD_RIGHT);
				
			}			
			
			// Sort Result
			$sortby = "Avg_Rat";
			$sort=1;
			$program_data = array();
			foreach ($Avg_PG as $prgdata) {    
				$program_data[] = $prgdata[$sortby];
			}
	
			if($sort==1) {
				if($sortby == "grp" || $sortby == "reach" ||  $sortby == "Avg_Rat") {
					array_multisort($program_data, SORT_DESC, $Avg_PG);
				}
				else {
					array_multisort($program_data, SORT_ASC, $Avg_PG);	
				}
			}				
			
		}
		catch (Exception $e) {

		}		

		return $Avg_PG;
	}

	//****************************************************************************************************************************************//
	
	public function Average_PeriodWise($PG_Data_Array) {
		
		$Avg_PG = array();
		
		try {
			foreach($PG_Data_Array as $PG_Data) {
				
				$id = $PG_Data['chid'] . "_" . $PG_Data['medcd'] . "_" . $PG_Data['progname'];
				
				if (array_key_exists($id, $Avg_PG)) {
					if($PG_Data['Avg_Rat']>0) {
						$Avg_PG[$id]['episode']	 = $Avg_PG[$id]['episode'] + 1;

						if($Avg_PG[$id]['Min_Avg_Rat'] > $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Min_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Min_Reach'] > $PG_Data['Reach']) {
							$Avg_PG[$id]['Min_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Min_Share'] > $PG_Data['Share']) {
							$Avg_PG[$id]['Min_Share']  = $PG_Data['Share'];
						}

						if($Avg_PG[$id]['Max_Avg_Rat'] < $PG_Data['Avg_Rat']) {
							$Avg_PG[$id]['Max_Avg_Rat']  = $PG_Data['Avg_Rat'];
						}
						if($Avg_PG[$id]['Max_Reach'] < $PG_Data['Reach']) {
							$Avg_PG[$id]['Max_Reach']  = $PG_Data['Reach'];
						}
						if($Avg_PG[$id]['Max_Share'] < $PG_Data['Share']) {
							$Avg_PG[$id]['Max_Share']  = $PG_Data['Share'];
						}

						$Avg_PG[$id]['Avg_Rat']  = $Avg_PG[$id]['Avg_Rat'] + $PG_Data['Avg_Rat'];
						$Avg_PG[$id]['Reach']    = $Avg_PG[$id]['Reach'] + $PG_Data['Reach'];
						$Avg_PG[$id]['Share']    = $Avg_PG[$id]['Share'] + $PG_Data['Share'];
						$Avg_PG[$id]['Grp']  	 = $Avg_PG[$id]['Grp'] 	   + $PG_Data['Grp'];
						$Avg_PG[$id]['Total_Tv']  	 = $Avg_PG[$id]['Total_Tv'] 	   + $PG_Data['Total_Tv'];
						$Avg_PG[$id]['Ats_Perc']  	 = $Avg_PG[$id]['Ats_Perc'] 	   + $PG_Data['Ats_Perc'];
						$Avg_PG[$id]['Share_Ch']  	 = $Avg_PG[$id]['Share_Ch'] 	   + $PG_Data['Share_Ch'];
						$Avg_PG[$id]['Share_T']  	 = $Avg_PG[$id]['Share_T'] 	   	   + $PG_Data['Share_T'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min']  	 = $Avg_PG[$id]['Ats_Min'] 	   + $MinDur;
						
					}
				}
				else {
					if($PG_Data['Avg_Rat']>0) {
						$PG_Data['episode'] = 1;
						$PG_Data['Min_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Min_Reach']   = $PG_Data['Reach'];
						$PG_Data['Min_Share']   = $PG_Data['Share'];

						$PG_Data['Max_Avg_Rat'] = $PG_Data['Avg_Rat'];
						$PG_Data['Max_Reach']   = $PG_Data['Reach'];
						$PG_Data['Max_Share']   = $PG_Data['Share'];
						
						$Ats_Ary = explode(":",$PG_Data['Ats']);
						$MinDur = (intval($Ats_Ary[0]) * 60) + intval($Ats_Ary[1]);
						$Avg_PG[$id]['Ats_Min'] = $MinDur;
						
						foreach($PG_Data as $KYPG => $PGDT) {
							$Avg_PG[$id][$KYPG] = $PGDT;
						}
					}
				}
			}

			foreach($Avg_PG as $ky=>$Avg_PG_Data) {
				$Avg_PG[$ky]['Avg_Rat'] = round($Avg_PG_Data['Avg_Rat'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Reach']   = round($Avg_PG_Data['Reach'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share']   = round($Avg_PG_Data['Share'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Grp'] 	= round($Avg_PG_Data['Grp'] / $Avg_PG_Data['episode'],2);
				
				$Avg_PG[$ky]['Total_Tv'] 	= round($Avg_PG_Data['Total_Tv'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Ats_Perc'] 	= round($Avg_PG_Data['Ats_Perc'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share_Ch'] 	= round($Avg_PG_Data['Share_Ch'] / $Avg_PG_Data['episode'],2);
				$Avg_PG[$ky]['Share_T'] 	= round($Avg_PG_Data['Share_T'] / $Avg_PG_Data['episode'],2);

				$Ats = round($Avg_PG_Data['Ats_Min'] / $Avg_PG_Data['episode'],0);
				
				$hr = intval($Ats / 60);
				$min = $Ats - ($hr * 60);
				$Avg_PG[$ky]['Ats']			= str_pad($hr,2,"0",STR_PAD_RIGHT) . ":" . str_pad($min,2,"0",STR_PAD_RIGHT);
				
			}			
			
			// Sort Result
			$sortby = "Avg_Rat";
			$sort=1;
			$program_data = array();
			foreach ($Avg_PG as $prgdata) {    
				$program_data[] = $prgdata[$sortby];
			}
	
			if($sort==1) {
				if($sortby == "grp" || $sortby == "reach" ||  $sortby == "Avg_Rat") {
					array_multisort($program_data, SORT_DESC, $Avg_PG);
				}
				else {
					array_multisort($program_data, SORT_ASC, $Avg_PG);	
				}
			}				
			
		}
		catch (Exception $e) {

		}		

		return $Avg_PG;
	}

	//****************************************************************************************************************************************//
	
	public function gmttolocal($toMarket,$sTseg) {
		$localTime   = $sTseg;

		try {
			
			$GmtDiff = $this->market[$toMarket]['mkt_gmt'];
			$lnST = intval(substr($sTseg,0,2))*60 + intval(substr($sTseg,2,2));

			if($GmtDiff == 0) {
				$localTime = $sTseg;
			}
			else {
				$lnST = $lnST - $GmtDiff;
	
				if($lnST < (6 * 60)) {
					$lnST = $lnST + (24 * 60);
				}
				if($lnST >= (30 * 60)) {
					$lnST = $lnST - (24 * 60);
				}
				$localTime = str_pad(intval($lnST/60),2,'0',STR_PAD_LEFT) . str_pad(intval(($lnST % 60)),2,'0',STR_PAD_LEFT);
			}
			
		}
		catch (Exception $e) {
		
		}			
		return $localTime;
	}

	//****************************************************************************************************************************************//
		
	public function localtogmt($toMarket,$sTseg) {
		$GmtTime   = $sTseg;

		try {
			
			$GmtDiff = $this->market[$toMarket]['mkt_gmt'];
			$lnST = intval(substr($sTseg,0,2))*60 + intval(substr($sTseg,2,2));
			
			if($GmtDiff == 0) {
				$GmtTime = $sTseg;
			}
			else {
				$lnST = $lnST + $GmtDiff;
				
				if($lnST < (6 * 60)) {
					$lnST = $lnST + (24 * 60);
				}
				if($lnST >= (30 * 60)) {
					$lnST = $lnST - (24 * 60);
				}
				$GmtTime = str_pad(intval($lnST/60),2,'0',STR_PAD_LEFT) . str_pad(intval(($lnST % 60)),2,'0',STR_PAD_LEFT);
			}

		}
		catch (Exception $e) {
		
		}			
		return $GmtTime;
	}
	
	//****************************************************************************************************************************************//
		
	public function get_time_slots($pTime1,$pTime2,$mBrk=15,$cDur=1) {
		
		$Rv = array();
		
		try {
		
			$TimeJumper  = ($mBrk * 60) - 1;
			
			$mDur  = $this->calculate_duration($pTime1,$pTime2);
			$mMins = round(intval(substr($mDur,0,2)) * 60 + intval(substr($mDur,3,2)),0);
			$Slot15= $mMins / $mBrk;
			
			if(($mMins % $mBrk) > 0) {
				$Slot15 = intval($Slot15) + 1;
			}

			//**
			$preal_time1 = $this->to_real_time($pTime1);
			$preal_time2 = $this->to_real_time($pTime2);

			if(intval(substr($pTime1,0,2)) >= 24) {
				$mDtime1 = new DateTime('2000-01-02 ' . $preal_time1 . ":00");
			}
			else {
				$mDtime1 = new DateTime('2000-01-01 ' . $preal_time1 . ":00");
			}
				
			if(intval(substr($pTime2,0,2)) >= 24) {
				$mDtime2 = new DateTime('2000-01-02 ' . $preal_time2 . ":00");
			}
			else {
				$mDtime2 = new DateTime('2000-01-01 ' . $preal_time2 . ":00");
			}
	
			if($mDtime1 > $mDtime2) {
				$mDtime2 = $mDtime2->add(new DateInterval('PT86400S')); // skip a day for program starting at 29:00 and ending at 6:30
			}		

			$xDate = new DateTime('2000-01-01 06:00:00');
			$yDate = new DateTime('2000-01-03 05:59:59');


			$xTesg1 = 0;
			while($xDate <= $yDate) {
				if($xDate >= $mDtime1) {
					break;
				}
				$xTesg1 = $xTesg1 + 1;
				$xDate  = $xDate->add(new DateInterval('PT'. $TimeJumper .'S'));
			}

			$xDate = new DateTime('2000-01-01 06:00:00');
			$yDate = new DateTime('2000-01-03 05:59:59');
			
			$xTesg2 = 0;
			while($xDate <= $yDate) {
				if($xDate >= $mDtime2) {
					break;
				}
				$xTesg2 = $xTesg2 + 1;
				$xDate  = $xDate->add(new DateInterval('PT'. $TimeJumper .'S'));
			}
			
			if($xTesg1==0) $xTesg1=1;
			if($xTesg2==0) $xTesg2=1;

			// Avoid time segment to correct the duration of program
			if($cDur == 1) {
				$No_of_tsegs = ($xTesg2 - $xTesg1)+1;
				$remainSlots = $No_of_tsegs - $Slot15;

			
				if($remainSlots != 0) {
					// The remaining slots must be avoided from starting or ending time
					// Time took from first slot
					$FirstSlot = new DateTime('2000-01-01 06:00:00');
						  $inc = (($xTesg1-1) * ($TimeJumper+1));
					$FirstSlot = $FirstSlot->add(new DateInterval('PT'. $inc .'S'));
					
					$tmp_First_Slot      = $FirstSlot;
								   $sinc = ($mBrk-1) * 60;
					$tmp_First_Slot      = $tmp_First_Slot->add(new DateInterval('PT'. $sinc .'S'));
					$interval_First_Slot = $tmp_First_Slot->diff($mDtime1);
					$Sec_From_First_Slot = ($interval_First_Slot->days * 24 * 60 * 60) + ($interval_First_Slot->h * 60 * 60) +  ($interval_First_Slot->i * 60) +  ($interval_First_Slot->s);				
					
					// Time took from Last slot
					$LastSlot  = new DateTime('2000-01-01 06:00:00');
						  $inc = (($xTesg2-1) * ($TimeJumper+1));
					$LastSlot  = $LastSlot->add(new DateInterval('PT'. $inc .'S'));	  
					
					$Dif_From_Last_Slot = $mDtime2->diff($LastSlot);
					$Sec_From_Last_Slot = ($Dif_From_Last_Slot->days * 24 * 60 * 60) + ($Dif_From_Last_Slot->h * 60 * 60) +  ($Dif_From_Last_Slot->i * 60) +  ($Dif_From_Last_Slot->s);	
						
					if($Sec_From_First_Slot >= $Sec_From_Last_Slot) {
						$xTesg2 = $xTesg2 - $remainSlots;
					}
					else {
						$xTesg1 = $xTesg1 + $remainSlots;
					}
			
				}
			}

			$Rv = array(str_pad($xTesg1,2,"0",STR_PAD_LEFT),str_pad($xTesg2,2,"0",STR_PAD_LEFT));
		}
		catch (Exception $e) {

		}
		return $Rv;
	}

	//****************************************************************************************************************************************//
		
	public function calculate_duration($pTime1,$pTime2) {
		$rv_Dur ="00:00";
		
		try {
			
			$preal_time1 = $this->to_real_time($pTime1);
			$preal_time2 = $this->to_real_time($pTime2);
		
			
			if(intval(substr($pTime1,0,2)) >= 24) {
				$mDtime1 = new DateTime('2000-01-02 ' . $preal_time1 . ":00");
			}
			else {
				$mDtime1 = new DateTime('2000-01-01 ' . $preal_time1 . ":00");
			}
				
			if(intval(substr($pTime2,0,2)) >= 24) {
				$mDtime2 = new DateTime('2000-01-02 ' . $preal_time2 . ":00");
			}
			else {
				$mDtime2 = new DateTime('2000-01-01 ' . $preal_time2 . ":00");
			}
	
	
			if($mDtime1 > $mDtime2) {
				$mDtime2 = $mDtime2->add(new DateInterval('PT86400S')); // skip a day for program starting at 29:00 and ending at 6:30
			}
		
			$interval = $mDtime2->diff($mDtime1);
			$DurSec = ($interval->days * 24 * 60 * 60) + ($interval->h * 60 * 60) +  ($interval->i * 60) +  ($interval->s);
			$DurSec = $DurSec + 60;
			$hrs  = intval(round($DurSec / 3600,3));
			$mins = intval(round(($DurSec - ($hrs * 3600))/60,3));
			$Secs = $DurSec - (($hrs * 3600) + ($mins * 60));
			
			$rv_Dur =str_pad($hrs,2,"0",STR_PAD_LEFT) . ":" . str_pad($mins,2,"0",STR_PAD_LEFT);
		}
		catch (Exception $e) {
		
		}

		return $rv_Dur;
	}

	//****************************************************************************************************************************************//
		
	public function to_real_time($pTime) {
		$RealTime = "00:00";
		
		try {
			$fSlot = substr($pTime,0,2);
			if(intval($fSlot) >=24) {
				$fSlot = str_pad(round(intval($fSlot),0) - 24,2,"0",STR_PAD_LEFT);
			}
			$RealTime = $fSlot . ":" . substr($pTime,2,2);
		}
		catch (Exception $e) {
		
		}			
		return $RealTime;
	}
	
	
	//****************************************************************************************************************************************//
		
	public function filter_resp_weight_sum($sdate,$Resp_Dat_Ary) {

		$filtered_array = array();
		$weight = 0;

		if(!is_array($sdate)) {
			$sdate = array($sdate);
		}

		try {
			foreach($sdate as $sdt) {
				if(isset($Resp_Dat_Ary[$sdt])) {
					$filtered_array  = $Resp_Dat_Ary[$sdt];
					foreach($filtered_array as $fary) {
						$weight = $weight + $fary['weight'];
					}
				}
			}
		}
		catch (Exception $e) {
	
		}
					
		return $weight;
	}	

	//****************************************************************************************************************************************//
	
	public function filter_resp($sdate,$Resp_Dat_Ary) {
		$filtered_array = array();
		$resp_id = array();

		if(!is_array($sdate)) {
			$sdate = array($sdate);
		}
		
		try {	
			foreach($sdate as $sdt) {
				if(isset($Resp_Dat_Ary[$sdt])) {
					$filtered_array  = $Resp_Dat_Ary[$sdt];
					foreach($filtered_array as $fary) {
						$resp_id[] = $fary['respid'];
					}
				}
			}

			return $resp_id;
		}
		catch (Exception $e) {

		}			
	}	
	
	//****************************************************************************************************************************************//
		
	public function filter_viewers_data($Viewers_DB,$pdate,$chid,$Tseg1,$Tseg2) {
		
		$Rv_Viewers_DB = array();

		if(!is_array($pdate)) {
			$pdate = array($pdate);
		}

		
		$Full_Data = array();
		
		foreach($pdate as $pdt) {
			if(isset($Viewers_DB[$pdt][$chid])) {
				if(count($Full_Data) >0) {
					array_push($Full_Data,$Viewers_DB[$pdt][$chid]);
				}
				else {
					$Full_Data = $Viewers_DB[$pdt][$chid];
				}
			}
		}
		
		try {	
			foreach($Full_Data as $vdb){
				//if($vdb['srv_dt'] == $pdate && $vdb['chid'] == $chid) {
				if(isset($vdb['tsid'])) {	
					if($vdb['tsid'] >= $Tseg1 && $vdb['tsid'] <= $Tseg2) {
						$Rv_Viewers_DB[] = $vdb;
					}
				}
				//}
			}
		}
		catch (Exception $e) {

		}			
		
		return $Rv_Viewers_DB;
	}

	//****************************************************************************************************************************************//
	
	public function filter_viewers_info_data($Viewers_DB,$pdate,$chid=0,$Tseg1=0,$Tseg2=0,$dist=0,$sum_weight=0) {
		
		$Rv_Viewers_DB = array();

		if(!is_array($pdate)) {
			$pdate = array($pdate);
		}
		
		$Full_Data = array();
		
		if($chid <=0) {
			foreach($pdate as $pdt) {
				if(isset($Viewers_DB[$pdt])) {
					$Full_Data_1 = $Viewers_DB[$pdt];  // If NO channel filter applies
					foreach($Full_Data_1 as $fdb) {
						foreach($fdb as $f_db) {
							$f_db['chid'] = 0;  // Remove channel info
							$Full_Data[] = $f_db;  // Data from all channels
						}
					}
				}
			}
		}
		else {
			foreach($pdate as $pdt) {
				if(isset($Viewers_DB[$pdt][$chid])) {
					if(count($Full_Data) >0) {
						array_push($Full_Data,$Viewers_DB[$pdt][$chid]);
					}
					else {
						$Full_Data = $Viewers_DB[$pdt][$chid];  // If channel filter applies
					}
				}
			}
		}
		
		try {	
			foreach($Full_Data as $vdb){
				
				//if($vdb['srv_dt'] == $pdate && $vdb['chid'] == $chid) {
					if($Tseg1 >0 || $Tseg2 >0) {
						if(isset($vdb['tsid'])) {
							if($vdb['tsid'] >= $Tseg1 && $vdb['tsid'] <= $Tseg2) {
								if($dist==1) {  // Consider only unique respondents 
									if($this->in_array_r($vdb['respid'] , $Rv_Viewers_DB) == false){
										$Rv_Viewers_DB[] = $vdb;
									}
								}
								else {  // Consider duplicate respondents 
									$Rv_Viewers_DB[] = $vdb;
								}
							}
						}
					}
					else {  // No time segment para
						if($dist==1) {  // Consider only unique respondents 
							if($this->in_array_r($vdb['respid'] , $Rv_Viewers_DB) == false){
								$Rv_Viewers_DB[] = $vdb;
							}
						}
						else {  // Consider duplicate respondents 
							$Rv_Viewers_DB[] = $vdb;
						}						
					}
				//}
			}
		}
		catch (Exception $e) {

		}			
		
		
		if($sum_weight==1) {
			$weight = 0;
			foreach($Rv_Viewers_DB as $v_db) {
				if(isset($v_db['weight'])) {
					$weight = $weight + $v_db['weight'];
				}
			}
			return $weight;
		}
		else {
			return $Rv_Viewers_DB;
		}
	}
	
	//****************************************************************************************************************************************//
		
	public function in_array_r($item , $array){
	    return preg_match('/"'.$item.'"/i' , json_encode($array));
	}
	
}




?>