<?php
namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\authentication;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Action\Common;

class CurrencyController extends Controller

{
    private $countries = [];
    private $debug = false;

    public $appType = 'SM';
    public function __construct(Request $request)
    {
        if ($request->has('debug') && $request->input('debug') == true)
        {
            $this->debug = true;
        }
        if ($request->has('appType') && $request->input('appType') == true)
        {
            $this->appType = $request->input('appType');
        }
        elseif ($request->has('filters'))
        {
            $filter = $request->input('filters');
            if (!empty($filter['app_type']))
            {
                $this->appType = 'CM';
            }
        }
        else if ($request->has('app_type') && $request->input('app_type') == true)
        {
            $this->appType = $request->input('app_type');
        }
    }

    public function getList(Request $request)
    {
		$data=[];
        $resourceType = "app";
        
		$source = "home";
		if ($request->has('source'))
			$source = strtolower($request->input('source'));
		
        $result = array();
        if ($request->has('resourceType')) 
			$resourceType = strtolower($request->input('resourceType'));

        $currency = '';$whereCond='';
        if ($request->has('currencyName'))
        {
            $currency = $request->input('currencyName');
        }

        $offset = 0;
        $pageValue = 1;
		/* $limit = 11;
		if($source!='home') */
			$limit=25;

        $pageValue=1;
				
		if ($request->has('pageValue') && $request->input('pageValue')!='')
			$pageValue = $request->input('pageValue');	
		$offset = ($pageValue-1)* $limit;		
		
        $user_id = 0;
        if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '')
        {
            //$uemail = $request->input('email');//oldPassword
            $token = $request->input('accessToken');
            //$user = new User();
            $auth = new authentication();
            $user_id = $auth->authToken($token,$this->appType);
            if (!$user_id) return new JsonResponse(array(
                "status" => array(
                    "code" => 2100,
                    "message" => "Unauthorized action."
                )
            ));
        }
        elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '')
        {

            $memid = $request->input('memid');
            $auth = new authentication();
            $user_id = $auth->authUserId($memid); //for web user
            if (!$user_id) return new JsonResponse(array(
                "status" => array(
                    "code" => 2100,
                    "message" => "Unauthorized action."
                )
            ));
        }

        $accessType = 'pre'; //for visitor///
        if ($user_id)
        {
            $user = new User($user_id, $this->appType);
            ///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
            $isAccessible = $user->isAccessible($resourceType, $section = 'Prices');
            //added code to handle the access related things (market independent)
            //if($request->input('debug')=="1")
            {
                $all_session = session()->all();
                $accessible_mkt = array_filter(explode(",",$all_session['marketsIncludes']));
                foreach($accessible_mkt as $key_mkt){
                    $mergedArray = array_unique(explode(',', strtolower($all_session[$key_mkt]['sectionsIncludes'])));                   
                    if(in_array('prices',$mergedArray)){
                        $isAccessible=-1;                       
                        break;
                    }
                }               
            }
            if ($isAccessible == -1)
            {
                $accessType = 'post';
            }
            else
            {
                $accessType = 'pre';
            }
			
			if($source=='portfolio'){
				$temp = DB::table('tbl_user_portfolio')
			   // ->select('type','category', 'country', 'lead_type','row_id','prices_col')
				->select('prices_col')
				->where('user_id', '=' , $user_id)
				->where('type', '=' , 'forex')
				->where('appType', '=' , $this->appType)
				->get();
				$from_currency_code = [];
				$to_currency = [];
				foreach( $temp as $tm)
				{
					$prices_col = explode('-',$tm['prices_col']);
					$from_currency_code[] = $prices_col[0];
					$to_currency_code[] = $prices_col[1];
					/*$from_currency.="'".$prices_col[0]."'";
					$to_currency.="'".$prices_col[1]."'";*/
				}
				if(!empty($from_currency_code)){
					$whereCond = " WHERE from_currency_code IN ('". implode("','", array_unique($from_currency_code))."')";
					$whereCond .= " AND to_currency_code IN ('". implode("','", array_unique($to_currency_code))."')";
				}else{
					$whereCond = " WHERE from_currency_code='' AND to_currency_code='' ";
				}
			}
        }
		
		
		if(strtolower($source)=='recentview'){
			if($request->has('itemIdForexType') && !empty($request->input('itemIdForexType'))){
				$itemIdForexType = $request->input('itemIdForexType');
				foreach($itemIdForexType as $iID):
					$prices_col = explode('-',$iID);
					$from_currency_code[] = $prices_col[0];
					$to_currency_code[] = $prices_col[1];
				endforeach;
				if(!empty($from_currency_code)){
					$whereCond = " WHERE from_currency_code IN ('". implode("','", array_unique($from_currency_code))."')";
					$whereCond .= " AND to_currency_code IN ('". implode("','", array_unique($to_currency_code))."')";
				}else{
					$whereCond = " WHERE from_currency_code='' AND to_currency_code='' ";
				}
			}				
		}
		
		if($whereCond==''){
			$whereCond = " WHERE `from_currency_code` = 'USD' 
			and 	`to_currency_code` in ('BRL','AUD','ZAR','AED','IDR','EUR','RUB','GBP','PKR','JPY','TWD','CNY','INR')";
		}
		
        $sql = "
            SELECT t1.f_datetime as datePublished, t1.from_currency_code as fromCurrency, t1.to_currency_code as toCurrency, currency_name as currencyName, conversion_rate as value, (SELECT t2.`conversion_rate` FROM `tbl_currency_convertor` t2 WHERE t2.`to_currency_code` = t1.`to_currency_code` AND `from_currency_code` = 'USD' AND t2.`f_datetime` < t1.`f_datetime` ORDER BY t2.`f_datetime` DESC LIMIT 0, 1) as value2
			,(SELECT COUNT(up.`id`) FROM `tbl_user_portfolio` up WHERE up.`user_id` = '" . $user_id . "' AND up.`type` = 'forex' and prices_col=concat(t1.from_currency_code, '-', t1.to_currency_code)) as portfolio
			,lower(c.country_code) as fromCurrencyCode
			,lower(c1.country_code) as toCurrencyCode
            FROM 	`tbl_currency_convertor` t1
			LEFT JOIN tbl_country c ON t1.from_currency_code=c.currency_code
			LEFT JOIN tbl_country c1 ON t1.to_currency_code=c1.currency_code
            $whereCond
            and 	`f_datetime` = (SELECT st.`f_datetime` FROM `tbl_currency_convertor` st ORDER BY st.`f_datetime` DESC LIMIT 0, 1) 
			GROUP BY t1.from_currency_code, t1.to_currency_code 
        ";
		
		if($limit){
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}
		
		if($this->debug) {
			echo "<pre>", print_r($sql),print_r($all_session); "</pre>";
		}

		$results = DB::select($sql);

		if($results) {
			foreach($results as $result) {
				$display_text = strtoupper($result['fromCurrency']).' - '.strtoupper($result['toCurrency']);
				
				if($accessType == 'post') {
					$value = preg_replace('/[^\d.]/', '', $result['value']);
					$value2 = preg_replace('/[^\d.]/', '', $result['value2']);
					$change = (string) round(($value - $value2), 2);
					$percentage = (string) round((($change / $value) * 100), 2);
					$value = (string)round($value, 2);
					$_changeValue = $change;
				}else {
					$value = 'hidden';
					$change = 'hidden';
					$percentage = 'hidden';
					
					$_changeValue = round(($result['value'] - $result['value2']), 2);
					
				}
					if('EUR'==$result['toCurrency'])
						$result['toCurrencyCode']='eu';
					if('JPY'==$result['toCurrency'])
						$result['toCurrencyCode']='jp';
					if('CNY'==$result['toCurrency'])
						$result['toCurrencyCode']='cn';
					if('BRL'==$result['toCurrency'])
						$result['toCurrencyCode']='br';
					if('AUD'==$result['toCurrency'])
						$result['toCurrencyCode']='au';	
						
						
	        		$data[] = array(
	        			'itemID'	=>	str_replace(" ", "", $display_text), 
	        			'display_text'	=>	$display_text,
	        			'fromFlag'	=>	"https://www.steelmint.com/steeladmin/flags/".strtolower($result['fromCurrencyCode']).".png",
	        			'toFlag'	=>	"https://www.steelmint.com/steeladmin/flags/".strtolower($result['toCurrencyCode']).".png",
	        			'value'			=>	$value,
	        			'change'		=>	$change,
	        			'isChangePositive'		=>	($_changeValue==0|| $_changeValue=='NA')? '': ($_changeValue>0?"y":"n"),
	        			'percentage'	=>	$percentage,
	        			///'country'		=>	$country,
	        			///'country_code'	=>	isset($this->countries[$country]) ? $this->countries[$country] : '',
	        			'date_time'		=>	date("d M Y H:i", strtotime($result['datePublished'])). " IST",
	        			///"isAddedToPortfolio" =>($accessType=='post' ? ($result['portfolio']>0? 'y': 'n') : "n")
	        			"isAddedToPortfolio" =>($result['portfolio']>0? 'y': 'n')
	        		);

	        	
			}
		}
		
        $code = 1001;
        $message = "Success";
        return new JsonResponse(array(
            "status" => array(
                "code" => $code,
                "message" => $message
            ) ,
            "data" => $data
        ));

    }

    public function getDetail(Request $request, $id = '')
    {
		$resourceType = "web";
        
        $result = array();
        if ($request->has('resourceType')) 
			$resourceType = strtolower($request->input('resourceType'));

        $from = '';$to = '';
        if ($id)
        {
            ///$id = $request->input('id');
			$idArr = explode('-',$id);
			$from=$idArr[0];
			$to=$idArr[1];
        }
		
		if($from=='' || $to==''){
			return new JsonResponse(array(
                "status" => array(
                    "code" => 2100,
                    "message" => "Invalid itemID."
                )
            ));
		}

        $user_id = 0;
        if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '')
        {
            //$uemail = $request->input('email');//oldPassword
            $token = $request->input('accessToken');
            //$user = new User();
            $auth = new authentication();
            $user_id = $auth->authToken($token,$this->appType);
            if (!$user_id) return new JsonResponse(array(
                "status" => array(
                    "code" => 2100,
                    "message" => "Unauthorized action."
                )
            ));
        }
        elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '')
        {

            $memid = $request->input('memid');
            $auth = new authentication();
            $user_id = $auth->authUserId($memid); //for web user
            if (!$user_id) return new JsonResponse(array(
                "status" => array(
                    "code" => 2100,
                    "message" => "Unauthorized action."
                )
            ));
        }

        $accessType = 'pre'; //for visitor///
        if ($user_id)
        {
            $user = new User($user_id, $this->appType);
            ///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
            $isAccessible = $user->isAccessible($resourceType, $section = 'Prices');
            //added code to handle the access related things (market independent)
            {
                $all_session = session()->all();
                $accessible_mkt = array_filter(explode(",",$all_session['marketsIncludes']));
                foreach($accessible_mkt as $key_mkt){
                    $mergedArray = array_unique(explode(',', strtolower($all_session[$key_mkt]['sectionsIncludes'])));                   
                    if(in_array('prices',$mergedArray)){
                        $isAccessible=-1;                       
                        break;
                    }
                }               
            }
            if ($isAccessible == -1)
            {
                $accessType = 'post';
            }
            else
            {
                $accessType = 'pre';
            }
        }
		
		$FromDt = date('Y-m-d', strtotime('-2 years'));
        $sql = "
            SELECT t1.f_datetime as datePublished, conversion_rate as value
            FROM 	`tbl_currency_convertor` t1

            WHERE 	`from_currency_code` = '$from'

            and 	`to_currency_code` = '$to'
			and f_datetime >='$FromDt'
            ORDER BY t1.`f_datetime`       
        ";
		/* 
		if($limit){
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		} */
		
		if($this->debug) {
			echo "<pre>", print_r($sql), "</pre>";
			echo "==>".$isAccessible;
		}

		$results = DB::select($sql);


        $graphData = [];

        
        $rows = DB::select($sql);

        if ($results)
        {
            foreach ($results as $row)
            {
                $value = preg_replace("/[^0-9.]/", "", $row['value']);
                if (!$value)
                {
                    $value = "0";
                }

                $graphData[] = [
					"x"=>strtotime($row['datePublished']) ,
					"y"=>round(floor($value * 100) / 100,2)
				];
            }

        }		
				
        $code = 1001;
        $message = "Success";
        $isGraphAccessible = "n";         
        if($accessType=='post' || $resourceType=='web'){
            $isGraphAccessible = "y";
		}

        return new JsonResponse(array(
            "status" => array(
                "code" => $code,
                "message" => $message
            ) ,
            "data" => $graphData,
           "isGraphAccessible"=>$isGraphAccessible
        ));

    }

    protected function countriesList()

    {

        $results = DB::table('tbl_country')->get();

        if ($results)
        {

            foreach ($results as $result)
            {

                $this->countries[strtolower(trim($result['country'])) ] = $result['country_code'];

            }

            $this->countries[strtolower(trim('United Arab Emirates')) ] = 'AE';

        }

    }

}

