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

use App\Traits\ReferenceData;

class TendersController extends Controller
{ 
	use ReferenceData {
        getReferenceData as protected refData;
    }
	
    public $appType = 'SM' ;
	public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;			
        }
		$this->appType = 'SM';
		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 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');
		    
			///cphrase code
			if( isset($filters['searchTerms'])){
				$common = new Common();
				$innerFilterCond = $common->getSearchTermFilterCond($filters['searchTerms'], 'tender');
				
				if(!empty($innerFilterCond)){
					unset($filters['searchTerms']);
					$filters['innerFilterCond'] = $innerFilterCond;			 
			    }
			    			
			}///
// 			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
// 				$this->appType = $filters['app_type'];//if coalmint then show only colamint related tenders
// 			}
			
		}
		$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( $source == 'portfolio' )
			    $offset = ($pageValue-1)* 7;				
			else
			    $offset = ($pageValue-1)* DEFAULT_TENDERS_LIMIT;				
			if ($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")));
                }

			    if( $source == 'portfolio' )
			        $offset = ($pageValue-1)* 7;				
			    else
				    $offset = ($pageValue-1)* DEFAULT_LIMIT;	
				
				
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
				//print_r($filters);
				
				if ($user_id) {
					$accessType = 'post'; 
					//run query here
					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);
					}
				}else{
					$code = 2100;
					$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";
			}
			
            //if(strtolower($source) == "mapview")
			//	$result = $this->result_web($result);
				
		}else{
			///include('/home/steelmin/public_html/api/storage/v2019/tenders_pre.php');
			if( $source == 'portfolio' )
			    $offset = ($pageValue-1)* 7;				
			else
			    $offset = ($pageValue-1)* DEFAULT_TENDERS_LIMIT;
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
				if( $source == 'portfolio' )
			        $offset = ($pageValue-1)* 7;				
			    else
				    $offset = ($pageValue-1)* DEFAULT_LIMIT;
			   // $auth = new authentication();
					$auth = new authentication();	
					$token = $request->input('accessToken');
					$memid = $auth->authToken($token,$this->appType);	
					
					//$pageValue = $request->input('pageValue');					
					
					
					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';
						} */
						$accessType = 'post';
						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 = 2100;
						$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";
			}
		}
		
		$recentTenders = [];

		$recentTenders = array(
			array(
				"itemID" => 20001,
				"title" => "SAIL Bhilai TMT Bars",
				"closesIn" => "2d 6h",
				"type" => "SELL",
				"quantity" => "5,000 MT",
				"location" => "Bhilai, Chhattisgarh",
				"offerType" => "E-Auction",
				"basePrice" => "₹38,500/MT",
				"timeElapsedPercent" => 78,
				"closingDate" => "Closes 18 Mar"
			),
			array(
				"itemID" => 20002,
				"title" => "Iron Ore Fines",
				"closesIn" => "4d 2h",
				"type" => "SELL",
				"quantity" => "10,000 MT",
				"location" => "Donimalai, Karnataka",
				"offerType" => "E-Auction",
				"basePrice" => "₹4,200/MT",
				"timeElapsedPercent" => 45,
				"closingDate" => "Closes 20 Mar"
			),
			array(
				"itemID" => 20003,
				"title" => "HMS Scrap",
				"closesIn" => "1d 12h",
				"type" => "BUY",
				"quantity" => "2,500 MT",
				"location" => "Mumbai, Maharashtra",
				"offerType" => "E-Auction",
				"basePrice" => "₹32,000/MT",
				"timeElapsedPercent" => 85,
				"closingDate" => "Closes 17 Mar"
			),
			array(
				"itemID" => 20004,
				"title" => "Coal Supply Tender",
				"closesIn" => "5d 2h",
				"type" => "BUY",
				"quantity" => "10,000 MT",
				"location" => "Delhi, India",
				"offerType" => "Open Tender",
				"basePrice" => "₹8,200/MT",
				"timeElapsedPercent" => 25,
				"closingDate" => "Closes 20 Mar"
			)
		);

	    if($code==1001){
            if($source == 'portfolio') {
               // print_r($result);
                $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, 'recentTenders' => $recentTenders));
		} else
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	}  
	

	private function result_web(&$result){
		$result_with_viewmore = array();$vmore=array("parent"=>"","val"=>"","indexer"=>false);
		usort($result, array($this, "build_sorted"));
		foreach($result as $k=>$v){
			  $vmore["indexer"] = $vmore["val"] == $v["regionID"] ? true : false;
			   if($vmore["indexer"]){
				   $vmore["parent"] = $vmore["parent"] == "" ? count($result_with_viewmore)-1:$vmore["parent"];
				   $result_with_viewmore[$vmore["parent"]]["viewmore"][] = $v;
			   }else{
				   $vmore["parent"] = "";
				   $result_with_viewmore[] = $v;
			   }  
			      
			   $vmore["val"] = $v["regionID"];
		}
		return $result_with_viewmore;
	}
	
	private function build_sorted ($a, $b){
			if ($a["regionID"] == $b["regionID"]) {
				return 0;
			}
			return ($a["regionID"] < $b["regionID"]) ? -1 : 1;
	}
	
	public function getTendersLandingPageFilter(Request $request){
		
	}
	
	public function getTendersFilter(Request $request)
    {      
		$result = array();
		$resourceType = "app";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		//$this->appType;
		
		$currentDate = $GLOBALS['currDate'];
		$_cm_cond='';
		
		$at_place = "APP_TENDER_LISTING_FILTER";
		$forCompany = 'SM';
		$section = "Tender_app";
		if($this->appType == 'CM'){
			$_cm_cond = " AND commodityID = 401 ";
			$at_place = "APP_TENDER_LISTING_FILTER_CM";
			$forCompany = 'CM';
			$section = "Tender_app_CM";
		}
		$_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, subSubCommodityID, cityID')
            ->whereRaw(" commodityID>0 and verified = 1  $_cm_cond")
	        ->orderByRaw('TRIM(subCommodityId)')
            ->get();
		$temp = array();
		$cityIDArr = array();
        foreach($commodity_list as $commodies ){
			$temp["subCommodities"][]= $commodies['commodityID'];
			$temp["subCommodities"][]= $commodies['subCommodityID'];
			$temp["subCommodities"][]= $commodies['subSubCommodityID'];
			
			$cityIDArr[]= $commodies['cityID'];
		}
		$scIds = implode(',', $temp["subCommodities"]);
		if($scIds=='')$scIds=0;

		$commodities = $this->refData($resourceType, $itemType='commodity', $section, $place=$at_place, $otherCondition=' AND m.ID in ('.$scIds.') ', '', $forCompany);
		
		
		
		if(!empty($commodities))
			$result["commodity"] = $commodities[$at_place]['commodity'];
		
		$region_list = DB::table('tbl_state_city')
				->select('country_id' )				
				->whereIn('id', $cityIDArr )
				->get();
		
		$regionArr = array();
		foreach($region_list as $region )
            $regionArr[]= $region['country_id'] ;
			
		if(count($regionArr)>0){
			
			$parentID_cond = DB::select("SELECT parentID,grandParentID FROM `tbl_region_commodity_master` as m where itemType='region' AND m.ID in (".implode(',', array_unique($regionArr)).") ORDER BY `itemName` ASC ");	
			
			foreach($parentID_cond as $d1){
				
				if($d1['parentID']>0)
					$regionArr[] = $d1['parentID'];
				if($d1['grandParentID']>0)
					$regionArr[] = $d1['grandParentID'];
			}			
		}
		//print_r($regionArr);	
		$scIds = implode(',', array_unique($regionArr));
		if($scIds=='')
			$scIds=0;
		
		$regions = $this->refData($resourceType, $itemType='region', $section, $place=$at_place, $otherCondition=' AND m.ID in ('.$scIds.') ', '', $forCompany);

		if(!empty($regions))
			$result["region"] = $regions[$at_place]['region'];
		
		//////
		$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['others']["companyName"][$company['company_name']]= $company['company_name'] ;
		
		$result['others']["tenderType"] = array(
			"all"=>"All",
			"buy"=>"Buy",
			"sell"=>"Sell",
			"Services"=>"Services"
		);
		
		$result['others']["date"] = array(
			"d_5"=>"Expiring In 5 Days",
			"d_10"=>"Expiring In 10 Days",
			"d_15"=>"Expiring In 15 Days"
		);
		
		$result['others']["sortBy"] = array(
			"due_date"=>"Expiring Soon",
			"publish_date_Asc"=>"Publish Date Asc",
			"publish_date_Desc"=>"Publish Date Desc"
		);
		
		$result['others']["offerType"] = array(
			"eoi"=>"EOI",
			"tender"=>"Tender",
			"auction"=>"Auction"
		);
		
		$result['others']["status"] = array(
			"live"=>"Live",
			"expired"=>"Expired"
		);
		
		$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'));

		$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
			}
		}	
		
		$result = \apiQuery::getTendersCount($resourceType, $filters);		
		$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'));
		
		$code = 1001;
		$message = "Success";
		$result = \ApiQuery::getTendersCollectionRows($this->appType);
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	  //added to get market wise data - for app (24-july-24)
    public function getTendersCollectionBM(Request $request)
    {      
		$result = array();
		///$source = $request->input('source');
		//include_once "/home/steelmin/public_html/api/storage/v2019/tenders_collection_list.php";
		$resourceType = "APP";	
		$filters=array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if ($request->has('selected_market'))
			$filters['selected_market'] = strtolower($request->input('selected_market'));
		$code = 1001;
		$message = "Success";
		$result = \ApiQuery::getTendersCollectionRowsBM($this->appType,$filters);
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}

	public function getTenderDetails(Request $request)
    {
		$resourceType = "app";
		$memid = 0;
		$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,$this->appType);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($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")));
            }
		    
		    
//			$memid = $request->input('memid');
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		//print_r($filters);
		$accessType = 'pre';
		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';
			}
			*/
			$accessType = 'post';
			$resultDetails = \ApiQuery::getTendersRows($memid, $source='', $resourceType, $type='', $filters, $accessType, 1, $offset=0, $this->appType);
			
			if(count($resultDetails)>0 && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
			
		}else{
			///not loggedin/visitor///
			
			$resultDetails = \ApiQuery::getTendersRows($memid, $source='', $resourceType, $type='', $filters, $accessType, 1, $offset=0, $this->appType);
			//$itemID
			if(count($resultDetails)>0 && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
		}
		//echo "<pre>";
	//	print_r($result);
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result)); 
	   
    }
	
}
