<?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 Session;

class ReportsController extends Controller
{
    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';
			 }
		} elseif($request->has('app_type') && $request->input('app_type') == true) {
            $this->appType = $request->input('app_type');		
        }
    }
	
	public function getReportPath(Request $request)
    {      
		$resourceType = "app";
		$source = "listing";
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('source'))
			$source = strtolower($request->input('source'));
		
		if($request->has('itemID'))
			$itemID = strtolower($request->input('itemID'));
		else
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Invalid request.")));
		
		$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');
			    $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();
			$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){
			$accessType = 'post';//check for each report, 
			$user = new User($user_id, $this->appType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Report_s', $itemID);
			
			//sectionFromDate & sectionTodate
			if ($isAccessible==-1) {
				$accessType = 'post';
				
				$dbresult2 = DB::table('tbl_steelreport')
					->select('file' )				
					->where('id' , $itemID)
					->first();
				$filePath = BASEURL."reports/".$dbresult2['file'];
				$result['filePath'] = $filePath;
				return new JsonResponse(array("status"=>array("code" => 1001, "message" => 'Success'), "data"=> $result));
			}else{
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
			} 
		}else
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));	
    } 
	
	public function getReports(Request $request)
    {     
		 
		$resourceType = "app";
		$source = "listing";
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('source'))
			$source = strtolower($request->input('source'));
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
		}	
		
		$offset=0;
		$pageValue=1;
		
		if ($request->has('pageValue') && $request->input('pageValue')!='')
			$pageValue = $request->input('pageValue');	
		
		if(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') 
		    $offset = ($pageValue-1)* 2;		
		else 
		    $offset = ($pageValue-1)* DEFAULT_REPORTS_LIMIT;		
		
		$user_id=0;
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			$token = $request->input('accessToken');
			$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 = 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();
			$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){
			$accessType = 'post';//check for each report, 
		}
		
		if($pageValue>1 || count($filters)>0){
			$result = \ApiQuery::getReportsRows($user_id, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_REPORTS_LIMIT, $offset, $this->appType);			
		}else {/// data from json array file 		
			$result = \ApiQuery::getReportsRows($user_id, $source, $resourceType, $type='default', $filters, $accessType,DEFAULT_REPORTS_LIMIT, $offset, $this->appType);
		}

		if(strtolower($resourceType)=="app" && !isset($filters['reportID'])){
			usort($result, array($this, "build_sorted"));
		}		
		$code = 1001;				
		$message = "Success";	

        if(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
            $ex = $result;
            $result = array();
            $result = $ex["dataValue"];
            $cntValue = $ex["cntValue"];
        } else {
            $cntValue = 0;
        }

		header('Content-Disposition: attachment; filename="filename.ext"');
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "cntValue"=> $cntValue));
    } 
	private function build_sorted ($a, $b){
            if ($a["orderForRegularRpts"] == $b["orderForRegularRpts"]) {
                return 0;
            }
            return ($a["orderForRegularRpts"] < $b["orderForRegularRpts"]) ? -1 : 1;
    }	    
    public function sendSampleReport(Request $request){
		$resourceType = "web";
	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('email'))
			$email = strtolower($request->input('email'));

		if($request->has('itemID'))
			$itemID = strtolower($request->input('itemID'));
			
		$result = \ApiQuery::emailSampleReport($email, $itemID);			
        
	    return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Succesfully Sent!!")));
    }
	
	public function getReportCount(Request $request){
		$result = array();
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');

			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
				$filters['commodityID'] = array(401);//if coalmint then show only colamint related reports
			}
		}	
		
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			/*$result = array(
				"upcoming" => 57,
				"archived" => 365
			 );*/
			 
			 $result = \ApiQuery::reportsCategoryCount($filters);			
		} elseif($resourceType=='app') {
			$code = 1001;
			$message = "Success";
			/* if ($request->has('accessToken') && $request->input('accessToken')!='') {
			   // $auth = new authentication();
				$token = $request->input('accessToken');
				if(empty($token)){
					include_once "/home/steelmin/public_html/api/storage/v2019/reports_pre.php";
					$code = 2013;
					$message = "User not found.";
				}else{
					include_once "/home/steelmin/public_html/api/storage/v2019/reports_post.php";
					$code = 1001;
					$message = "Success";
				}
			}else{
				include_once "/home/steelmin/public_html/api/storage/v2019/reports_pre.php";
				$code = 1001;
				$message = "Success";
			} */
		}else{
			$code = 2001;
			$message = "invalid input";
		}
	   return new JsonResponse(array(
			"code" => $code,
			"status" => ($code === 1001),
			"message" => $message,
			"data" => $result
		));
	}
	
	function testCases(Request $request){
		$memid =116688;
		$section='Statistics_Graph';
		$resourceType="web";
		if($request->has('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")));
                }
			
		}if($request->has('section'))
			$section = $request->input('section');
		if($request->has('resourceType'))
			$resourceType = $request->input('resourceType');
	    $user = new User($memid, $this->appType);
	    //$isAccessible = $user->getUserServicePackages();
	    
	    
	    //$isAccessible = $user->isAccessible($resourceType, $section='Report_s', $itemID='', $itemDate='');
	    $isAccessible = $user->isAccessible($resourceType, $section, $itemID='', $itemDate='');
	    //sectionFromDate & sectionTodate
		if ($isAccessible==-1) {
			$accessType = 'post';
		}else{
			$accessType = 'pre';
		}
	    // echo $this->appType.'--'.$isAccessible.'--'.$accessType;
		// echo '<br> :: '. Session::get('my_name');
		 print_r(session()->all());
	}
	
	public function getNewsletterContent(Request $request)
    {      
		$result = array();	
		$result = DB::table('tbl_newsletter_content')
					->where('letter_name' , $request->input('reportName'))
					->get();
		
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => 'Success'), "data"=> $result));	
    }

	public function getNewsletterPriceGraph(Request $request)
    {      
		$result = array();
		if($request->has('reportName') && $request->input('reportName')!=''){
			
			$result = DB::table('tbl_newsletter_pricegraph')
					->where('report_name' , $request->input('reportName'))
					->orderBy('order_by','ASC')
					->get();
			$code = 1001;
			$message = "Success";
		}else{
			$code = 2001;
			$message = "invalid report";
		}		
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));	
    }
	
	public function getNewsletterStatsGraph(Request $request)
    {
		$result = array();
		if($request->has('reportName') && $request->input('reportName')!=''){
			
			$result = DB::table('tbl_newsletter_statsgraph')
					->where('reportID' , $request->input('reportName'))
					->orderBy('orderBy','ASC')
					->get();
			$code = 1001;
			$message = "Success";
		}else{
			$code = 2001;
			$message = "invalid report";
		}
		
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));		
    }
}
