<?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'].'/mappNew.php' ;



class PriceModuleController extends Controller

{

    /**

     * Get all filters for pricing module

     */

    private $debug = false;


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

    ];

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

    private $region_corelations = [
        "India"                         =>  "India",
        "China"                         =>  "China",
        "Japan, Korea"                  =>  "Japan, Korea, South Korea",
        "Pakistan, Bangladesh, Nepal"   =>  "Pakistan, Bangladesh, Nepal, Benapole Port, Bhutan",
        "Australia"                     =>  "Australia",
        "South East Asia"               =>  "South East Asia, Indonesia, Malaysia, Taiwan, Vietnam",
        "Middle East Africa"            =>  "Middle East Africa, South Africa, Ghana, Gabon, Dubai, Middle East, Oman, United Arab Emirates, Saudi Arabia, Iran",
        "CIS Nations"                   =>  "CIS Nations, CIS Country, Ukraine, Russia",
        "Europe"                        =>  "Europe, Albania, Italy, Turkey",
        "US/Canada"                     =>  "US/Canada, United States",
        "Brazil"                        =>  "Brazil,Colombia",
        "Global"                        =>  "Global"
    ];


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



    public function __construct(Request $request)
    {

        $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'

                    ]

                ]

            ]

        );

        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;
        }

    }

    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' and category <> 'SB' 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'  )
					$item = $row['item'];
				else if( $row['item'] == 'HR PLATE'  )
					$item = "HR Plate";
				else if( $row['item'] == 'TMT'  )
					$item = "Rebar";
				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(Request $request)
    {

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

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

        $filters["category_listing"]= $this->getNewCategories();
			
        return new JsonResponse( array("status#"=>"1", "data#"=> $filters ) ) ;*/
		if($request->has('appType') && (strtolower($request->input('appType'))=='coalmint' || strtoupper($request->input('appType'))=='CM'))
			$path = storage_path() . "/json/constants/v3_coalmint_price_category.json";
        else
			$path = storage_path() . "/json/constants/v3_test_price_category.json";
        $filter = json_decode(file_get_contents($path), true);

        return new JsonResponse($filter);

    }
	
	public function getRegionsFilters(Request $request)
    {

		/*$common = new Common();
		if ($request->has('filter_for') && strtolower($request->input('filter_for'))=='ios'){
			$filters = array($common->getRegions('tenders'));	
		}else{
			$filters["regions"] = $common->getRegions();	
		}
			
        return new JsonResponse( array("status#"=>"1", "data#"=> $filters ) ) ;*/

        $path = storage_path() . "/json/constants/v3_test_price_filters_regions.json";
        $filter = json_decode(file_get_contents($path), true);

        if($request->has('filter_for') && strtolower($request->input('filter_for'))=='ios') {
            $iosRegionFilter = array();
            $iosRegionFilter['filter'] = "regions";
            $iosRegionFilter['sub_filter'] = array();

            if(isset($filter['data#']['regions']) && !empty($filter['data#']['regions'])) {
                foreach($filter['data#']['regions'] as $regionKey => $region) {
                    if(is_array($region)) {
                        $countries = array();
                        if(!empty($region)) {
                            foreach($region as $country) {
                                $countries[] = array(
                                    'filter'    =>  $country
                                );
                            }
                        }

                        if($countries) {
                            $iosRegionFilter['sub_filter'][] = array(
                                'filter'        =>  $regionKey,
                                'sub_filter'    =>  $countries
                            );
                        } else {
                            $iosRegionFilter['sub_filter'][] = array(
                                'filter'    =>  $regionKey
                            );
                        }

                    } else {
                        $iosRegionFilter['sub_filter'][] = array(
                            'filter'    =>  $region
                        );
                    }
                }
            }

            $filter['data#'] = array(
                $iosRegionFilter
            );
        }

        return new JsonResponse($filter);

    }

    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 getPrices(Request $request)
    {
        include($_ENV['COMMON_ROOT_PATH'].'/mappNew.php');

        $filter = array();

        $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);

            } 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"
                )) ;
            }

            $category = '';
        }
		
		$appType='SM';
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){    
			$filter['appType'] = $request->input('appType');
			$appType = $request->input('appType');
		}elseif($request->has('category')) {
            $category= $request->input('category') ;

            $filter['category'] = (isset($this->category_corelation[strtoupper($category)]) ? $this->category_corelation[strtoupper($category)] : 'RM');

        }

        if($request->has('tab')) {
            $tab = $request->input('tab');
            $trade_type = $this->prepare_tradetype()[$tab];

            $filter['tabs'] = $tab;
        }

        if($request->has('sub_category')) {
            $sub_category = $request->input('sub_category');
            if(strtolower($sub_category)=='pet coke & anthracite') {
				$sub_category = 'Pet Coke';
			}
			$filter['sub_category'] = $sub_category;
        }
		
        if($request->has('relatedPrices')) {
            $relatedPrices = $request->input('relatedPrices');
            $filter['relatedPrices'] = $relatedPrices;
        }

        if($request->has('trade_type')) {
            $trade_type = $request->input('trade_type');
            $filter['trade_type'] = $trade_type;
        }

        $portfolio='';
        if($request->has('portfolio')) {
            $common = new Common();
            $portfolio = $common->getUserPortfolio($user_id, 'prices', $appType);

            if(empty($portfolio)){
                $portfolio['f'] = array(0);
            }
            $filter['portfolio'] = $portfolio;            
        }
         
        if($request->has('sterm')){
            $sterm = $request->input('sterm');
            $sterm = htmlspecialchars($sterm, ENT_QUOTES);
            $filter['sterm'] = $sterm;
        }

        if($request->has('region')){
            $regions = $request->input('region');
            $regions = explode(";", $regions);

            /************************************************************************
                Mapping of Regions has been removed on 17th Jan, 2018 at 10:37 am
            *************************************************************************/
            // foreach($regions as $key => $region) {
            //     $region = htmlspecialchars($region, ENT_QUOTES);

            //     foreach($this->region_corelations as $regionKey => $region_corelation) {
            //         if(strtolower($regionKey) == strtolower($region)) {
            //             $regions[$key] = $region_corelation;
            //             break;
            //         }
            //     }
            // }

            $filter['region'] = implode(",", $regions);
        }

        if($request->has('row_ids') && $request->has('trade_types')) {
            $row_ids = explode(",", $request->input('row_ids'));
            $trade_types = explode(",", $request->input('trade_types'));

            $filter['row_ids'] = array();

            foreach($row_ids as $key => $row_id) {
                $filter['row_ids'][] = array(
                    'id'            =>  $row_id,
                    'trade_type'    =>  isset($trade_types[$key]) ? $trade_types[$key] : ''
                );
            }
        }

        $filter['debug'] = $this->debug;

		$filter['src'] = "APP";

        $results = getPricesForApp($user_id, $filter);

        //return json_encode( array("status#"=>"1", "data#"=> $results)) ;
        return new JsonResponse( array("status#"=>"1", "data#"=> $results)) ;
    }

    public function getPriceById(Request $request, $id )
    {

        include($_ENV['COMMON_ROOT_PATH'].'/mappNew.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') ;
        }
		$appType='SM';
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){    
			$appType = $request->input('appType');
		}
        $_rs_array = getGraphDataForId($user_id , $relation_id , $price_type_prefix , $assesment, $appType);

        return new JsonResponse(array(

            "status#" => "1" ,
            "data#" => $_rs_array

        )) ;

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

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

        $relation_id = $id;

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

            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);

			if(!$user_id) {
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                ));
            }

        }

        $filter = array();
        $filter['src'] = "APP";
        $filter['row_id'] = $relation_id;
		$appType='SM';
		
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){    
			$filter['appType'] = $request->input('appType');
		}
		
        if($request->has('prices_col')) {
            $filter['price_type'] = strtolower($request->input('prices_col'));  
        }

		$results = getPricesForApp($user_id, $filter);

        return new JsonResponse( array("status#"=>"1", "data#"=> (isset($results[0]) ? $results[0] : array())));

    }

}
