<?php

namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Auth\authentication;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Action\Common;
//stepLogic
use App\Http\Controllers\Action\StplCommonController;
use InfographController;
use Validator;
use Session;

class AlphaController extends Controller
{

  public function statTablePlot(Request $request)
  {

    $result = \ApiQuery::statTablePlot($request->all());
    echo json_encode($result, true);
  }

  public function statTablePlot_CM(Request $request)
  {

    $result = \ApiQuery::statTablePlot($request->all());
    // return json_encode($result,true);

    return response()->json($result);
  }

  public function getStatisticsPortfolio(Request $request)
  {
    $result = array();
    //if called from new dashboard then send data for specific datatype
    //$renderForDataType contains datatype for whse data is required on frontend
    $renderForDataType = '';
    $isNewDashboardGraph = 'n';
    if ($request->has('memid') && !empty($request->input('memid'))) {
      //$memid = $request->input('memid');
      $memid = htmlentities($request->input('memid'), ENT_QUOTES);

      if (!is_numeric($memid)) {
        return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
      }

      $auth = new authentication();
      $memid = $auth->authUserId($memid); //for web user

      if ($memid) {
        if ($request->has('renderForDataType') && !empty($request->input('renderForDataType')))
          $renderForDataType = $request->input('renderForDataType');

        if ($request->has('isNewDashboardGraph') && !empty($request->input('isNewDashboardGraph')))
          $isNewDashboardGraph = $request->input('isNewDashboardGraph');


        $offset = 0;
        $pageValue = 1;

        if ($request->has('pageValue') && $request->input('pageValue') != '') {
          $pageValue = $request->input('pageValue');
          if ($renderForDataType != '') {
            $offset = ($pageValue - 1) * 10;
          } else {
            $offset = ($pageValue - 1) * 8;
          }
        }

        $common = new StplCommonController(); //$type='statistics',
        $result = $common->getUserStatsPortfolioV2019($memid,  $appType = 'SM', $renderForDataType, $offset, $isNewDashboardGraph);
        //include_once "/home/steelmin/public_html/api/storage/v2019/web/statistic_2ndlevel_post.php";

        $code = 1001;
        $message = "Success";
      } else {
        $code = 2013;
        $message = "User not found.";
      }
    } else {
      $code = 2013;
      $message = "User not found.";
    }
    if ($renderForDataType != '') {
      $ex = $result;
      $result = array();
      $result = $ex["dataValue"];
      $cntValue = $ex["cntValue"];
    } else {
      $cntValue = 0;
    }


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


  public function getStatistics(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:Web,web',
      'requireData' => 'required|in:datatype',
      'requiredFor' => 'required|in:statistics,price'
    ];
    $check = $this->checkInputisValid($rule, $request->all());
    if ($check) {
      return response()->json($check);
    } else {

      $isCM = '';
      if ($request->has('filters')) {
        $filter = $request->input('filters');
        if (!empty($filter['app_type'])) {
          $isCM = $filter['app_type'];
        }
      }

      $requiredFor = trim($request->requiredFor);
      $objCommon = new StplCommonController;
      $data = $objCommon->getDetaTypeName($requiredFor, $isCM, $request->selected_market);
      $datatypes = array();
      if ($data === null) {
        $datatypes = $data;
        $status = 10005;
        $message = "No record Found!";
      } else {
        $datatypes['datatype'] = $data;
        $status = 1001;
        $message = "success";
      }
      $getresponce = $this->innerResponceHander($datatypes, $status, $message);
      if ($request->debugMode == 'true') {
        $table = array('tbl_stats_datatype_header_list_bm');
        $requreParam = array(
          'resourceType' => 'required|string|web',
          'requireData' => 'required|string|datatype',
          'requiredFor' => 'required|string|statistics,price',
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function getFilterLeftMain(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:Web,web',
      'requireData' => 'required|in:regionCommodity',
      'requiredFor' => 'required|in:statistics,price',
      'source' => 'required|in:stats_graphs',
      'dataType' => 'required'
    ];
    $check = $this->checkInputisValid($rule, $request->all());
    if ($check) {
      return response()->json($check);
    } else {

      $memid = 0;
      //update memId if getting in POST request
      if ($request->memid) {
        $memid = trim($request->memid);
      }

      if ($memid <= 0) {
        $status = array(
          'status' => 2001,
          'message' => 'Unauthorized action'
        );
        return response()->json($status);
      }
      $isCM = 'SM';
      if ($request->has('filters')) {
        $filter = $request->input('filters');
        if (!empty($filter['app_type'])) {
          $isCM = $filter['app_type'];
        }
      }

      $user = new User($memid, $isCM);

      if ("public/statsJson.php" !=  $request->src) { //called from /bm/public/statsJson.php to generate public_html/bm/public/datatypes.json which is then used in bm/app/Http/Controllers/StatisticsController.php
        $isAccessible =  $user->isAccessible($resourceType = 'Web', $section = 'Statistics_Graph', '', '', '', $request['selected_market']);
        if ($isAccessible != -1) {
          $status = array(
            'status' => 2001,
            'message' => 'Not a valid user, no access'
          );
          return response()->json($status);
        }
      }
      $datatype = trim($request->dataType);

      //START: form key for redis using above parameters
      $redisKeyName = 'stats_graph';
      if ($datatype !== '') {
        if ($redisKeyName == '')
          $redisKeyName = $datatype;
        else
          $redisKeyName .= "_" . $datatype;
      }

      if ($isCM !== '') {
        if ($redisKeyName == '')
          $redisKeyName = $isCM;
        else
          $redisKeyName .= "_" . $isCM;
      }
      //END: form key for redis using above parameters       
      //check if the above key exists in redis DB
      //if yes, then return the same
      include_once "/home/steelmin/public_html/redisFn.php";
      /* if(isKeyExistsInRedis($redisKeyName)){
            $status = 1001;
            $message= "success";
            $data = json_decode(getKeyValueFromRedis($redisKeyName), true);
            $getresponce = $this->innerResponceHander($data,$status,$message);		 
            return response()->json($getresponce); 
		} */

      $objCommon = new StplCommonController;
      //echo $datatype . $memid;
      $checkRecordExist = $objCommon->checkDatatypeExist($datatype, $memid, $isCM);

      if ($checkRecordExist != 'true') {
        $status = array(
          'status' => 10004,
          'message' => 'dataType not Found!'
        );
        return response()->json($status);
      }

      $memid = 0;
      if ($request->memid) {
        $memid = trim($request->memid);
      }

      $data = $objCommon->getCommAndRegion($datatype, $memid, $isCM, $request['selected_market']);
      //set $redisKeyName in redis with $result for one day
      //after every 24 hours it will expire
      setInRedis($redisKeyName, json_encode($data), 86400);

      $status = 1001;
      $message = "success";
      $getresponce = $this->innerResponceHander($data, $status, $message);
      if ($request->debugMode == 'true') {
        $table = array('tbl_stats_datatype_header_list_bm', 'tbl_stats_left_toolbox_landing_bm');
        $requreParam = array(
          'resourceType' => 'required|string|web',
          'requireData' => 'required|string|regionCommodity',
          'requiredFor' => 'required|string|statistics,price',
          'source' => 'required|string|stats_graphs',
          'dataType' => 'required|string',
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }

      return response()->json($getresponce);
    }
  }

  public function getGraphs(Request $request)
  {
    //die('here');

    $rule = [
      'resourceType' => 'required|in:Web,web,app',
      'dataType' => 'required|string|max:20',
      //'commodity' => 'required|string|max:20',
      //'region' => 'required|string|max:20',
      //'fromDate' => 'required|string|max:20',
      // 'toDate' => 'required|string|max:20',
      //'periodFormat' => 'required|string|max:20',
      ///'memid' => 'required|string|max:20',
      //'columnNameOfRegion' => 'required|string|max:20',
      //'columnNameOfCommodity' => 'required|string|max:20',
    ];
    $check = $this->checkInputisValid($rule, $request->all());

    if ($check != '') {
      return response()->json($check);
    } else {
      //if($request->has('memid') && $request -> memid == 116707)
      {
        if ($request->has('resourceType') && $request->input('resourceType') == 'app' && !$request->has('fromDate') && !$request->has('periodFormat')) {
          include_once "/home/steelmin/public_html/redisFn.php";
          $region = $request->region;
          $commodity = $request->commodity;
          $columnNameOfCommodity = $request->columnNameOfCommodity;
          $columnNameOfRegion = $request->columnNameOfRegion;
          $dataType = $request->dataType;
          $unit = $request->unit;


          $redisKeyName = "app_graph_" . str_replace(" ", "", $region) . '_' . str_replace(" ", "", $commodity) . '_' . $columnNameOfCommodity . '_' . $columnNameOfRegion . '_' . $dataType . '_' . $unit;

          // if(isKeyExistsInRedis($redisKeyName)){
          // $status = 1001;
          // $message = 'success';
          // $data = json_decode(getKeyValueFromRedis($redisKeyName), true);
          // $getresponce = $this->innerResponceHanderApp($data,$status,$message);
          // return response()->json($getresponce);
          // }
        }
      }



      $mntArr = array();
      $objCommon = new StplCommonController;
      //$data['graphValues'] = $objCommon->getGraphData($request->all(), $unitTextToShow);
      $data['graphValues'] = $objCommon->getGraphData($request->all(), $unitTextToShow, $mntArr);

      if ($data['graphValues'] == 'Unauthorized') {
        return response()->json(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
      }

      $data['unitTextToShow'] = $unitTextToShow;
      if (! empty($mntArr)) {
        ksort($mntArr, SORT_NUMERIC);
      }

      $data['mntArr'] = $mntArr;

      //echo "outer" . $request->source . "//"; 
      //if($request->has('source') && $request->source!='tabular'){
      if ($request->source != 'tabular') {
        //	echo "inner"; 
        if ($request->has('mainCommodity'))
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->mainCommodity)) . ' | ' . trim(ucfirst($request->commodity)) . ' | ' . trim(ucfirst($request->region));
        else
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->commodity)) . ' | ' . trim(ucfirst($request->region));
        $data['title'] = $title;
        if ($request->input('resourceType') != 'app') {
          $data['nextChildren'] = $objCommon->getHeaderNameAndColumns($request->all());

          $check_portfolio = $objCommon->checkPortfolio($request->all(), "parent");

          //if($request->debugMode=='true')
          //echo "check_portfolio:"  . $check_portfolio;

          if ($check_portfolio == "false" || $check_portfolio == "") {
            $data['isAddedToPortfolio'] = "N";
          } else {
            $data['isAddedToPortfolio'] = 'Y';
            $data['addedPortfolioId'] = $check_portfolio;
          }
        }
        if ($data['graphValues'] == 'false' || $data['graphValues'] == null ||  $data['nextChildren'] == 'false') {
          if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
            $status = array(
              'code' => 10005,
              'message' => 'No record Found!'
            );
          } else {
            $status = array(
              'status' => 10005,
              'message' => 'No record Found!'
            );
          }
          return response()->json($status);
        }
      } else {

        if ($request->has('commodity')) {
          if ("Capacity" == $request->dataType) {
            if ($request->commodity == 'Non Coking Coal' || $request->commodity == 'Coking Coal')
              $request->commodity = 'Coal Washery -> ' . trim(ucfirst($request->commodity));
            else
              $request->commodity = 'Coal -> ' . trim(ucfirst($request->commodity));
          }
          if ($request->has('mainCommodity'))
            $title = trim(ucfirst($request->dataType)) . ' - ' . trim($request->mainCommodity) . ' | ' . trim(ucfirst($request->commodity));
          else
            $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->commodity));
          if ($request->has('region')) {
            $title = $title . ' | ' . $request->region;
          }
        } else {
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->region));
        }
        $data['title'] = $title;
      }
      $status = 1001;
      $message = 'success';

      if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
        //if($request->has('memid') && $request -> memid == 116707)
        {
          //no from and todate then  default value for case of resourceType is app
          if (!$request->has('fromDate') && !$request->has('periodFormat')) {
            setInRedis($redisKeyName, json_encode($data), 0);
          }
        }
        $getresponce = $this->innerResponceHanderApp($data, $status, $message);
      } else {
        $getresponce = $this->innerResponceHander($data, $status, $message);
      }

      if ($request->debugMode == 'true') {
        $table = array('dataType' => $request->dataType, 'tableUsedForHeader' => 'tbl_stats_datatype_header_list_bm');

        $requreParam = array(
          'resourceType' => 'required|string|web',
          'dataType' => 'required|string|max:20',
          'commodity' => 'required|string|max:20',
          'region' => 'required|string|max:20',
          'fromDate' => 'required|string|max:20',
          'toDate' => 'required|string|max:20',
          'periodFormat' => 'required|string|max:20',
          //'memid' => 'required|string|max:20',
          'columnNameOfRegion' => 'required|string|max:20',
          'columnNameOfCommodity' => 'required|string|max:20'
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function getGraphs_5_3_2022(Request $request)
  {
    //die('here');

    $rule = [
      'resourceType' => 'required|in:Web,web,app',
      'dataType' => 'required|string|max:20',
      //'commodity' => 'required|string|max:20',
      //'region' => 'required|string|max:20',
      //'fromDate' => 'required|string|max:20',
      // 'toDate' => 'required|string|max:20',
      //'periodFormat' => 'required|string|max:20',
      ///'memid' => 'required|string|max:20',
      //'columnNameOfRegion' => 'required|string|max:20',
      //'columnNameOfCommodity' => 'required|string|max:20',
    ];
    $check = $this->checkInputisValid($rule, $request->all());

    if ($check != '') {
      return response()->json($check);
    } else {
      $mntArr = array();
      $objCommon = new StplCommonController;
      //$data['graphValues'] = $objCommon->getGraphData($request->all(), $unitTextToShow);
      $data['graphValues'] = $objCommon->getGraphData($request->all(), $unitTextToShow, $mntArr);

      if ($data['graphValues'] == 'Unauthorized') {
        return response()->json(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
      }

      $data['unitTextToShow'] = $unitTextToShow;
      if (! empty($mntArr)) {
        ksort($mntArr, SORT_NUMERIC);
      }

      $data['mntArr'] = $mntArr;

      //echo "outer" . $request->source . "//"; 
      //if($request->has('source') && $request->source!='tabular'){
      if ($request->source != 'tabular') {
        //	echo "inner"; 
        if ($request->has('mainCommodity'))
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->mainCommodity)) . ' | ' . trim(ucfirst($request->commodity)) . ' | ' . trim(ucfirst($request->region));
        else
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->commodity)) . ' | ' . trim(ucfirst($request->region));
        $data['title'] = $title;
        if ($request->input('resourceType') != 'app') {
          $data['nextChildren'] = $objCommon->getHeaderNameAndColumns($request->all());

          $check_portfolio = $objCommon->checkPortfolio($request->all(), "parent");

          //if($request->debugMode=='true')
          //echo "check_portfolio:"  . $check_portfolio;

          if ($check_portfolio == "false" || $check_portfolio == "") {
            $data['isAddedToPortfolio'] = "N";
          } else {
            $data['isAddedToPortfolio'] = 'Y';
            $data['addedPortfolioId'] = $check_portfolio;
          }
        }
        if ($data['graphValues'] == 'false' || $data['graphValues'] == null ||  $data['nextChildren'] == 'false') {
          if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
            $status = array(
              'code' => 10005,
              'message' => 'No record Found!'
            );
          } else {
            $status = array(
              'status' => 10005,
              'message' => 'No record Found!'
            );
          }
          return response()->json($status);
        }
      } else {

        if ($request->has('commodity')) {
          if ("Capacity" == $request->dataType) {
            if ($request->commodity == 'Non Coking Coal' || $request->commodity == 'Coking Coal')
              $request->commodity = 'Coal Washery -> ' . trim(ucfirst($request->commodity));
            else
              $request->commodity = 'Coal -> ' . trim(ucfirst($request->commodity));
          }
          if ($request->has('mainCommodity'))
            $title = trim(ucfirst($request->dataType)) . ' - ' . trim($request->mainCommodity) . ' | ' . trim(ucfirst($request->commodity));
          else
            $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->commodity));
          if ($request->has('region')) {
            $title = $title . ' | ' . $request->region;
          }
        } else {
          $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->region));
        }
        $data['title'] = $title;
      }


      $status = 1001;
      $message = 'success';


      if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
        $getresponce = $this->innerResponceHanderApp($data, $status, $message);
      } else {
        $getresponce = $this->innerResponceHander($data, $status, $message);
      }
      /// $getresponce = $this->innerResponceHander($data,$status,$message);
      if ($request->debugMode == 'true') {
        $table = array('dataType' => $request->dataType, 'tableUsedForHeader' => 'tbl_stats_datatype_header_list_bm');

        $requreParam = array(
          'resourceType' => 'required|string|web',
          'dataType' => 'required|string|max:20',
          'commodity' => 'required|string|max:20',
          'region' => 'required|string|max:20',
          'fromDate' => 'required|string|max:20',
          'toDate' => 'required|string|max:20',
          'periodFormat' => 'required|string|max:20',
          //'memid' => 'required|string|max:20',
          'columnNameOfRegion' => 'required|string|max:20',
          'columnNameOfCommodity' => 'required|string|max:20'
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }
  public function getGraphs2ndLevel(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:Web,web,app',
      'dataType' => 'required|string|max:20',
      'commodity' => 'required|string|max:50',
      'region' => 'required|string|max:20',
      //'fromDate' => 'required|string|max:20',
      //'toDate' => 'required|string|max:20',
      //'periodFormat' => 'required|string|max:20',
      // 'memid' => 'required|string|max:20',
      'columnNameOfRegion' => 'required|string|max:20',
      'columnNameOfCommodity' => 'required|string|max:20',
      //'headerColumn' => 'required|string|max:20',
      'headerColumn' => 'required|string',
    ];

    $check = $this->checkInputisValid($rule, $request->all());
    if ($check) {
      return response()->json($check);
    } else {

      if ($request->has('resourceType') && $request->input('resourceType') == 'app' && !$request->has('fromDate') && !$request->has('periodFormat')) {
        include_once "/home/steelmin/public_html/redisFn.php";
        $region = $request->region;
        $commodity = $request->commodity;
        $columnNameOfCommodity = $request->columnNameOfCommodity;
        $columnNameOfRegion = $request->columnNameOfRegion;
        $dataType = $request->dataType;
        $unit = $request->unit;
        $headerColumn = $request->headerColumn;


        $redisKeyName = "app_childgraph_" . str_replace(" ", "", $region) . '_' . str_replace(" ", "", $commodity) . '_' . $columnNameOfCommodity . '_' . $columnNameOfRegion . '_' . $dataType . '_' . $unit . '_' . $headerColumn;

        // if(isKeyExistsInRedis($redisKeyName)){
        // $status = 1001;
        // $message = 'success';
        // $data = json_decode(getKeyValueFromRedis($redisKeyName), true);
        // $getresponce = $this->innerResponceHanderApp($data,$status,$message);
        // return response()->json($getresponce);
        // }
      }


      $objCommon = new StplCommonController;
      $title = trim(ucfirst($request->dataType)) . ' - ' . trim(ucfirst($request->commodity)) . ' | ' . trim(ucfirst($request->region));
      $data['childrenTitle'] = $title;

      if ("subSubCommodity" == $request->headerColumn) {
        $data['headerColumnName']['headerName_display'] = "Sub Commodity Wise";
      } else {
        $headerColumnName = DB::table('tbl_stats_datatype_header_dtls')
          ->select('headerName_display')
          ->where('tbl_column_name', '=', $request->headerColumn)
          ->first();
        $data['headerColumnName']['headerName_display'] = $headerColumnName['headerName_display'];
      }

      $isCM = 'SM';
      if ($request->has('filters')) {
        $filter = $request->input('filters');
        if (!empty($filter['app_type'])) {
          $isCM = $filter['app_type'];
          //$isCM = 'CM';
        }
      }

      $data['childrenGraphPoints'] = $objCommon->getChildrenGraphPoint($request->all(), $isCM, $title);

      if ($data['childrenGraphPoints'] == 'Unauthorized') {
        return response()->json(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
      }

      if ($request->input('resourceType') != 'app') {
        $check_portfolio = $objCommon->checkPortfolio($request->all(), "child");
        if ($check_portfolio == "false" || $check_portfolio == "") {
          $data['isAddedToPortfolio'] = "N";
        } else {
          $data['isAddedToPortfolio'] = 'Y';
          $data['addedPortfolioId'] = $check_portfolio;
        }
      }


      if ($data['childrenGraphPoints'] == 'false' || $data['childrenGraphPoints'] == null) {
        if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
          $status = array(
            'code' => 10005,
            'message' => 'No record Found!'
          );
        } else {
          $status = array(
            'status' => 10005,
            'message' => 'No record Found!'
          );
        }
        return response()->json($status);
      }


      $status = 1001;
      $message = 'success';

      if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
        //if($request->has('memid') && $request -> memid == 116707)
        {
          //no from and todate then  default value for case of resourceType is app
          if (!$request->has('fromDate') && !$request->has('periodFormat')) {
            setInRedis($redisKeyName, json_encode($data), 0);
          }
        }
        $getresponce = $this->innerResponceHanderApp($data, $status, $message);
      } else {
        $getresponce = $this->innerResponceHander($data, $status, $message);
      }

      /*$status = 1001;
           $message = 'success';
		   if($request->has('resourceType') && $request->input('resourceType')=='app'){
				$getresponce = $this->innerResponceHanderApp($data,$status,$message);
			}else{
				$getresponce = $this->innerResponceHander($data,$status,$message);
			}*/

      if ($request->debugMode == 'true') {
        $table = array('dataType' => $request->dataType);

        $requreParam = array(
          'resourceType' => 'required|string|web',
          'dataType' => 'required|string|max:20',
          'commodity' => 'required|string|max:20',
          'region' => 'required|string|max:20',
          'fromDate' => 'required|string|max:20',
          'toDate' => 'required|string|max:20',
          //'periodFormat' => 'required|string|max:20',
          //'memid' => 'required|string|max:20',
          'columnNameOfRegion' => 'required|string|max:20',
          'columnNameOfCommodity' => 'required|string|max:20',
          'headerColumn' => 'required|string|max:20',
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function addPortfolio(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:Web,web',
      'dataType' => 'required|string|max:20',
      'commodity' => 'required|string|max:20',
      'region' => 'required|string|max:20',
      'fromDate' => 'required|string|max:20',
      'toDate' => 'required|string|max:20',
      'periodFormat' => 'required|string|max:20',
      'memid' => 'required|string|max:20',
      'columnNameOfRegion' => 'required|string|max:20',
      'columnNameOfCommodity' => 'required|string|max:20',
      'graphType' => 'required|string|max:20',
    ];
    $check = $this->checkInputisValid($rule, $request->all());
    if ($check) {
      return response()->json($check);
    } else {
      $objCommon = new StplCommonController;
      $getid = $objCommon->addtoPortfolio($request->all());
      if ($getid == 'false') {
        $status = array(
          'status' => 2001,
          'message' => 'Invalid input.'
        );
        return response()->json($status);
      }
      $data['addedPortFolioId'] = $getid;

      $status = 1001;
      $message = 'success';
      $getresponce = $this->innerResponceHander($data, $status, $message);
      if ($request->debugMode == 'true') {
        $table = array('portfolio');
        $requreParam = array(
          'resourceType' => 'required|string|web',
          'dataType' => 'required|string|max:20',
          'commodity' => 'required|string|max:20',
          'region' => 'required|string|max:20',
          'fromDate' => 'required|string|max:20',
          'toDate' => 'required|string|max:20',
          'periodFormat' => 'required|string|max:20',
          'memid' => 'required|string|max:20',
          'columnNameOfRegion' => 'required|string|max:20',
          'columnNameOfCommodity' => 'required|string|max:20',
          'graphType' => 'required|string|max:20',
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function removePortfolio(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:Web,web',
      'portFolioId' => 'required|numeric',
      'memid' => 'required|string'
    ];
    $check = $this->checkInputisValid($rule, $request->all());
    if ($check) {
      return response()->json($check);
    } else {
      $objCommon = new StplCommonController;
      $getid = $objCommon->removeFromPortfolio($request->all());
      if ($getid == 'false') {
        $status = array(
          'status' => 10004,
          'message' => 'Given Id Not found in the dataBase'
        );
        return response()->json($status);
      }
      $data['removedPortFolioId'] = $getid;
      $status = 1001;
      $message = 'success';
      $getresponce = $this->innerResponceHander($data, $status, $message);
      if ($request->debugMode == 'true') {
        $table = array('portfolio');
        $requreParam = array(
          'resourceType' => 'required|in:Web,web',
          'portFolioId' => 'required|numeric',
          'memid' => 'required|string'
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function getRecentView(Request $request)
  {
    $trimmed = array_map('trim', $request->all());
    $validate = Validator::make($trimmed, [
      'resourceType' => 'required|in:Web,web,App,app',
      'memid' => 'required',
      'type' => 'required|in:stats_graphs,tabular',
    ]);
    if ($validate->fails()) {
      return response()->json(array(
        'code' => 2001,
        'status' => false,
        'message' => 'Validation failed',
        'errors' => $validate->errors()->toArray(),
        'data' => array(),
      ), 200);
    }
    $objCommon = new StplCommonController;
    $result = $objCommon->getRecentView($request->all());
    if ($result == 'false') {
      return response()->json(array(
        'code' => 10004,
        'status' => false,
        'message' => 'Given Id Not found in the dataBase',
        'data' => array(),
      ));
    }
    $code = 1001;
    $message = "success";
    $getresponce = array(
      'code' => $code,
      'status' => ($code === 1001),
      'message' => $message,
      'data' => $result,
    );
    if ($request->debugMode == 'true') {
      $table = array('recent_activities');
      $requreParam = array(
        'resourceType' => 'required|in:Web,web,App,app',
        'memid' => 'required',
        'type' => 'required|in:stats_graphs,tabular',
      );
      $getresponce['debugMode']['usedtable'] = $table;
      $getresponce['debugMode']['argumentDetail'] = $requreParam;
    }
    return response()->json($getresponce);
  }


  public function innerResponceHander($data, $status, $message)
  {
    $status = array(
      'status' => $status,
      'message' => $message
    );
    $responce = array(
      'data' => $data,
      'status' => $status
    );
    return $responce;
  }

  public function innerResponceHanderApp($data, $status, $message, $otherParam = [])
  {
    $status = array(
      'code' => $status,
      'message' => $message
    );
    $responce = array(
      'data' => $data,
      'status' => $status
    );
    $responce = array_merge($responce, $otherParam);
    return $responce;
  }

  public function getUserSessData(Request $request)
  {
    $memid = 0;
    //update memId if getting in POST request
    if ($request->memid) {
      $memid = trim($request->memid);
    }

    if ($memid <= 0) {
      $status = array(
        'status' => 2001,
        'message' => 'Unauthorized action'
      );
      return response()->json($status);
    }
    $isCM = 'SM';
    if ($request->has('filters')) {
      $filter = $request->input('filters');
      if (!empty($filter['app_type'])) {
        $isCM = $filter['app_type'];
      }
    }

    $user = new User($memid, $isCM);
    // $isAccessible =  $user->isAccessible($resourceType='Web', $section='Statistics_Graph');
    $isAccessible =  $user->isAccessible($resourceType = 'Web', $section = 'Statistics_Graph', '', '', '', $request['selected_market']);
    if ($isAccessible != -1) {
      $status = array(
        'status' => 2001,
        'message' => 'Not a valid user, no access'
      );
      return response()->json($status);
    }
    $data = [];
    if (!empty(Session::get($request['selected_market'])['sectionFromDate'])) {
      $sectionFromDate = Session::get($request['selected_market'])['sectionFromDate'];
      if ($memid == 27956 || $memid == 95898 || $memid == 123110 || $memid == 127182  || $memid == 113678 || $memid == 161902 || $memid == 163411) {
        $sectionFromDate = '';
      }
      $sectionTodate = Session::get($request['selected_market'])['sectionTodate'];
      $sectionTodate = strtotime($sectionTodate) <= strtotime($GLOBALS['currDate']) ? $sectionTodate : $GLOBALS['currDate'];
      $data['startDate'] = $sectionFromDate;
      $data['endDate'] = $sectionTodate;
    } else {
      $data['startDate'] = $GLOBALS['currDate'];
      $data['endDate'] = $GLOBALS['currDate'];
    }

    $status = 1001;
    $message = "success";
    $getresponce = $this->innerResponceHander($data, $status, $message);
    return response()->json($getresponce);
  }

  public function checkInputisValid($rule, $reqx)
  {
    $trimmed = array_map('trim', $reqx);
    $messages = [
      'resourceType.required' => 'resourceType required!',
    ];
    $validate = Validator::make($trimmed, $rule, $messages);
    if ($validate->fails()) {
      $validationFailedArray = array();
      $validationFailedArray['status'] = array(
        'code' => 2001,
        'messages' => 'Invalid input.'
        //'message' => $validate->errors()->first()
      );
      return $validationFailedArray;
    }
  }

  public function getFilterAppMenu(Request $request)
  {
    /* $rule = [
          'resourceType' => 'required|in:App,app,Web,web',
          'requireData' => 'required|in:regionCommodity',
          'requiredFor' => 'required|in:statistics,price',
          'source' => 'required|in:stats_graphs',
          'dataType' => 'required'
        ];
        $check = $this->checkInputisValid($rule,$request->all()); */
    $check = false;
    if ($check) {
      return response()->json($check);
    } else {
      $isCM = 'SM';
      if ($request->has('filters')) {
        $filter = $request->input('filters');
        if (!empty($filter['app_type'])) {
          $isCM = $filter['app_type'];
        }
      }

      if ($request->has('appType') && $request->input('appType') == 'CM')
        $isCM = 'CM';
      if ($request->has('app_type') && $request->input('app_type') == 'CM')
        $isCM = 'CM';
      $selected_market = '';
      if ($request->has('selected_market') && !empty($request->input('selected_market')))
        $selected_market = $request->input('selected_market');

      //store the commodities, regions in cache for 24 hours.
      //include_once "/home/steelmin/public_html/redisFn.php";
      //$redisKey = "stats_app_CommRegMenu_$isCM";
      if ($request->input('memid') == 56350 || $request->input('memid') == 99375) {
        $objCommon = new StplCommonController;
        $data = $objCommon->getCommRegMenuByCount($att = [], $isCM);
      }/*elseif(isKeyExistsInRedis($redisKey)){
		        $data = json_decode(getKeyValueFromRedis($redisKey), true);
		    } else*/ {
        $objCommon = new StplCommonController;
        $data = $objCommon->getCommRegMenuByCount($att = [], $isCM, $selected_market);

        //setInRedis($redisKey, json_encode($data), 86400);
      }

      //$infograhicsData = app('App\Http\Controllers\v2019\infographController')->getInfograph($request);
      $infograhicsData = app('App\Http\Controllers\v2019\infographController')->getInfographBM($request);
      $data['infograhics'] = $infograhicsData->getData()->data;

      //$infographController = new InfographController;
      //$data['infograhics'] = $infographController->getInfograph($request->all());

      $status = 1001;
      $message = "success";

      if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
        $getresponce = $this->innerResponceHanderApp($data, $status, $message);
      } else {
        $getresponce = $this->innerResponceHander($data, $status, $message);
      }

      if ($request->debugMode == 'true') {
        $table = array('tbl_stats_datatype_header_list_bm');
        $requreParam = array(
          'resourceType' => 'required|string|web',
          'requireData' => 'required|string|datatype',
          'requiredFor' => 'required|string|statistics,price',
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function getStatsHeaderLists(Request $request)
  {
    $rule = [
      'resourceType' => 'required|in:App,app,Web,web',
      'commodity' => 'required',
      'region' => 'required'
    ];
    $check = $this->checkInputisValid($rule, $request->all());
    $check = false;
    if ($check) {
      return response()->json($check);
    } else {
      $isCM = 'SM';
      if ($request->has('filters')) {
        $filter = $request->input('filters');
        if (!empty($filter['app_type'])) {
          $isCM = $filter['app_type'];
        }
      }

      if ($request->has('appType') && $request->input('appType') == 'CM')
        $isCM = 'CM';
      if ($request->has('app_type') && $request->input('app_type') == 'CM')
        $isCM = 'CM';

      //form the redis key with all the parameters being passed to the below function
      $redisKey = "stats_app_StatsHeaderList_$isCM";
      if ($request->has('dataType')) {
        $dataType = $request->input('dataType');
        $redisKey .= "_" . str_replace(" ", "", $dataType);
      }
      if ($request->has('region')) {
        $region = $request->input('region');
        $redisKey .= "_" . str_replace(" ", "", $region);
      }
      if ($request->has('commodity')) {
        $commodity = $request->input('commodity');
        $redisKey .= "_" . str_replace(" ", "", $commodity);
      }
      if ($request->has('filterType')) {
        $filterType = $request->input('filterType');
        $redisKey .= "_" . str_replace(" ", "", $filterType);
      }
      $selected_market = '';
      if ($request->has('selected_market')) {
        $selected_market = $request->input('selected_market');
      }


      //store the commodities, regions in cache for 24 hours.
      include_once "/home/steelmin/public_html/redisFn.php";

      /* if($request->input('memid')==56350 || $request->input('memid')==99375 || $request->input('memid')==115566){//99375=> gIVEN TO FREE LANCER 
				$objCommon = new StplCommonController;
    			$data = $objCommon->getStatsHeaderList($request->all(), $isCM);
			}elseif(isKeyExistsInRedis($redisKey)){
			    //echo $redisKey; dd();
		        $data = json_decode(getKeyValueFromRedis($redisKey), true);
		    } else */ {
        $objCommon = new StplCommonController;
        $data = $objCommon->getStatsHeaderList($request->all(), $isCM);

        setInRedis($redisKey, json_encode($data), 86400);
      }

      $status = 1001;
      $message = "success";

      if ($request->has('resourceType') && $request->input('resourceType') == 'app') {
        $memid = 0;

        if ($request->has('memid')) {
          //$memid = trim($request->input('memid'));
          $memid = htmlentities(trim($request->input('memid')), ENT_QUOTES);

          if (!is_numeric($memid)) {
            return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
          }
        } elseif ($request->has('accessToken') && !empty($request->input('accessToken'))) {
          $token = $request->input('accessToken');
          $auth = new authentication();
          $memid = $auth->authToken($token, $isCM);
        }

        $user = new User($memid, $isCM);
        $isAccessible =  $user->isAccessible($resourceType = 'app', $section = 'Statistics_Graph', '', '', '', $selected_market);
        //$isAccessible =  $user->isAccessible($resourceType='app', $section='Statistics_Graph');

        if (!empty(Session::get($selected_market)['startdate'])) {
          $sectionFromDate = Session::get($selected_market)['sectionFromDate'];
          $sectionTodate = Session::get($selected_market)['sectionTodate'];
          $sectionTodate = strtotime($sectionTodate) <= strtotime($GLOBALS['currDate']) ? $sectionTodate : $GLOBALS['currDate'];
          //$value['startDate'] = $sectionFromDate;
          //$value['endDate'] = $sectionTodate;

        } else {
          $sectionFromDate = $GLOBALS['currDate'];
          $sectionTodate = $GLOBALS['currDate'];
        }
        $otherParam['accessFromDate'] = $sectionFromDate;
        $otherParam['accessTodate'] = $sectionTodate;
        $otherParam['quantityUnit'] = "MnT,MT";

        $getresponce = $this->innerResponceHanderApp($data, $status, $message, $otherParam);
      } else {
        $getresponce = $this->innerResponceHander($data, $status, $message);
      }

      if ($request->debugMode == 'true') {
        $table = array('tbl_stats_datatype_header_list_bm');
        $requreParam = array(
          'resourceType' => 'required|string|web',
          'commodity' => 'required',
          'region' => 'required'
        );
        $getresponce['debugMode']['usedtable'] = $table;
        $getresponce['debugMode']['argumentDetail'] = $requreParam;
      }
      return response()->json($getresponce);
    }
  }

  public function getStatsVendorAPI(Request $request)
  {
    if ($request->has('api_key') && $request->has('sub_api_key')) {
      $api_key = $request->input('api_key');
      $sub_api_key = $request->input('sub_api_key');

      //check if api_key is valid	
      ///DB::enableQueryLog(); 
      $api_key_dtls =
        DB::table('tbl_stats_api')
        ->where("api_key", "=", $api_key)
        ->where("sub_api_key", "=", $sub_api_key)
        ->where("key_valid_till", ">=", date("Y-m-d"))
        ->where("key_valid_from", "<=", date("Y-m-d"))
        ->first();
      ///print_r($api_key_dtls);
      if (count($api_key_dtls) == 0) {
        $code = 2001;
        $message = "api key or sub key is invalid or it has expired.";
        return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
      } else {
        $memid = 116707;
        $filters = array();
        $filters['resourceType'] = $api_key_dtls['resourceType'];
        $filters['region'] = $api_key_dtls['region'];
        $filters['periodFormat'] = $api_key_dtls['periodFormat'];
        //$filters['fromDate'] = $api_key_dtls['periodFormat']=='yearly'?$api_key_dtls['access_from_year']:($api_key_dtls['periodFormat']=='monthly'?$api_key_dtls['access_from_month']:$api_key_dtls['access_from_qtr']);
        $filters['fromDate'] = $api_key_dtls['access_from'];

        $month = date("n");
        $yearQuarter = ceil($month / 3);
        $filters['toDate'] = $api_key_dtls['periodFormat'] == 'yearly' ? date('Y') : ($api_key_dtls['periodFormat'] == 'monthly' ? date('M Y') : "Q$yearQuarter " . date('Y'));
        $filters['commodity'] = $api_key_dtls['commodity'];
        $filters['mainCommodity'] = $api_key_dtls['mainCommodity'];
        $filters['columnNameOfRegion'] = $api_key_dtls['columnNameOfRegion'];
        $filters['columnNameOfCommodity'] = $api_key_dtls['columnNameOfCommodity'];
        $filters['dataType'] = $api_key_dtls['dataType'];
        $filters['unit'] = $api_key_dtls['unit'];
        $filters['headerColumn'] = $api_key_dtls['headerColumn'];
        $filters['memid'] = $memid;
        /*
				resourceType: web
				region: India
				fromDate: 2014
				toDate: 2022
				commodity: Fines/Lumps
				periodFormat: yearly
				columnNameOfRegion: country
				columnNameOfCommodity: subCommodity
				dataType: production
				unit: MnT
				memid:  56350 
				mainCommodity: Iron Ore
				headerColumn: state_wise
				*/

        if ($api_key_dtls['graph_type'] == 'child')
          $url = "https://www.steelmint.com/api/public/v2019/statistics/graph2ndLevel";
        else
          $url = "https://www.steelmint.com/api/public/v2019/statistics/graph";
        $res = $this->postCURL($url, $filters);
        $result = json_decode($res, true);
        if ($result['status']['status'] == 1001) {
          ///$commodityWiseData = $result['data'];
          if ($api_key_dtls['graph_type'] == 'child')
            return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result['data']['childrenGraphPoints']['value']));
          else
            return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result['data']['graphValues']));
        } else {
          $code = 2001;
          $message = "invalid stats input";
          return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
        }
      }
    } else {
      $code = 2001;
      $message = "api key or sub_api_key is invalid.";
      return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
    }
  }

  public  function postCURL($url, $params)
  {
    $fields_string = http_build_query($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

    $output = curl_exec($ch);
    $information = curl_getinfo($ch);

    return $output;
  }


  public function getGraphs_koyladarpan(Request $request)
  {
    //die('here');

    $rule = [
      'resourceType' => 'required|in:Web,web,app',
      'fromDate' => 'required|string|max:10',
      'toDate' => 'required|string|max:10'
    ];
    $check = $this->checkInputisValid($rule, $request->all());

    if ($check != '') {
      return response()->json($check);
    } else {
      $data = DB::table("tbl_koyladarpan")->select('*')->where('f_fieldname', 'CIL');
      if ($request->has('fromDate')) {
        $data = $data->where('f_date', '>=', $request->input('fromDate'));
      }
      if ($request->has('to')) {
        $data = $data->where('f_date', '<=', $request->input('toDate'));
      }
      $data =  $data->orderBy('f_date', 'ASC')->get();
      // $data=  $data->orderBy('YYMM','ASC')->get();
      $responceArray = array();
      $data = json_decode(json_encode($data), true);
      if (count($data) > 0) {

        foreach ($data as $key => $value) {
          $responceArray['graphValues'][$value['f_type']][]  = array(strtotime($value['f_date']) * 1000, round(($value['f_valueasondate'] * 1), 2));
        }
      } else {
        return response()->json(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
      }



      $responceArray['unitTextToShow'] = '';

      if ($request->has('unitTextToShow')) {
        $responceArray['unitTextToShow'] = $request->input('unitTextToShow');
      }
      $responceArray['title'] = "Koyla Darpan Graph";
      if ($request->has('graphTitle')) {
        $responceArray['title'] = $request->input('graphTitle');
      }


      $status = 1001;
      $message = 'success';
      $getresponce = $this->innerResponceHander($responceArray, $status, $message);
      //   print_r($getresponce);
      return response()->json($getresponce);
    }
  }
  public function getGraphs_cil(Request $request)
  {
    //die('here');

    $rule = [
      'resourceType' => 'required|in:Web,web,app',
      'fromDate' => 'required|string|max:10',
      'toDate' => 'required|string|max:10'
    ];
    $check = $this->checkInputisValid($rule, $request->all());

    if ($check != '') {
      return response()->json($check);
    } else {

      $data = DB::table("tbl_cil_auction")->select(DB::raw('concat(LEFT(month,3),\'-\',year) as YearMonth'), DB::raw('SUM(Quantity_Offered) as total_offered'), DB::raw('SUM(Quantity_Booked) as total_booked'));
      if ($request->has('fromDate')) {
        $fromDate =  $request->input('fromDate');
        $data = $data->where('formattedDate', '>=', $fromDate);
      }
      if ($request->has('toDate')) {
        $toDate =  $request->input('toDate');
        //$date_cond = " and formattedDate <= '$toDate'"; 
        $data = $data->where('formattedDate', '<=', $toDate);
      }
      $data = $data->groupBy('year', 'month');
      // print_r($data->orderBy('year','ASC')->orderBy('month','ASC')->toSql());
      $data =  $data->orderBy('formattedDate', 'ASC')->get();
      // $data=  $data->orderBy('YYMM','ASC')->get();

      $responceArray = array();
      $data = json_decode(json_encode($data), true);
      if (count($data) > 0) {
        foreach ($data as $key => $value) {
          $responceArray['graphValues'][] = array('x' => $value['YearMonth'], 'y' => array("Quantity Offered" => $value['total_offered'] / 1000000, "Quantity Booked" => $value['total_booked'] / 1000000));
        }
      } else {
        return response()->json(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
      }



      $responceArray['unitTextToShow'] = 'CIL Auction Graph';

      if ($request->has('unitTextToShow')) {
        $responceArray['unitTextToShow'] = $request->input('unitTextToShow');
      }
      $responceArray['title'] = "CIL Auction Graph";
      if ($request->has('graphTitle')) {
        $responceArray['title'] = $request->input('graphTitle');
      }

      $status = 1001;
      $message = 'success';
      $getresponce = $this->innerResponceHander($responceArray, $status, $message);
      //   print_r($getresponce);
      return response()->json($getresponce);
    }
  }
}
