<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;

use Validator;

class TenderModuleController extends Controller
{
	private $debug = false;
	private $user_id = 0;
	private $user_access_level = 1;
	private $user_access_token = null;
	private $limit = 10;
	private $categories = [];
	private $validFileExtentions = ['jpg', 'jpeg','png', 'doc', 'xls', 'xlsx','pdf'];

	public function __construct(Request $request)
	{
		include('/home/steelmin/public_html/inc/config1.php');
		include('/home/steelmin/public_html/tender_function.php');

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

		$this->user_id = $request->get('user_id');
		$this->user_access_level = $request->get('user_access_level');
		$this->user_access_token = $request->get('user_access_token');

		$this->categories = $tenderDefaultCategories;
	}

	public function getCategories()
	{
		$categories = [];

		if($this->categories) {
			foreach($this->categories as $key => $category) {
				if(isset($category['show_in']) && in_array('tenders', $category['show_in'])) {
					$categories[] = [
						'key'	=>	$key,
						'name'	=>	$category['name'],
						'sub_cat' => $category['sub_categories']
					];
				}
			}
		}

		return response()->json($categories, 200);
	}

	public function getHomeTenders()
	{
		$tenders = [];
		$limit = 4;

		$filter = [];
		$filter['start'] = 0;
		$filter['limit'] = $limit;
		$filter['member_id'] = $this->user_id;
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		$tenders['latest'] = getTendersV2($filter);

		$filter['due_date'] = date('Y-m-d', strtotime(REALTIME . ' +3 days'));
		$tenders['expiring'] = getTendersV2($filter);

		if($this->user_id) {
			unset($filter['due_date']);
			$tenders['related'] = getTendersV2($filter);

			$filter['tender_member_id'] = $this->user_id;
			//print_r ($filter); dd();
			$tenders['user_tenders'] = getTendersV2($filter);
		}

		return response()->json($tenders, 200);
	}

	public function getTenders(Request $request)
	{
		$page = 1;
		if($request->has('page')) {
			$page = $request->input('page');
		}

		$filter = [];
		$filter['start'] = ($page - 1) * $this->limit;
		$filter['limit'] = $this->limit;
		$filter['member_id'] = $this->user_id;
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		if($request->has('category')) {
			$filter['product'] = $request->input('category');
		}

		if($request->has('sub_category')) {
			$filter['sub_product'] = $request->input('sub_category');
		}

		$tenders = getTendersV2($filter);

		return response()->json($tenders, 200);
	}

	public function getRelatedTenders(Request $request)
	{
		$page = 1;
		if($request->has('page')) {
			$page = $request->input('page');
		}

		$filter = [];
		$filter['start'] = ($page - 1) * $this->limit;
		$filter['limit'] = $this->limit;
		$filter['member_id'] = $this->user_id;
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		$tenders = getTendersV2($filter);

		return response()->json($tenders, 200);
	}

	public function getExpiringTenders(Request $request, $days = 3)
	{
		$tenders = [];

		$page = 1;
		if($request->has('page')) {
			$page = $request->input('page');
		}

		$filter = [];
		$filter['start'] = ($page - 1) * $this->limit;
		$filter['limit'] = $this->limit;
		$filter['member_id'] = $this->user_id;
		$filter['due_date'] = date('Y-m-d', strtotime(REALTIME . ' +' . $days . ' days'));
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		$tenders = getTendersV2($filter);

		return response()->json($tenders, 200);
	}

	public function getUserTenders(Request $request)
	{
		$page = 1;
		if($request->has('page')) {
			$page = $request->input('page');
		}

		$filter = [];
		$filter['start'] = ($page - 1) * $this->limit;
		$filter['limit'] = $this->limit;
		$filter['member_id'] = $this->user_id;
		$filter['tender_member_id'] = $this->user_id;
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		$tenders = getTendersV2($filter);

		return response()->json($tenders, 200);
	}

	public function getTenderById(Request $request, $id = 0)
	{
		$filter = [];
		$filter['id'] = $id;
		$filter['member_id'] = $this->user_id;
		$filter['debug'] = $this->debug;
		$filter['source'] = 'APP';

		$tenders = getTendersV2($filter);

		return response()->json($tenders, 200);
	}

	public function storeTender(Request $request)
	{
		
		/* $rules = [
			'type'				=>	'required',
			'description'		=>	'required',
			'category'			=>	'required',
			'quantity'			=>	'required',
			'quantity_unit'		=>	'required',
			'grade'				=>	'required',
			'company_name'				=>	'required',
			'title'				=>	'required',
			'location'			=>	'required',
			'base_price'		=>	'required',
			'due_date'			=>	'required',
			'document'			=>	'required|max:2000|mimes:pdf',
			'contact.name'		=>	'required',
			'contact.email'		=>	'required',
			'contact.phone'		=>	'required|regex:/[0-9]{10}/',
			'contact.location'	=>	'required',
			'contact.designation'	=>	'required',
			'opening_date'		=>	'required',
			'contact.isd_code'	=>	'required',
			'region'			=>	'required',
			'offer_type'		=>	'required'
		];

		$validator = Validator::make($request->all(), $rules);

		if($validator->fails()) {
			return response()->json(['errors' => $validator->errors()], 400);
		} */

		 $data = $request->all();
		if($data['category']) {
			$category = $this->getCategoryFromSubCategory($data['category']);
			$data['sub_category'] = $data['category'];
			$data['category'] = $category;
		}

		$data['pdf_path'] = '';
		$data['member_id'] = $this->user_id;
		if($request->has('document')) {
			// Upload document and assign the name of uploaded file to $data['pdf_path']
		}
/* echo "1";
		print_r ($request->all());
dd(); */
		$result = storeTender($data);

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

	public function updateTender(Request $request, $id = 0)
	{
		if(!$id) {
			return response()->json(['error' => 'Tender Id Missing!'], 400);
		}

		$rules = [
			'type'				=>	'required',
			'description'		=>	'required',
			'category'			=>	'required',
			'quantity'			=>	'required',
			'quantity_unit'		=>	'required',
			'grade'				=>	'required',
			'location'			=>	'required',
			'base_price'		=>	'required',
			'due_date'			=>	'required',
			'document'			=>	'required|max:2000|mimes:pdf',
			'contact.name'		=>	'required',
			'contact.email'		=>	'required',
			'contact.phone'		=>	'required|regex:/[0-9]{10}/',
			'contact.location'	=>	'required'
		];

		$validator = Validator::make($request->all(), $rules);

		if($validator->fails()) {
			return response()->json(['errors' => $validator->errors()], 400);
		}

		$result = updateTender($id, $request->all());

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

	public function deleteTender(Request $request, $id = 0)
	{
		if(!$id) {
			return response()->json(['error' => 'Tender Id Missing!'], 400);
		}

		$result = deleteTender($id);

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

	public function getAds(Request $request)
	{
		$ads = [
			'home' => [
				'slider'	=>	[
					[
						'image'	=>	'https://peach.blender.org/wp-content/themes/bunny/graphics/header1.jpg',
						'url'	=>	'https://www.steelmint.com/tenders'
					],
					[
						'image'	=>	'https://peach.blender.org/wp-content/uploads/poster_rodents_small.jpg',
						'url'	=>	'https://www.steelmint.com/tenders'
					]
				],
				'banner'	=>	[
					[
						'image'	=>	'https://peach.blender.org/wp-content/uploads/title_anouncement.jpg',
						'url'	=>	'https://www.steelmint.com/tenders'
					]
				]
			],
			'account' => [
				'banner'	=>	[
					[
						'image'	=>	'https://peach.blender.org/wp-content/uploads/poster_rodents_small.jpg',
						'url'	=>	'https://www.steelmint.com/tenders'
					]
				]
			]
		];

		return response()->json($ads, 200);	
	}

	protected function getCategoryFromSubCategory($sub_category = '')
	{
		$category = '';
		
		if($sub_category) {
			foreach($this->categories as $key => $value) {
				if(isset($value['sub_categories']) && in_array($sub_category, $value['sub_categories'])) {
					$category = $value['name'];
					break;
				}
			}
		}

		return $category;
	}

	
/*
	START: function to upload tender images/documents
*/	
/* 	public function apiTender(Request $request, $tid)
	{
		$recored_file = '';
		if ($request->hasFile('upload_file'))
		{
			$file = $request->file('upload_file');
			
			$extension = $file->getClientOriginalExtension();
			$size = $file->getSize();
			$recored_file = $file->getFilename() . '.' . $extension;
			if (!in_array(strtolower($extension) , $this->validFileExtentions)){
				 return new JsonResponse(array(
					"status#" => "401",
					"msg#" => "Invalid file format!"
				)); 
			} else {
				if ($tid)
					$data = DB::table('tbl_tenders_duplicate')->select('pdf_path', 'imgPath', 'more_images')->where('id', '=', $tid)->first();
				
				if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'png') //any image is uploaded for tender
				{
					if ($size < 5600000)
					{
						// ///////// upload image 1st ///////////////
						if ($data['imgPath'] == '')//first image uploaded for this tender id
						{
							if ($recored_file)
							{
								uploadFileToFolder("/home/steelmin/public_html/images/tenders/large/", $recored_file);
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['imgPath' => $recored_file]);
								return new JsonResponse(array("success#" => "1",
							        "data#" => array("url"=> "https://www.steelmint.com/images/tenders/large/".$recored_file))); 
							}
						} else {//image uploaded after first image for this tender id
							uploadFileToFolder("/home/steelmin/public_html/images/tenders/more_images/", $recored_file);
							$recored_file = "images/tenders/more_images/" . $file->getFilename() . '.' . $extension;
							if ($recored_file)
							{
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['more_images' => '1']);
								DB::table('images')->insert(['table_id' => $tid, 'table_type' => "tbl_tenders_duplicate", 'image_url' => $recored_file]);
								
								return new JsonResponse(array("success#" => "1",
							        "data#" => array("url"=> "https://www.steelmint.com/images/tenders/more_images/".$recored_file) )); 
							}
						}
					} else {
						 return new JsonResponse(array(
							"success#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							"data#" => array()  
						)); 
					}
				}else{ //any doc is uploaded for tender
					if ($size < 8700000)
					{
						uploadFileToFolder("/home/steelmin/public_html/images/tenders/", $recored_file);
						$recored_file = $file->getFilename() . '.' . $extension;

						// /////// for pdf ////////////

						if ($recored_file)
						{
							$id = $tid;
							$updated = DB::table('tbl_tenders_duplicate')->where('id', "=", $id)->update(['pdf_path' => $recored_file]);
							return new JsonResponse(array(
										"success#" 	=> "1",
										"data#" 	=> array("url"=> "https://www.steelmint.com/images/tenders/".$recored_file) ));
						}
					} else {
						return new JsonResponse(array(
							"success#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							"data#" => array()  
						));
					}
				}
			}
		}
	}  */
	
public function apiTender(Request $request, $tid)
	{
		$recored_file = '';
		//print_r ($request -> all());
		if ($request->hasFile('file'))
		{
			$file = $request->file('file');
			
			$extension = $file->getClientOriginalExtension();
			$size = $file->getSize();
			$recored_file = $file->getFilename() . '.' . $extension;
			if (!in_array(strtolower($extension) , $this->validFileExtentions)){
				 return new JsonResponse(array(
					"status#" => "2",
					"msg#" => "Invalid file format!"
				)); 
			} else {
				if ($tid)
					$data = DB::table('tbl_tenders_duplicate')->select('pdf_path', 'imgPath', 'more_images')->where('id', '=', $tid)->first();
				
				if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'png') //any image is uploaded for tender
				{
					if ($size < 5600000)
					{
                                            //echo "<pre>";print_r($data);
						// ///////// upload image 1st ///////////////
						if (empty($data['imgPath']))//first image uploaded for this tender id
						{
							if ($recored_file)
							{
								uploadFileToFolder("/home/steelmin/public_html/images/tenders/large/", $recored_file);
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['imgPath' => $recored_file]);
								return new JsonResponse(array("status#" => "1","url"=> "https://www.steelmint.com/images/tenders/large/".$recored_file)); 
							}
						} else {//image uploaded after first image for this tender id
							uploadFileToFolder("/home/steelmin/public_html/images/tenders/more_images/", $recored_file);
							$recored_file = "images/tenders/more_images/" . $file->getFilename() . '.' . $extension;
							if ($recored_file)
							{
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['more_images' => '1']);
								DB::table('images')->insert(['table_id' => $tid, 'table_type' => "tbl_tenders_duplicate", 'image_url' => $recored_file]);
								return new JsonResponse(array("status#" => "1","url"=> "https://www.steelmint.com/images/tenders/more_images/".$recored_file)); 
							}
						}
					} else {
						 return new JsonResponse(array(
							"status#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							  
						)); 
					}
				}else{ //any doc is uploaded for tender
					if ($size < 8700000)
					{
						uploadFileToFolder("/home/steelmin/public_html/images/tenders/", $recored_file);
						$recored_file = $file->getFilename() . '.' . $extension;

						// /////// for pdf ////////////

						if ($recored_file)
						{
							$id = $tid;
							$updated = DB::table('tbl_tenders_duplicate')->where('id', "=", $id)->update(['pdf_path' => $recored_file]);
							return new JsonResponse(array("status#" 	=> "1","url"=> "https://www.steelmint.com/images/tenders/".$recored_file));
						}
					} else {
						return new JsonResponse(array(
							"status#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							  
						));
					}
				}
			}
		} else {
			return new JsonResponse(array(
							"status#" => "2",
							"message#" => "else part of bad file @!#!",
							 
						));
		}
	} 	
	
	
	/* public function apiTender(Request $request, $tid)
	{
		$recored_file = '';
		print_r($request->all());
		dd();
		//if ($request->hasFile('upload_file'))
		{
			$file = base64_decode($request->input('file'));
			
			$extension = $file->getClientOriginalExtension();
			$size = $file->getSize();
			$recored_file = $file->getFilename() . '.' . $extension;
			if (!in_array(strtolower($extension) , $this->validFileExtentions)){
				 return new JsonResponse(array(
					"status#" => "401",
					"msg#" => "Invalid file format!"
				)); 
			} else {
				if ($tid)
					$data = DB::table('tbl_tenders_duplicate')->select('pdf_path', 'imgPath', 'more_images')->where('id', '=', $tid)->first();
				
				if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'png') //any image is uploaded for tender
				{
					if ($size < 5600000)
					{
						// ///////// upload image 1st ///////////////
						if ($data['imgPath'] == '')//first image uploaded for this tender id
						{
							if ($recored_file)
							{
								uploadFileToFolder($request->input('file'), "/home/steelmin/public_html/images/tenders/large/", $recored_file);
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['imgPath' => $recored_file]);
								return new JsonResponse(array("success#" => "1",
							        "data#" => array("url"=> "https://www.steelmint.com/images/tenders/large/".$recored_file))); 
							}
						} else {//image uploaded after first image for this tender id
							uploadFileToFolder($request->input('file'), "/home/steelmin/public_html/images/tenders/more_images/", $recored_file);
							$recored_file = "images/tenders/more_images/" . $file->getFilename() . '.' . $extension;
							if ($recored_file)
							{
								$updated = DB::table('tbl_tenders_duplicate')->where('id', '=', $tid)->update(['more_images' => '1']);
								DB::table('images')->insert(['table_id' => $tid, 'table_type' => "tbl_tenders_duplicate", 'image_url' => $recored_file]);
								
								return new JsonResponse(array("success#" => "1",
							        "data#" => array("url"=> "https://www.steelmint.com/images/tenders/more_images/".$recored_file) )); 
							}
						}
					} else {
						 return new JsonResponse(array(
							"success#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							"data#" => array()  
						)); 
					}
				}else{ //any doc is uploaded for tender
					if ($size < 8700000)
					{
						uploadFileToFolder($request->input('file'), "/home/steelmin/public_html/images/tenders/", $recored_file);
						$recored_file = $file->getFilename() . '.' . $extension;

						// /////// for pdf ////////////

						if ($recored_file)
						{
							$id = $tid;
							$updated = DB::table('tbl_tenders_duplicate')->where('id', "=", $id)->update(['pdf_path' => $recored_file]);
							return new JsonResponse(array(
										"success#" 	=> "1",
										"data#" 	=> array("url"=> "https://www.steelmint.com/images/tenders/".$recored_file) ));
						}
					} else {
						return new JsonResponse(array(
							"success#" => "2",
							"message#" => $recored_file . " exceeding file size of 8 gross mbs",
							"data#" => array()  
						));
					}
				}
			}
		}
	}  */	
	/*
	END: function to upload tender images/documents
	*/	
	public function __destruct()
	{
		include('/home/steelmin/public_html/inc/desconfig.php');
	}
}
