<?php

function getTabsForMobileApp($category='', $item='',$type='DOM'){
    $_cat_arr = array();
    $_cat_arr['RM']['E_I']['COAL']=array('COKING', 'NON-COKING');
    $_cat_arr['RM']['DOM']['IRON ORE']=array('ODISHA', 'CHATTISGARH');

    //$_cat_arr['RM']['DOM']['IRON ORE']=array('ODISHA', 'OMC', 'CHATTISGARH','GOA','KARNATAKA');
    $_cat_arr['RM']['DOM']['SCRAP']=array('SHIP BREAKING', 'HMS');
    $_cat_arr['SF']['DOM']['PIG IRON']=array('FOUNDRY GRADE', 'STEEL GRADE');
    $_cat_arr['FL']['DOM']['TMT']=array('Large Scale Producers', 'Medium and Small Scale Producers');
    //$_cat_arr['FL']['DOM']['STRUCTURE']=array('ANGLE', 'DURAGAPUR', 'GHAZIABAD','HYDERABAD','MANDI GOVINDGARH' ,'MUMBAI','RAIPUR');


    //$_cat_arr['RM']['E_I']['COAL']=array('COKING', 'NON-COKING');
    $_cat_arr['RM']['E_I']['SCRAP']=array('SHIP_BREAKING', 'IMPORTED');

    if(isset($_cat_arr[$category][$type][$item])){
        return $_cat_arr[$category][$type][$item];
    }else{
		if($type=='E_I'){
			return qryToCommaSepString("
				Select id from tbl_prices_index_master 
				where page = 'mobileapp' and category = '$category' and trade_type='E_I' and item = '$item'");
		}
		return '';
	}
}

require("/home/steelmin/public_html/hf.php");
require("/home/steelmin/public_html/cf.php");
require("/home/steelmin/public_html/cf_new.php");
//ini_set('display_errors',1);

//$category='FL,FF';///$category = RM/SF/FL,FF(Finish Steel)/L
//
//$_rs_array = getAppListing($memid, $category);
////1.////
//$memid=56350;
//$category='RM';
//
//$_rs_array = getAppListing($memid, $category);

////2.///

/* $memid=17415;
$category='';
$item='';
$trade_type='E_I';
$tab='90';//90 or COKING
$_rs_array = getAppListing($memid, $category, $tab, $item, $trade_type);
 */

/////3.////
/* $memid=17415;
$relation_id = 74;
$price_type_prefix='fob';
$assesment = 'W';
$_rs_array = getGraphDataForId($memid, $relation_id,$price_type_prefix,$assesment);

echo "<pre>";
print_r($_rs_array);  */

function getAppListing($memid='', $category='', $tab='', $item='', $trade_type='', $portfolio='', $price_id='', $sterm=''){

//  echo "memid: $memid\tcategory: $category\ttab: $tab\t$item: $item\t$trade_type: $trade_type" ;
//if($memid==56350){echo "<pre>$item - ".$price_id."</pre>";} 
    require ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $us = new \App\Http\Controllers\Auth\User($memid) ;
    /* $us->getUserServices() ;
//    $temArr = getUserServices($memid);
    $userService = $us->session['W']['userService'];

//    var_dump($us->session) ;
//    var_dump($memid) ;

    $is_show='';
    if($userService=='Upgrade')
        $is_show='Upgrade needed';
    if($userService=='Visitor')
        $is_show='Login needed'; */

    //// $maxCount = getUserServices($memid, $at_palce='mobileapp', $currDateTime);
   $maxCount = $us->getTakenServicesByUser() ;
//if($memid==56350)$maxCount=-1;
 
    if($maxCount==0)
        $is_show='Upgrade';
    if($maxCount==1)
        $is_show='Login'; 

    $sql="Select * from tbl_prices_index_master where page = 'mobileapp' ";
	
	if(!empty($portfolio)){
	
		$fprice = isset($portfolio['f'])?$portfolio['f']:'';
		$cnfprice = isset($portfolio['cnf'])?$portfolio['cnf']:'';
		$fobprice = isset($portfolio['fob'])?$portfolio['fob']:'';	
		 
		if($fprice) $f_price_column_cond = " and f_price_column = 'f'";
		if($cnfprice) $cnf_price_column_cond = " and f_price_column = 'cnf'";
		if($fobprice) $fob_price_column_cond = " and f_price_column = 'fob'";
		$sql='';
		if($fprice)
			$sql="Select id,app_order,assesment,category,item,trade_type,cond_cols_block,cond_cols_val_block,cond_cols_end,'".implode(',',$fprice)."' as cond_cols_val_end,first_col,second_col,f_price_column from tbl_prices_index_master where page = 'mobileapp' $f_price_column_cond and item in (SELECT sub_category FROM `tbl_dom_master`	where id in(0,".implode(',',$fprice)." )) ";
		if($cnfprice){
			if($sql) $sql.= " union all ";
				$sql.=" Select id,app_order,assesment,category,item,trade_type,cond_cols_block,cond_cols_val_block,cond_cols_end,'".implode(',',$cnfprice)."' as cond_cols_val_end,first_col,second_col,f_price_column	from tbl_prices_index_master where page = 'mobileapp' $cnf_price_column_cond and item in (SELECT sub_category FROM `tbl_exim_master`	where id in(0,".implode(',',$cnfprice).") and cnf_fob like '%cnf%') ";
		}if($fobprice){
			if($sql) $sql.= " union all ";
			$sql.="Select id,app_order,assesment,category,item,trade_type,cond_cols_block,cond_cols_val_block,cond_cols_end,'".implode(',',$fobprice)."' as cond_cols_val_end,first_col,second_col,f_price_column from tbl_prices_index_master where page = 'mobileapp' $fob_price_column_cond and item in (SELECT sub_category FROM `tbl_exim_master`	where id in (0,".implode(',',$fobprice).") and cnf_fob like '%fob%')";
		}
	}
	
	 $sql.=" and category not IN ('IN')";
    if($category){
        $category = "'". str_replace(",", "','", $category)."'";
        $sql.=" and category IN ($category)";
    }
	
    if($item)
        $sql.=" and item='$item'";

    if($item)
        $sql.=" and item='$item'";

    if($trade_type)
        $sql.=" and trade_type='$trade_type'";
	
	if($price_id){
        if(strpos($price_id, ":")!==false)
			list($price_id, $f_price_column) = explode(':', $price_id);
		
		$sql.=" and (cond_cols_val_end like '%,$price_id,%' or cond_cols_val_end like '$price_id,%' or cond_cols_val_end like '%,$price_id' or cond_cols_val_end_prices like '%,$price_id,%' or cond_cols_val_end_prices like '$price_id,%' or cond_cols_val_end_prices like '%,$price_id')";
		
		if($f_price_column)
			$sql.=" and f_price_column='$f_price_column'";
	}
	
   if($tab){
		if(strpos($tab, ",")!==false)
			$sql.=" and (tabs in ($tab))";
		else{
			$sql.=" and (tabs in ('$tab'))";
		}
	}else
		$sql.=" and app_order<>999";

	$sql.=" order by
		CASE
			WHEN category LIKE 'RM' THEN 1
			WHEN category LIKE 'SF' THEN 2
			WHEN category LIKE 'FL' THEN 3
			WHEN category LIKE 'FF' THEN 4
			WHEN category LIKE 'FA' THEN 5
			ELSE 99
		END, app_order, item, trade_type desc
	";
	
	$other_condition='';$_page_on='';
	if(!empty($sterm)){
		$other_condition=$sterm;
		$_page_on='search';
	}
	
	//$sql.=" order by position asc";
    /* $sql.=" order by
		CASE
			WHEN category LIKE 'RM' THEN 1
			WHEN category LIKE 'SF' THEN 2
			WHEN category LIKE 'FL' THEN 3
			WHEN category LIKE 'FF' THEN 3
			WHEN category LIKE 'FA' THEN 4
			ELSE 99
		END
	"; */
  // if($memid==56350){echo "prices_index_table : ".$sql;die;}

    $rs1 = mysql_query($sql) or die(mysql_error().$sql);

    $_rs_array = array();

    while($row1 = mysql_fetch_array($rs1,MYSQL_ASSOC)){
		
        $cond_cols_val_end = $row1['val_daily_report'];

        $assesment = $row1['assesment'];
        $item = $row1['item'];
        $trade_type = $row1['trade_type'];
        $cond_cols_block = $row1['cond_cols_block'];
        $cond_cols_val_block = $row1['cond_cols_val_block'];
        $cond_cols_end = $row1['cond_cols_end'];

        if($tab)
            $cond_cols_val_end = $row1['cond_cols_val_end_prices'];
        else
            $cond_cols_val_end = $row1['cond_cols_val_end'];

        //if($tab)
        //$cond_cols_val_end = $row1['cond_cols_val_end_prices'];
		if($price_id)
			$cond_cols_val_end =$price_id;
		
		if(!empty($portfolio)){
		
			if($row1['f_price_column']=='f')$cond_cols_val_end =implode(',',$fprice);
			elseif($row1['f_price_column']=='cnf')$cond_cols_val_end =implode(',',$cnfprice);
			elseif($row1['f_price_column']=='fob')$cond_cols_val_end =implode(',',$fobprice);
			
		}
		
        $first_col = $row1['first_col'];
        $second_col = $row1['second_col'];
        $f_price_column = $row1['f_price_column'];

        $row_id = $row1['id'];
        $page = $row1['page'];
        $category = $row1['category'];

        //$tabs[$item][]= $row1['tabs'];
        $tabs =array();
        $tabs = getTabsForMobileApp($category, $item, $trade_type);
        //echo $category.'--'.$item.'--'.$trade_type."<pre>";print_r($tabs);

        if(empty($tabs) || $item == 'LOGISTICS')
			$tabs=$row_id;
		else if($tabs=='')
			$tabs = $row1['tabs'];
        $date='';

        $first_col = "first_col_replace";
        $second_col = "second_col_replace";

        $_cond_end='';
		
       // if(strpos($cond_cols_val_block, "Secondary")!==false && strtoupper($item)=='TMT' && $cond_cols_val_end==''){
        if(strpos($cond_cols_val_block, "Secondary")!==false && strtoupper($item)=='TMT'){
            //$cond_type_block = "and cond_cols_val_end like '%$_cond_type%'";
          // echo $cond_cols_val_end = "/*/'12MM'" ;
		   $_cond_end=" and resp.cnf_price='12MM'";
//            $cond_cols_val_end = ",12MM" ;
            /* if(strpos($cond_cols_val_end, "12MM")!==false)
                    $_cond_end="resp.cnf_price='12MM'";
                if(strpos($cond_cols_val_end, "28MM")!==false)
                    $_cond_end="resp.cnf_price='28MM'"; */
        }
		if(strtoupper($item)=='STRUCTURE' && $cond_cols_val_block!=''){
			if($cond_cols_val_end=='')
				$_cond_ids = $cond_cols_val_block;
			else
				$_cond_ids = $cond_cols_val_end;
			$stru="SELECT city,group_concat(id) as relation_ids
				FROM `tbl_dom_master`
				WHERE `sub_category` LIKE 'structure'
				and id in ($_cond_ids)
				group by city";
			$rs_stru = mysql_query($stru) or die(mysql_error());
			$mainSql='';
			while($row_stru = mysql_fetch_array($rs_stru,MYSQL_ASSOC)){
				$_cond_cols_block = 'city,id';
				$_cond_cols_val_block = "'".$row_stru['city']."'/*/".$row_stru['relation_ids']."";
				$_cond_cols_end='relation_id';
				$_cond_cols_val_end=$row_stru['relation_ids'];

				$mainSql1 = getPricesNew($assesment,$page='mobileapp',$item,$trade_type, $_cond_cols_block,$_cond_cols_val_block,$_cond_cols_end,$_cond_cols_val_end, $date, $first_col, $second_col,$f_price_column, $_page_on, $next_prev='',$other_condition,$_cond_end);

				if($mainSql)
					$mainSql.=' union all ';
				$mainSql.="(".$mainSql1.")";
			}

		}else
			$mainSql = getPricesNew($assesment,$page='mobileapp',$item,$trade_type, $cond_cols_block,$cond_cols_val_block,$cond_cols_end,$cond_cols_val_end, $date, $first_col, $second_col,$f_price_column, $_page_on, $next_prev='',$other_condition,$_cond_end);
//if($memid==56350){echo "<pre>$item - ".$price_id;} 
        if($item == 'LOGISTICS')
        {
            $mainSql = str_replace("first_col_replace", "res1.delivery_terms as first_col",$mainSql);

            $second_col = "
			CASE
				WHEN res1.f_size <>'' and res1.f_grade <> ''  THEN concat(res1.f_size ,', ', res1.f_grade)
				WHEN res1.f_size <>'' THEN res1.f_size
				WHEN res1.f_grade <> '' THEN res1.f_grade
			END	as second_col";

            $mainSql = str_replace("fob_price", "cnf_price",$mainSql);
            $mainSql = str_replace("second_col_replace", $second_col, $mainSql);

        }elseif(strtolower($f_price_column)=='fob'){
            $mainSql = str_replace("first_col_replace", "concat('FOB ', res1.load_country) as first_col",$mainSql);

            $second_col = "
			CASE
				WHEN res1.f_size <>'' and res1.f_grade <> ''  THEN concat(res1.f_size ,', ', res1.f_grade)
				WHEN res1.f_size <>'' THEN res1.f_size
				WHEN res1.f_grade <> '' THEN res1.f_grade
			END	as second_col";

            $mainSql = str_replace("second_col_replace", $second_col, $mainSql);
            $mainSql = str_replace("cnf_price", "fob_price",$mainSql);
        }elseif(strtolower($f_price_column)=='cnf'){

            $mainSql = str_replace("first_col_replace", "concat('CNF ', res1.unload_country) as first_col",$mainSql);

            $second_col = "
			CASE
				WHEN res1.f_size <>'' and res1.f_grade <> '' and res1.load_country <> '' THEN concat(res1.f_size ,', ', res1.f_grade , ', ', res1.load_country)
				WHEN res1.f_size <>'' and res1.load_country <> '' THEN concat(res1.f_size , ', ', res1.load_country)
				WHEN res1.f_grade <> '' and res1.load_country <> '' THEN concat(res1.f_grade , ', ', res1.load_country)
				WHEN res1.f_size <> '' and res1.load_country = '' THEN res1.f_size
				WHEN res1.f_grade <> '' and res1.load_country = '' THEN res1.f_grade
				WHEN res1.f_size = '' and res1.f_grade = '' and res1.load_country <> '' THEN res1.load_country
			END	as second_col";

            $mainSql = str_replace("fob_price", "cnf_price",$mainSql);
            $mainSql = str_replace("second_col_replace", $second_col, $mainSql);
        }
        else
        {///domestic f prices
            $flag='INDIA';
            $mainSql = str_replace("first_col_replace", "first_col",$mainSql);

            $second_col = "
			CASE
				WHEN res1.f_size <>'' and res1.f_grade <> ''  THEN concat(res1.f_size ,', ', res1.f_grade)
				WHEN res1.f_size <>'' THEN res1.f_size
				WHEN res1.f_grade <> '' THEN res1.f_grade
			END	as second_col";

            $mainSql = str_replace("second_col_replace", $second_col, $mainSql);
        }
        //if(1){ echo "<br>----------<pre>". $mainSql;}
        mysql_query("SET SQL_BIG_SELECTS=1");

        //$mainSql.= " order by first_col, second_col";
        if($cond_cols_val_end){
			if(strpos($cond_cols_val_end, "/*/")!==false)
				list($cond_cols_val_end, $cond_cols) = explode('/*/',$cond_cols_val_end);
            if($cond_cols_val_end && empty($portfolio)){
				if(strtoupper($item)=='STRUCTURE' && $cond_cols_val_block!='')
					$mainSql .= " order by FIELD(resp.relation_id, $cond_cols_val_end), first_col, second_col";
				else
					$mainSql .= " order by FIELD(res1.id, $cond_cols_val_end), first_col, second_col";
			}
			//if(!empty($portfolio))
			//	$mainSql .= " order by res1.item, FIELD(res1.id, $cond_cols_val_end), first_col, second_col";
		}else
		{
			if( strtoupper($item) != 'STRUCTURE' )
				$mainSql.= " order by resp.relation_id, first_col, second_col";
		}
            
		if($memid){
			$mainSql = str_replace('resp.as_on', "resp.as_on, (select count(distinct row_id) from tbl_user_portfolio where user_id = ".$memid." and row_id= resp.relation_id and type='prices') as bookmark", $mainSql);
			//echo "<pre>$mainSql - ".$price_id; require ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );die;
		} 	
		
		// if($memid==78206){echo "<pre>".$mainSql;}
	   $rs=mysql_query($mainSql)or die(mysql_error() . "<pre>".$mainSql);
	
	
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
        {
            //if($memid==27644 && $item=='TMT'){echo "<pre>$item :: $mainSql ::::<br>"; print_R($row);die;} 
            /*old cond*/
            $relation_id = $row['relation_id'];
            $f_price = $row['f_price'];
            $priceDiff = $row['priceDiff'];
            $priceOneWeekAgo = $row['priceOneWeekAgo'];
            $priceOneMonthAgo = $row['priceOneMonthAgo'];
            $priceThreeMonthAgo = $row['priceThreeMonthAgo'];
            $chemical_composition = $row['chemical_composition'];
            $delivery_terms = $row['delivery_terms'];
            $payment = $row['payment'];
            $quantity = $row['quantity'];
            $delivery_period = $row['delivery_period'];
            $taxes = $row['taxes'];
            $currency = $row['currency'];
            $remarks = $row['remarks'];
            $as_on_date = $row['as_on'];
            $bookmark = $row['bookmark'];

            if($is_show==''){///only for paid users
                if($f_price == '-' || $f_price == 'NA' || $f_price == 0 || $f_price == ''){
                    $f_price = 'NA';
                    $priceOneWeekAgo = 'NA';
                    $priceOneMonthAgo = 'NA';
                    $priceThreeMonthAgo = 'NA';
                }
                else {
                    if($priceOneWeekAgo == '-' || $priceOneWeekAgo == 'NA' || $f_price == 0 || $priceOneWeekAgo == '')
                        $priceOneWeekAgo = 'NA';
                    else
                        $priceOneWeekAgo = round($f_price - $priceOneWeekAgo)!=0?formatedPriceChanges($f_price - $priceOneWeekAgo):0;

                    if($priceOneMonthAgo == '-' || $priceOneMonthAgo == 'NA' || $f_price == 0 || $priceOneMonthAgo == '')
                        $priceOneMonthAgo = 'NA';
                    else
                        $priceOneMonthAgo = round($f_price - $priceOneMonthAgo)!=0?formatedPriceChanges($f_price - $priceOneMonthAgo):0;

                    if($priceThreeMonthAgo == '-' || $priceThreeMonthAgo == 'NA' || $f_price == 0 || $priceThreeMonthAgo == '')
                        $priceThreeMonthAgo = 'NA';
                    else
                        $priceThreeMonthAgo = round($f_price - $priceThreeMonthAgo)!=0?formatedPriceChanges($f_price - $priceThreeMonthAgo):0;
                }

                $f_price = formatedPriceChanges($f_price, true, $item, $trade_type);
                $change = formatedPriceChanges($priceDiff);
            }else{
                $f_price = $is_show;
                $change = $is_show;
                $priceOneWeekAgo = $is_show;
                $priceOneMonthAgo = $is_show;
                $priceThreeMonthAgo = $is_show;
				//show login when no login user
				 if($maxCount==1)
					 $bookmark=$is_show;
            }

            $_second_col=array();
            $flag='INDIA';

            $_second_col[] = capitalizeWords($row['second_col']);
			$_item =$item;
            if($item == 'LOGISTICS'){
                $flag=$row['load_country'].','.$row['unload_country'];
				$_item = trim($cond_cols_val_block, "'");
            }
            elseif($f_price_column=='fob'){
                $flag=$row['load_country'];
            }elseif($f_price_column=='cnf'){
                $flag=$row['unload_country'];
                $_second_col=array();
                $second_col = explode( ",", $row['second_col']);
               if(count($second_col)>1){
					$_second_col[0] = capitalizeWords(trim(str_replace($second_col[count($second_col)-1], "", $row['second_col']), ','));
					$_second_col[1] = capitalizeWords($second_col[count($second_col)-1]);
				}else
					$_second_col[0] = $row['second_col'];
            }
			
			if($assesment=='D')$assessment_text = "Daily";
			elseif($assesment=='W')$assessment_text = "Weekly";
			elseif($assesment=='M')$assessment_text = "Monthly";
			
			$_flag_code = $row['cntry_flag'];
            $_rs_array[] = array(
                'item'=>($_item == '' ? '' : $_item),
				'item_name'=>(str_replace("_", " ",$_item) == '' ? '' : str_replace("_", " ",$_item)),
                'row_id'=>$row_id,
				'trade_type'=>($trade_type == '' ? '' : $trade_type),
                'tabs'=>($tabs == '' ? '' : $tabs),
                'relation_id'=>($relation_id == '' ? '' : $relation_id),
                'first_col'=>(capitalizeWords($row['first_col']) == '' ? '' : capitalizeWords($row['first_col'])),
                'second_col'=>($_second_col == '' ? '' : $_second_col),
                'city'=>($row['city'] == '' ? '' : $row['city']),
                'state'=>($row['state'] == '' ? '' : $row['state']),
                'f_grade'=>($row['f_grade'] == '' ? '' : $row['f_grade']),
                'supplier'=>($row['supplier'] == '' ? '' : $row['supplier']),
                'particular'=>($row['particular'] == '' ? '' : $row['particular']),
                'load_country'=>($row['origin_country'] == '' ? '' : $row['origin_country']),
                'unload_country'=>($row['unload_country'] == '' ? '' : $row['unload_country']),
                'f_price_column'=>($f_price_column == '' ? '' : $f_price_column),
                'assesment'=>($assesment == '' ? '' : $assesment),
                'f_price'=>($f_price == '' ? '' : $f_price),
                'change'=>($change == '' ? '' : $change),
                'flag'=>($flag == '' ? '' : $flag),
                'flag_code'=> ($_flag_code == '' ? '' : $_flag_code),
                'as_on_date'=>($as_on_date == '' ? '' : $as_on_date),
                'graph_view' => ($us->session['W']['userType'] == 1 ? true: false ) ,
				'portfolio'=>$bookmark,
                'details'=> array(
                    'One Week Ago'=>($priceOneWeekAgo == '' ? '' : $priceOneWeekAgo),
                    'One Month Ago'=>($priceOneMonthAgo == '' ? '' : $priceOneMonthAgo),
                    'Three Month Ago'=>($priceThreeMonthAgo == '' ? '' : $priceThreeMonthAgo),
                    'Assessment'=>$assessment_text,
					'Chemical Composition'=>($chemical_composition == '' ? '' : $chemical_composition),
                    'Delivery Terms'=>($delivery_terms == '' ? '' : $delivery_terms),
                    'Payment'=>($payment == '' ? '' : $payment),
                    'Remarks'=>($remarks == '' ? '' : $remarks),
                    'Quantity'=>($quantity == '' ? '' : $quantity),
                    'Delivery Period'=>($delivery_period == '' ? '' : $delivery_period),
                    'Taxes'=>($taxes == '' ? '' : $taxes),
                    'Currency'=>($currency == '' ? '' : $currency),
                    'Disclaimer'=>"Indicative Price"
                   
                ),'details2'=> array(
                    array('One Week Ago'=>($priceOneWeekAgo == '' ? '' : $priceOneWeekAgo)),
					array('One Month Ago'=>($priceOneMonthAgo == '' ? '' : $priceOneMonthAgo)),
					array('Three Month Ago'=>($priceThreeMonthAgo == '' ? '' : $priceThreeMonthAgo)),
					array('Assessment'=>$assessment_text),
					array('Chemical Composition'=>($chemical_composition == '' ? '' : $chemical_composition)),
					array('Delivery Terms'=>($delivery_terms == '' ? '' : $delivery_terms)),
					array('Payment'=>($payment == '' ? '' : $payment)),
					array('Remarks'=>($remarks == '' ? '' : $remarks)),
					array('Quantity'=>($quantity == '' ? '' : $quantity)),
					array('Delivery Period'=>($delivery_period == '' ? '' : $delivery_period)),
					array('Taxes'=>($taxes == '' ? '' : $taxes)),
					array('Currency'=>($currency == '' ? '' : $currency)) ,
					array('Disclaimer'=>"Indicative Price")					 
                )
            );
        }
		
    }
	   
    require ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;
}


function getGraphDataForId($memid=0, $relation_id='',$price_type_prefix='f', $assesment = 'W'){
    require ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    //assessment
    $f_date_cond='';$other_cond='';

    $temArr = getUserServices($memid);
    $userService = $temArr['W']['userService'];

    if($userService=='Free Trial'){
        $f_date_cond = date("Y-m-d",strtotime($GLOBALS['currDate'] . '-3 months'));
        $other_cond.= " AND f_date >= '$f_date_cond'";
    }

    $f_price = $price_type_prefix."_price";

    //$_cond = " and relation_id = ".$relation_id;
    if($assesment=='M'){
        $sql = "SELECT
				CONCAT(YEAR(f_date),'-',MONTH(f_date),'-', 01) AS final_date,
				AVG($f_price) as final_price
				FROM tbl_steelprices
				WHERE relation_id = ".$relation_id."
				$other_cond
				GROUP BY  final_date order by f_date ASC
				";
    }else if($assesment=='W'){

        $isLogistics = false;
	    	$isLogistics = qryToCommaSepString ( "
							SELECT id
							FROM `tbl_exim_master`
							WHERE LCASE(sub_category) = 'logistics'
							and id = $relation_id
						");

	    	if($isLogistics) {
		        $sql = "SELECT (
		                    SELECT DATE_ADD(monday, INTERVAL 4 DAY)
		                    FROM tbl_year_week
		                    WHERE f_date >= DATE_ADD(monday, INTERVAL 4 DAY)
		                    AND f_date <= DATE_ADD(sunday, INTERVAL 4 DAY)
		                    ) AS final_date,
		                AVG($f_price) as final_price
		                FROM tbl_steelprices
		                WHERE relation_id = ".$relation_id."
		                $other_cond
		                GROUP BY YEAR(f_date),  final_date
		                order by YEAR(f_date), final_date asc
		                ";
		    } else {
		    	$sql = "SELECT (
		                    SELECT monday
		                    FROM tbl_year_week
		                    WHERE f_date >= monday
		                    AND f_date <= sunday
		                    ) AS final_date,
		                AVG($f_price) as final_price
		                FROM tbl_steelprices
		                WHERE relation_id = ".$relation_id."
		                $other_cond
		                GROUP BY YEAR(f_date),  final_date
		                order by YEAR(f_date), final_date asc
		                ";
		    }

        //SELECT MAX(monday) FROM tbl_year_week WHERE DATE_ADD(f_date, INTERVAL 7 DAY) >= monday AND f_date <= sunday
    }else{
        $sql = "SELECT f_date as final_date,
				$f_price as final_price
				FROM tbl_steelprices
				WHERE relation_id = ".$relation_id."
				$other_cond
				Group by f_date asc";
    }
    //echo $sql;
    $result = mysql_query($sql) or die(mysql_error());

    $_rs_array=array();
    while($row = mysql_fetch_array( $result )) {
        if (strtotime($row['final_date']) )
            $_rs_array[] = array(strtotime($row['final_date']), round($row['final_price'] , 0));
    }
    require ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );
    return $_rs_array;
}

?>
