<?php

/**

 * Created by PhpStorm.

 * User: varun_2

 * Date: 11-12-2015

 * Time: 14:51

 */



namespace App\Http\Controllers;



use App\Http\Controllers\Action\Logistic;

use App\Http\Controllers\Auth\authentication;

use App\Http\Controllers\Auth\User ;

use Illuminate\Http\JsonResponse;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Response;
use App\Http\Controllers\Action\Common;

use DB;


//require_once $_ENV['COMMON_ROOT_PATH'].'/mapp.php' ;



class PriceController extends Controller

{

    /**

     * Get all filters for pricing module

     */



    private $category_corelation = [

        "RAW MATERIAL"  => "RM",

        "SEMI FINISHED" => "SF",

        "FINISH STEEL"  => "FL,FF",

        "FERRO ALLOY"   => "FA",

        "LOGISTICS"     => "L"

    ];

    private $category_abbreviations = [
        "CL"    =>  "COAL",
        "FA"    =>  "FERRO ALLOY",
        "FF"    =>  "FINISH FLAT",
        "FL"    =>  "FINISH LONG",
        "FS"    =>  "FERROUS SCRAP",
        "FS2"   =>  "FINISH STEEL",
        "IN"    =>  "INGOT",
        "IO"    =>  "IRON ORE",
        "L"     =>  "LOGISTICS",
        "RM"    =>  "RAW MATERIAL",
        "SB"    =>  "SHIP BREAKING",
        "SF"    =>  "SEMI FINISH"
    ];



    private $categories = null;
    private $newCategories = null;



    public function __construct()
    {

        $this->categories = array(

            [

                "name"=> array_search( 'RM' ,$this->category_corelation),

                "DOM" => [

                    "IRON ORE" => [

                        'ODISHA', 'CHATTISGARH'

                    ],

                    "SCRAP" => [

                        'SHIP BREAKING', 'HMS'

                    ]

                ] ,

                "E_I" => [

                    "COAL" => [

                        'COKING', 'NON-COKING'

                    ],

                ]

            ],

            [

                "name"=>array_search( 'SF' ,$this->category_corelation),

                "DOM" => [

                    "PIG IRON" => [

                        'FOUNDRY GRADE', 'STEEL GRADE'

                    ]

                ],

                "E_I" => [



                ]

            ],

            [

                "name"=>array_search( 'FL,FF' ,$this->category_corelation),

                "DOM" => [

                    "TMT" => [

                        'PRIMARY', 'SECONDARY'

                    ],

                    "STRUCTURE" => [

                        'ANGLE', 'DURAGAPUR', 'GHAZIABAD','HYDERABAD','MANDI GOVINDGARH' ,'MUMBAI','RAIPUR'

                    ]

                ],

                "E_I" => [



                ]

            ] ,

            [

                "name" => array_search("FA" , $this->category_corelation) ,

                "DOM" => [



                ],

                "E_I" => [



                ]

            ],

            [

                "name" => array_search( 'L' ,$this->category_corelation),

                "DOM" => [

                ],

                "E_I" => [

                    "LOGISTICS" => [

                        'IRON ORE','COAL'

                    ]

                ]

            ]

        );

    }

    public function getNewCategories()
    {

        $categories = array();
        $tempCategories = array();

        /* $sql = "SELECT `category`, `item`, `trade_type`, GROUP_CONCAT(`tabs`) as tabs FROM `tbl_prices_index_master` WHERE `tabs` <> '' AND `page` = 'mobileapp' GROUP BY `category`, `item`, `trade_type`";
        $sql .= " ORDER BY";
        $sql .= " `category`, `item` ASC, `trade_type` ASC"; */
		$sql = "SELECT distinct `category`, `item`, `trade_type`, GROUP_CONCAT(`tabs`) as tabs, CAST(group_concat(distinct view_all_spinner_ordering ) AS UNSIGNED) as view_all_spinner_ordering FROM `tbl_prices_index_master` WHERE `tabs` <> '' AND `page` = 'mobileapp' group by `category`, `item`, `trade_type` DESC  ";
        $sql .= "having  view_all_spinner_ordering <> 0 ORDER BY";
        $sql .= " view_all_spinner_ordering ";

        $results = DB::select($sql);
        if($results) {
            foreach($results as $row) {
                $category = $row['category'];
                $trade_type = $row['trade_type'];
				$row['item'] = str_replace("_", " ", $row['item']);
 				if( $row['item'] == 'HRC' || $row['item'] == 'CRC' || $row['item'] == 'GP' || $row['item'] == 'TMT' )
					$item = $row['item'];
				else if( $row['item'] == 'HR PLATE'  )
					$item = "HR Plate";
				else
					$item = ucwords(strtolower($row['item']));
               $tabs = $row['tabs'];

                if(!isset($tempCategories[$category])) {
                    $tempCategories[$category] = array();
                    $tempCategories[$category]['name'] = '';
                    $tempCategories[$category]['sub_cat'] = array();
                    $tempCategories[$category]['E_I'] = array();
                }

                $tempCategories[$category]['name'] = isset($this->category_abbreviations[$category]) ? $this->category_abbreviations[$category] : $category;
				$tempCategories[$category]['name'] = ucwords(strtolower($tempCategories[$category]['name']));

                if(!isset($tempCategories[$category]['sub_cat'][$item])) {
                    $tempCategories[$category]['sub_cat'][$item] = array();
                }


                $tabs = $row['tabs'];
                if(strlen(preg_replace('/\s+/', '', $tabs)) > 0) {
                    $is_numeric = is_numeric(preg_replace('/[^a-zA-Z0-9\']/', '', $tabs));
                    
                    if(!$is_numeric) {
                        $tabs = explode(",", trim($tabs));
                        $tabs = array_unique($tabs);
                        if(strtoupper($item) == 'LOGISTICS') {
                            rsort($tabs);
                        } else {
                            sort($tabs);
                        }
                    }

                    $tempCategories[$category]['sub_cat'][$item][$trade_type]['tabs'] = $tabs;
                }

            }
        }

        foreach($tempCategories as $tempCategory) {
            $categories[] = $tempCategory;
        }

        $this->newCategories = $categories;

        return $this->newCategories;

    }



    public function getfilters()

    {

        $filters["category"]= $this->categories;


		$common = new Common();
		$filters["regions"] = $common->getRegions();


        $filters["category_listing"]= $this->getNewCategories();
			
        return new JsonResponse( array("status#"=>"1", "data#"=> $filters ) ) ;

    }
	
	public function getRegionsFilters()
    {

		$common = new Common();
		$filters["regions"] = $common->getRegions();	
			
        return new JsonResponse( array("status#"=>"1", "data#"=> $filters ) ) ;

    }



    private function prepare_tradetype()

    {

        $trade_type = array();

        foreach($this->categories  as $category)
        {

            foreach( $category['DOM'] as $key=>$val)
            {

                foreach($val as $v)

                    $trade_type[$v] = 'DOM';

            }

            foreach( $category['E_I'] as $key=>$val)
            {

                foreach($val as $v)

                    $trade_type[$v] = 'E_I';

            }

        }



        return $trade_type ;

    }



    public function getallprice(Request $request)

    {

        include($_ENV['COMMON_ROOT_PATH'].'/mapp.php') ;



        $user_id = '' ;

        $category='' ;

        $tab='' ;

        $item='';

        $trade_type='';
        $sterm='';

       if($request->has('token') || $request->has('memid')
             ) {
			
			if($request->has('memid')){
				$memid = $request->input('memid');
				$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
			}else{

				$token = $request->input('token');

				$auth = new authentication();

				$user_id = $auth->authToken($token);
			}
			
			if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
            //if (!$user_id)

                //abort(403, 'Unauthorized action. Token access denied');
			$category='' ;
        }



        if($request->has('category'))

        {

            $category= $request->input('category') ;

            foreach($this->category_corelation as $key=>$value )

            {

                if ( strcasecmp ($category , $key )== 0)

                    $category = $value ;

            }

        }



        if($request->has('tab'))

        {

            $tab= $request->input('tab') ;

            $trade_type = $this->prepare_tradetype()[$tab] ;



        }



        if($request->has('item'))

            $item= $request->input('item') ;



        if($request->has('trade_type'))

            $trade_type= $request->input('trade_type') ;

		$portfolio='';
		if($request->has('portfolio')){
            $common = new Common();
			$portfolio = $common->getUserPortfolio($user_id, 'prices'); 
			if(empty($portfolio)){
				$portfolio['f']=array(0);
			}
			
		}
          // $rs = getAppListing($user_id , $category , $tab ,$item , $trade_type ) ;
		if($request->has('sterm')){
            $sterm= $request->input('sterm') ;
            $sterm= htmlspecialchars($sterm, ENT_QUOTES); ;
		}
		
        $rs = getAppListing($user_id , $category , $tab ,$item , $trade_type, $portfolio, '', $sterm ) ;

//if($user_id==56350)return new JsonResponse( array("status#"=> $user_id, "data#"=> $user_id, "data#"=> $rs)) ;

//        $us = new \App\Http\Controllers\Auth\User($memid) ;

//        $us->getUserServices() ;

//    $temArr = getUserServices($memid);

//        $userService = $us->session['W']['userService'];
		
		//return $rs;
		
        $res = array() ;

        foreach( $rs as $r)

        {

            $temp['id'] = $r['row_id'] ;

            $temp['sub_id'] = $r['relation_id'] ;

            if($request->has('category'))

                $temp['category'] = $request->input('category') ;

            if($request->has('tab'))

                $temp['tab'] = $request->input('tab') ;
			
		//	if( $temp['category'] != "L" )
				$temp['sub_category'] = ucwords(strtolower(str_replace("_", " ",  $r['item']))) ; //1
			/* else
				$temp['sub_category'] = $r['tabs']; */
			
			$temp['tabs'] = $r['tabs'] ;

            $temp['price'] = trim( html_entity_decode( preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '',  $r['f_price']) , ENT_HTML5  ) , " \t\n\r\0\x0B")  ; //3


//            var_dump(strpos($temp['price'] , 'login') ) ;

//            var_dump(strpos($temp['price'] , '$') == false);

            //if( (strpos($temp['price'] , '$') === false) && (strpos($temp['price'] , 'login') === false) && (strpos($temp['price'] , 'upgrade') === false) )
			
            if((strpos(strtolower($temp['price']) , 'login') === false) && (strpos(strtolower($temp['price']) , 'upgrade') === false) )
			{
				if( $r['f_price_column'] == 'f') {
	                $temp['price'] = "₹".$temp['price'] ;
				} else {
					// $temp['price'] = $temp['price'] ;
					// nothing to do
				}
			} 
			elseif((strpos(strtolower($temp['price']) , 'login') === true)) {
				$temp['price'] = 'Login ';
			}
			elseif((strpos(strtolower($temp['price']) , 'upgrade') === true)) {
				$temp['price'] = 'Upgrade ';
			}
			
            

            $temp['change'] = trim( html_entity_decode( preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '', $r['change']) , ENT_HTML5  ) , " \t\n\r\0\x0B")  ; //6

            
            // Handled text login / upgrade case
            
            if(strtolower($temp['price']) == strtolower("Login")) {
                $temp['price'] = 'Login ';
            }
            
            if(strtolower($temp['change']) == strtolower("login")) {
                $temp['change'] = '  ';
            }
            
            if(strtolower($temp['price']) == strtolower("upgrade")) {
                $temp['price'] = 'Upgrade';
            }
            
            if(strtolower($temp['change']) == strtolower("upgrade")) {
                $temp['change'] = ' ';
            }
            
            $temp['size'] = $r['second_col'][0] ;

            $temp['Grade'] = $r['second_col'][1] ; // second element size decrease

            $temp['delivery'] = $r['first_col'] ;

            $temp['top_flag'] = 'india';

            $temp['graph_id'] = $r['relation_id'] ;



            $temp['country'] = $r['flag'] ;
            $temp['flag_code'] = $r['flag_code'] ;
            $temp['trade_type'] = $r['trade_type'] ;



//            if ($trade_type == 'E_I')

            if ($r['f_price_column'] == 'cnf' || $r['f_price_column'] == 'fob' )

                $temp['top_flag'] = 'global' ;

            else

                $temp['top_flag'] = $r['flag'] ;



            $temp['date'] = $r['as_on_date'] ; //7
            $temp['portfolio'] = $r['portfolio'] ; //7

            if(strcasecmp( $temp['category'] , 'LOGISTICS') == 0 )
            {
/*                 $temp['country'] = explode(',', $r['flag']);
                $temp['s_country'] = $temp['country'][1] ;
                $temp['country'] = $temp['country'][0] ; */
				$temp['country'] = $r['flag'] ;
            }

//            if($r['assesment'] == 'Y')

//                $temp['date'] = date( 'M Y' , strtotime($temp['date'])) ;

//            elseif ($r['assesment'] == 'W')

//                $temp['date'] = date( 'd Mon' , strtotime($temp['date'])) ;



//            $temp['country'] = "India";

//            $temp['date']  = date( "Y-m-d" , strtotime("-1 Week")) ;



            $temp['f_price_column'] = $r['f_price_column'];

            $temp['assesment'] = $r['assesment'] ;

            $temp['details'] = $r['details'] ;
            $temp['details2'] = $r['details2'] ;

            $temp['graph_view'] = $r['graph_view'] ;

			$temp['sticky_header_value'] = $temp['sub_category'];
			if( "Coal" == $temp['sub_category']){
				if(strpos($temp['size'], 'GAR') !== false || strpos($temp['size'], 'NAR') !== false || strpos($temp['size'], 'Pet coke') !== false)
					$temp['sticky_header_value'] = "Non Coking Coal";
				else
					$temp['sticky_header_value'] = "Coking Coal";
			}	
			if( "Scrap" == $temp['sub_category']){
				if(strpos($temp['size'], 'General Cargo') !== false || strpos($temp['size'], 'Tanker') !== false || strpos($temp['size'], 'SHIP BREAKING') !== false)
					$temp['sticky_header_value'] = "Ship Breaking Scrap";
				else
					$temp['sticky_header_value'] = "Melting Scrap";
			}
			if( "L" == $temp['category']){
				$ex = explode(",", $temp['country']);
				$temp['sticky_header_value'] = $ex[0];
			}

            $res[] = $temp ;
        }
		
		
		if($category == 'L'){
			/* usort($res, function($a, $b) {
				return $a['sub_category'] - $b['sub_category'];
			}); */
			usort($res, function($a, $b) {
				if($a['sub_category']==$b['sub_category']) return 0;
				return $a['sub_category'] < $b['sub_category']?1:-1;
			});
		}

        return new JsonResponse( array("status#"=>"1", "data#"=> $res)) ;



    }



    public function getPriceById(Request $request, $id )

    {

        include($_ENV['COMMON_ROOT_PATH'].'/mapp.php') ;



        $user_id = '' ;

        $relation_id = $id ;

        $price_type_prefix = 'f';

        $assesment = 'W';



        if ($request->has('token')) {

            $token = $request->input('token');

            $auth = new authentication();

            $user_id = $auth->authToken($token);

            if (!$user_id)

                abort(403, 'Unauthorized action. Token access denied');

        }



        if ($request->has('f_price_column') )

            $price_type_prefix = $request->input('f_price_column') ;



        if( $request->has('assesment') )

            $assesment = $request->input('assesment') ;

        //echo "<br>Uid:".$user_id;
        //echo "<br>token:".$token;
        $_rs_array = getGraphDataForId($user_id , $relation_id , $price_type_prefix , $assesment);



        return new JsonResponse(array(

            "status#" => "1" ,

            "data#" => $_rs_array

        )) ;



    }
	
	public function getPriceByPriceId(Request $request, $id )

    {

        include($_ENV['COMMON_ROOT_PATH'].'/mapp.php') ;
        $user_id = '' ;

        $relation_id = $id ;


        if ($request->has('token')) {

            $token = $request->input('token');

            $auth = new authentication();

            $user_id = $auth->authToken($token);

           /*  if (!$user_id)

                abort(403, 'Unauthorized action. Token access denied'); */
				if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;

        }


		$rs = getAppListing($user_id , $category='' , $tab='' ,$item='' , $trade_type='', $portfolio='', $row_id=$relation_id ) ;

		$res = array() ;

        foreach( $rs as $r)

        {

            $temp['id'] = $r['row_id'] ;

            $temp['sub_id'] = $r['relation_id'] ;

            if($request->has('category'))

                $temp['category'] = $request->input('category') ;

            if($request->has('tab'))

                $temp['tab'] = $request->input('tab') ;

			$temp['sub_category'] = ucwords(strtolower(str_replace("_", " ",  $r['item']))) ; //1

            $temp['tabs'] = $r['tabs'] ;

            $temp['price'] = trim( html_entity_decode( preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '',  $r['f_price']) , ENT_HTML5  ) , " \t\n\r\0\x0B")  ; //3


//            var_dump(strpos($temp['price'] , 'login') ) ;

//            var_dump(strpos($temp['price'] , '$') == false);

            //if( (strpos($temp['price'] , '$') === false) && (strpos($temp['price'] , 'login') === false) && (strpos($temp['price'] , 'upgrade') === false) )
			
            if((strpos(strtolower($temp['price']) , 'login') === false) && (strpos(strtolower($temp['price']) , 'upgrade') === false) )
			{
				if( $r['f_price_column'] == 'f') {
	                $temp['price'] = "₹".$temp['price'] ;
				} else {
					// $temp['price'] = $temp['price'] ;
					// nothing to do
				}
			} 
			elseif((strpos(strtolower($temp['price']) , 'login') === true)) {
				$temp['price'] = 'Login ';
			}
			elseif((strpos(strtolower($temp['price']) , 'upgrade') === true)) {
				$temp['price'] = 'Upgrade ';
			}
			
            

            $temp['change'] = trim( html_entity_decode( preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '', $r['change']) , ENT_HTML5  ) , " \t\n\r\0\x0B")  ; //6

            
            // Handled text login / upgrade case
            
            if(strtolower($temp['price']) == strtolower("Login")) {
                $temp['price'] = 'Login ';
            }
            
            if(strtolower($temp['change']) == strtolower("login")) {
                $temp['change'] = '  ';
            }
            
            if(strtolower($temp['price']) == strtolower("upgrade")) {
                $temp['price'] = 'Upgrade';
            }
            
            if(strtolower($temp['change']) == strtolower("upgrade")) {
                $temp['change'] = ' ';
            }
            
            $temp['size'] = $r['second_col'][0] ;

            $temp['Grade'] = $r['second_col'][1] ; // second element size decrease

            $temp['delivery'] = $r['first_col'] ;

            $temp['top_flag'] = 'india';

            $temp['graph_id'] = $r['relation_id'] ;



            $temp['country'] = $r['flag'] ;
            $temp['flag_code'] = $r['flag_code'] ;
            $temp['trade_type'] = $r['trade_type'] ;



//            if ($trade_type == 'E_I')

            if ($r['f_price_column'] == 'cnf' || $r['f_price_column'] == 'fob' )

                $temp['top_flag'] = 'global' ;

            else

                $temp['top_flag'] = $r['flag'] ;



            $temp['date'] = $r['as_on_date'] ; //7

            if(strcasecmp( $temp['category'] , 'LOGISTICS') == 0 )

            {

                $temp['country'] = explode(',', $r['flag']);

                $temp['s_country'] = $temp['country'][1] ;

                $temp['country'] = $temp['country'][0] ;

            }

//            if($r['assesment'] == 'Y')

//                $temp['date'] = date( 'M Y' , strtotime($temp['date'])) ;

//            elseif ($r['assesment'] == 'W')

//                $temp['date'] = date( 'd Mon' , strtotime($temp['date'])) ;



//            $temp['country'] = "India";

//            $temp['date']  = date( "Y-m-d" , strtotime("-1 Week")) ;



            $temp['f_price_column'] = $r['f_price_column'];

            $temp['assesment'] = $r['assesment'] ;

            $temp['details'] = $r['details'] ;
            $temp['details2'] = $r['details2'] ;

            $temp['graph_view'] = $r['graph_view'] ;



            $res[] = $temp ;



        }

        return new JsonResponse( array("status#"=>"1", "data#"=> $res)) ;


    }

}
