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

class Tenders1Controller 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');		
        }
    }
	
	public function getTenders(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');	
		elseif ($request->has('pageNumber') && $request->input('pageNumber')!='')
			$pageValue = $request->input('pageNumber');
		
		if($resourceType=='web'){
			$code = 1001;				
			$message = "Success";
							
			if ($request->has('memid') && $request->input('memid')!=''){								
				$offset = ($pageValue-1)* DEFAULT_TENDERS_LIMIT;
				
				$memid = $request->input('memid');
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
				//print_r($filters);
				
				if ($user_id) {
					$user = new User($user_id, $this->appType);
					$isAccessible = $user->getTakenServicesByUser($item='tenders', $at_place='mobileapp', $tenderDateToCompare=date('Y-m-d'));
					if ($isAccessible==-1) {
						$accessType = 'post';
					}else{
						$accessType = 'pre';
					}
					
					//run query here
					if($pageValue>1 || count($filters)>0){			
						$result = \ApiQuery::getTendersRows($memid, $source, $resourceType, $type='', $filters,$accessType,DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
						/* $sql = DB::table('tbl_tenders')->offset($offset)->limit(DEFAULT_LIMIT); 
						$result = $sql->get(); */
					}else {/// data from json array file 
					
						$result = \ApiQuery::getTendersRows($memid, $source, $resourceType, $type='default', $filters,$accessType,DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
						////$sql = DB::table('tbl_tenders')->limit(DEFAULT_TENDERS_LIMIT); 
						///include_once "/home/steelmin/public_html/api/storage/v2019/json/web/tenders/listing_post.php";
					}
				}else{
					$code = 2013;
					$message = "Unauthorized action.";
				}
			}else{/// pre data from json array file 
				////$sql = DB::table('tbl_tenders')->limit(5);
				$result = \ApiQuery::getTendersRows($memid=0, $source, $resourceType, $type='default', $filters,'pre',DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
				//include_once "/home/steelmin/public_html/api/storage/v2019/json/web/tenders/listing_pre.php";
			}
		}else{
			///include('/home/steelmin/public_html/api/storage/v2019/tenders_pre.php');
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
			   // $auth = new authentication();
					$auth = new authentication();	
					$token = $request->input('accessToken');
					$memid = $auth->authToken($token);	
					
					//$pageValue = $request->input('pageValue');					
					$offset = ($pageValue-1)* DEFAULT_TENDERS_LIMIT;
					
					if ($memid) {
						$user = new User($memid, $this->appType);
						$isAccessible = $user->getTakenServicesByUser($item='tenders', $at_place='mobileapp', $tenderDateToCompare=date('Y-m-d'));
						if ($isAccessible==-1) {
							$accessType = 'post';
						}else{
							$accessType = 'pre';
						}
						if($pageValue>1 || count($filters)>0){			
							$result = \ApiQuery::getTendersRows($memid, $source, $resourceType, $type='', $filters,$accessType,DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
						}else {/// data from json array file 
							$result = \ApiQuery::getTendersRows($memid, $source, $resourceType, $type='default', $filters,$accessType,DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
							////$sql = DB::table('tbl_tenders')->limit(DEFAULT_TENDERS_LIMIT); 
							//include_once "/home/steelmin/public_html/api/storage/v2019/json/app/tenders/post.php";
						}
						
						$code = 1001;
						$message = "Success";
					}else{
						$code = 2013;
						$message = "Unauthorized action.";
					}
			}else{
				///not loggedin/visitor///
				$result = \ApiQuery::getTendersRows($memid=0, $source, $resourceType, $type='default', $filters,'pre',DEFAULT_TENDERS_LIMIT, $offset, $this->appType);
					//include_once "/home/steelmin/public_html/api/storage/v2019/json/app/intel/intel_app_pre.php";
				$code = 1001;
				$message = "Success";
			}
		}
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }  
	
	public function getTendersFilter(Request $request)
    {      
		$result = array();
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$currentDate = $GLOBALS['currDate'];
		$_cm_cond='';
		
		if($this->appType == 'CM'){
			$_cm_cond = " AND category_all like '%coal%'";
		}
		//$_cm_cond.= "AND due_date <> '0000-00-00 00:00:00' AND due_date >= '$currentDate'";
		$commodity_list = DB::connection('mysql')
            ->table('tbl_tenders')
            ->selectRaw('DISTINCT commodityId, subCommodityId')
            ->whereRaw(" subCommodityId<>'' and verified = 1  $_cm_cond")
	        ->orderByRaw('TRIM(subCommodityId)')
            ->get();
		///print_r($commodity_list);
		$temp = array();
        foreach($commodity_list as $commodies ){
			$commodityId = explode(',', $commodies['commodityId']);
			$subCommodityId = explode(',', $commodies['subCommodityId']);
            foreach($commodityId as $commodity){
				if($commodity)
					$temp["commodities"][]= $commodity;
            }
			foreach($subCommodityId as $subCommodity){
				if($subCommodity)
					$temp["subCommodities"][]= $subCommodity;
			}
		}
		$scIds = implode(',', $temp["subCommodities"]);
		//
		$commodity_arr = DB::connection('mysql')
            ->table('tbl_region_commodity_master as c')
			->leftjoin('tbl_region_commodity_master as p', 'p.id', '=', 'c.parentID')
            ->selectRaw('c.ID, c.itemName, c.parentID, p.itemName as parent_itemName')
            ->whereRaw(" c.section='price' and c.itemType='commodity' and c.id in ($scIds)")
	        ->orderByRaw('c.parentID, c.ID')
            ->get();
		/* $commodity_arr = DB::connection('mysql')
            ->table('tbl_region_commodity_master  as c')
			->leftJoin('tbl_region_commodity_master as p' , 'c.id' , '=' , 'p.parentID')
            ->selectRaw('c.ID, c.itemName, c.parentID, p.itemName')
            ->whereRaw(" c.section='tenders' and c.itemType='commodity' and c.id in ($scIds)")
	        ->orderByRaw('c.ID')
            ->get(); */
			///dd(DB::getQueryLog());
		$pItem='';$items=array();
		foreach($commodity_arr as $commodies ){
			$items[$commodies['parentID']]["name"] = $commodies['parent_itemName'];
			$items[$commodies['parentID']]["subCommodities"][] =  array(
                                        "isSelectable" => "Y",
                                        "id" => $commodies['ID'],
                                        "name" => $commodies['itemName']
                                     ) ;
		}
		
		foreach($items as $id=>$item){
			$result["commodities"] = array(
							"isSelectable" => "N",
							"id" => $id,
							"name" => $item['name'],
							"subCommodities"=>$item["subCommodities"]
						);
		}
		/* DB::enableQueryLog(); 
		$commodity_arr = DB::connection('mysql')
            ->table('tbl_tenders as t')
			->leftjoin('tbl_region_commodity_master as c', 'c.id', '=', 't.regionID')
			->leftjoin('tbl_region_commodity_master as p', 'p.id', '=', 'c.parentID')
            ->selectRaw('c.ID, c.itemName, c.parentID, p.itemName as parent_itemName')
            ->whereRaw(" c.section='price' and c.itemType='region' ")
	        ->orderByRaw('c.parentID, c.ID')
            ->get();
			dd(DB::getQueryLog()); */
			
		//////
		$company_list = DB::connection('mysql')
            ->table('tbl_tenders')
            ->selectRaw('DISTINCT TRIM(company_name) as company_name')
            ->whereRaw(" company_name<>'' and verified = 1 $_cm_cond")
	        ->orderByRaw('TRIM(company_name)')
            ->get();		
			
        foreach($company_list as $company )
            $result["companyName"][]= $company['company_name'] ;
		/* if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid')!=''){
				include_once "/home/steelmin/public_html/api/storage/v2019/tender_filter_post.php";
			}else{
				include_once "/home/steelmin/public_html/api/storage/v2019/tender_filter_post.php";
			}
		} else {
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
			// $auth = new authentication();
				$token = $request->input('accessToken');
				if(empty($token)){
					//if($source=='home')
						include_once "/home/steelmin/public_html/api/storage/v2019/tender_filter_post.php";
					$code = 2013;
					$message = "User not found.";
				}else{
					//if($source=='home')
						include_once "/home/steelmin/public_html/api/storage/v2019/tender_filter_post.php";
					$code = 1001;
					$message = "Success";
				}
			}else{
				//if($source=='home')
					include_once "/home/steelmin/public_html/api/storage/v2019/tender_filter_post.php";
				
				$code = 1001;
				$message = "Success";
			}
		} */	
		$code = 1001;
				$message = "Success";
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getTendersCommodityCount(Request $request)
    {      
		$result = array();
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid')!=''){
				//include_once "/home/steelmin/public_html/api/storage/v2019/tender_count_post.php";
				$result = \apiQuery::getTendersCount();
			}else{
				//include_once "/home/steelmin/public_html/api/storage/v2019/tender_count_post.php";
				$result = \apiQuery::getTendersCount();
			}
		} else {
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
			// $auth = new authentication();
				$token = $request->input('accessToken');
				if(empty($token)){
					//if($source=='home')
						//include_once "/home/steelmin/public_html/api/storage/v2019/tender_count_post.php";
					$result = \apiQuery::getTendersCount();
					$code = 2013;
					$message = "User not found.";
				}else{
					//if($source=='home')
						//include_once "/home/steelmin/public_html/api/storage/v2019/tender_count_post.php";
						$result = \apiQuery::getTendersCount();
					$code = 1001;
					$message = "Success";
				}
			}else{
				//if($source=='home')
					//include_once "/home/steelmin/public_html/api/storage/v2019/tender_count_post.php";
					$result = \apiQuery::getTendersCount();
				
				$code = 1001;
				$message = "Success";
			}
		}                         
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	
	public function getTendersCollection(Request $request)
    {      
		$result = array();
		///$source = $request->input('source');
		//include_once "/home/steelmin/public_html/api/storage/v2019/tenders_collection_list.php";
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		/* if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid')!=''){
			 //	
			}else{
			 // 
			}
		} else {
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
			// $auth = new authentication();
				$token = $request->input('accessToken');
				if(empty($token)){
					
					$code = 2013;
					$message = "User not found.";
				}else{
					$code = 1001;
					$message = "Success";
				}
			}else{
				
				$code = 1001;
				$message = "Success";
			}
		} */
		$code = 1001;
		$message = "Success";
		$result = \ApiQuery::getTendersCollectionRows($this->appType);
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}

	public function getTenderDetails(Request $request)
    {      
		$resourceType = "app";
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
		}else{
			$code = 2013;
			$message = "Invalid! itemId missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
		    $auth = new authentication();	
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			$memid = $request->input('memid');
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		
		if($memid){
			$user = new User($user_id, $this->appType);
			$isAccessible = $user->getTakenServicesByUser($item='tenders', $at_place='mobileapp', $tenderDateToCompare=date('Y-m-d'));
			if ($isAccessible==-1) {
				$accessType = 'post';
			}else{
				$accessType = 'pre';
			}

			$resultDetails = \ApiQuery::getTendersRows($memid, $source='', $resourceType, $type='', $filters, $accessType, 1, $offset=0);
			
			if(count($resultDetails)>0){
				$result = $resultDetails[0];
			}
			$code = 1001;
			$message = "Success";
			
		}else{
			///not loggedin/visitor///
			
			$resultDetails = \ApiQuery::getTendersRows($memid, $source='', $resourceType, $type='', $filters, $accessType, 1, $offset=0);
			if(count($resultDetails)>0){
				$result = $resultDetails[$itemID];
			}
			$code = 1001;
			$message = "Success";
		}
		
		/* $result = array();
		$source = $request->input('source');
		
		if ($request->has('memid') && $request->input('memid')!='') {
           // $auth = new authentication();
            $token = $request->input('memid');
			if($token == ''){
				include_once "/home/steelmin/public_html/api/storage/v2019/web/tenders_details_pre.php";
				$code = 2013;
				$message = "User not found.";
			}else{
				include_once "/home/steelmin/public_html/api/storage/v2019/web/tenders_details_post.php";
				$code = 1001;
				$message = "Success";
			}
        }else{
			include_once "/home/steelmin/public_html/api/storage/v2019/web/tenders_details_pre.php";
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result)); 
    }
	
}
