<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;

use App\Http\Controllers\Auth\authentication;

use App\Http\Controllers\Auth\User;

use DB;

class CurrencyController extends Controller
{

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

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

	public function getList(Request $request)
	{

		$user_id = 0;
		$maxCount = 1;

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

		$user = new User($user_id);
		$maxCount = $user->getTakenServicesByUser();

		$data = [];
		$excludeValues = [
			'SHANGHAI',
			'CME'
		];

		$this->countriesList();

		//$sql = "SELECT t1.*";
		//$sql .= ", (SELECT t2.`value` FROM `tbl_dollar_cme_shanghai_data` t2 WHERE t2.`type` = t1.`type` AND t2.`f_date_time` < t1.`f_date_time` ORDER BY t2.`f_date_time` DESC LIMIT 0, 1) as value2";
		//$sql .= " FROM `tbl_dollar_cme_shanghai_data` t1";
		//$sql .= " WHERE DATE(`f_date_time`) = (SELECT st.`f_date_time` FROM `tbl_dollar_cme_shanghai_data` st ORDER BY st.`f_date_time` DESC LIMIT 0, 1)";

        $sql = "
            SELECT * 
            FROM 	`tbl_currency_convertor` 
            WHERE 	`from_currency_code` = 'USD' 
            and 	`to_currency_code` in ('BRL','AUD','ZAR','AED','IDR','EUR','RUB','GBP','PKR','JPY','TWD','CNY') 
            and 	`f_datetime` = (SELECT st.`f_datetime` FROM `tbl_currency_convertor` st ORDER BY st.`f_datetime` DESC LIMIT 0, 1)         
        ";

		//if($request->has('id') && (int)$request->input('id') > 0) {
		//	$sql .= " AND t1.`id` = " . (int)$request->input('id');
		//}

		if($this->debug) {
			echo "<pre>", print_r($sql), "</pre>";
		}

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

		if($results) {
			foreach($results as $result) {
				$display_text = str_replace('_IN_', '/', strtoupper($result['type']));

				if(!in_array($display_text, $excludeValues)) {

					$countryParts = explode("(", $result['display_text']);
	    			$country = isset($countryParts[0]) ? strtolower(trim($countryParts[0])) : '';

	    			if($maxCount == -1) {
		    			$value = preg_replace('/[^\d.]/', '', $result['value']);
		    			$value2 = preg_replace('/[^\d.]/', '', $result['value2']);
		    			$change = round(($value - $value2), 2);
		    			$percentage = round((($change / $value) * 100), 2);
						$value = (string)round($value, 2);
		    		} else if($maxCount == 0) {
		    			$value = 'Upgrade';
		    			$change = 'Upgrade';
		    			$percentage = 'Upgrade';
		    		} else {
		    			$value = 'Login';
		    			$change = 'Login';
		    			$percentage = 'Login';
		    		}

	        		$data[] = array(
	        			'id'			=>	$result['id'],
	        			'display_text'	=>	$display_text,
	        			'value'			=>	$value,
	        			'change'		=>	$change,
	        			'percentage'	=>	$percentage,
	        			'country'		=>	$country,
	        			'country_code'	=>	isset($this->countries[$country]) ? $this->countries[$country] : '',
	        			'date_time'		=>	$result['f_date_time']
	        		);

	        	}
	        	
			}
		}

		require('/home/steelmin/public_html/inc/desconfig.php');

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

	public function getDetail(Request $request, $id = 0)
	{

		$user_id = 0;
		$maxCount = 1;

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

		$user = new User($user_id);
		$maxCount = $user->getTakenServicesByUser();

		$graphData = [];

		$sql = "SELECT `value`, `f_date_time` FROM `tbl_dollar_cme_shanghai_data` WHERE `type` = (SELECT st.`type` FROM `tbl_dollar_cme_shanghai_data` st WHERE st.`id` = " . (int)$id . ") ORDER BY `f_date_time` ASC";
		$rows = DB::select($sql);

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

				$graphData[] = [
					strtotime($row['f_date_time']),
					floor($value * 100) / 100
				];
			}
		}

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

	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';
		}
	}
}