<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;

use \App\Http\Requests;

use \App\Http\Controllers\Controller;

use DB;

use Schema;

/**
 * Controls general search functionality for the job postings
 *
 * SearchController is responsible for pulling job posting results from the
 * database. It also formats the results correctly so that they can be
 * easily displayed in the view.
 *
 * @author Adam Gleisner amg295@cornell.edu
 * @author Jeremy Miller jdm389@cornell.edu
 */
class SearchController extends Controller {

	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
	public function __construct()
	{

	}

	public function redirect() {
		return redirect()->route('index');
	}
	
	/////////////////////////////
	///                       ///
	///   Control Functions   ///
	///                       ///
	/////////////////////////////



	/**
	 * Show the default search page.
	 *
	 * @return \Illuminate\View\View The default search page
	 */
	public function show_jobsearch() {
		$terms = \App\Term::orderBy('description')->get();
		$regions = \App\Region::orderBy('description')->get();
		$fields = \App\Field::orderBy('description')->get();
		$defaultTerm = \App\Constant::where('name', 'default.add.job.term')
			->first()->value;
		$defaultRegion = \App\Constant::where('name', 'default.add.job.regional.location')
			->first()->value;
		$defaultField = \App\Constant::where('name', 'default.add.job.career.field')
			->first()->value;
		return view('jobSearch', [
			'terms' => $terms,
			'regions' => $regions,
			'fields' => $fields,
			'defaultTerm' => $defaultTerm,
			'defaultField' => $defaultField,
			'defaultRegion' => $defaultRegion
		]);
	}

	/**
	 * Receives a POST request from the search page, and uses the request data to build a SQL query.
	 * Returns the "results" view with the result of the SQL query appended.
	 *
	 * @param Request $request The HTTP Request
	 * @return \Illuminate\View\View The results page
	 */
	public function show_results(Request $request) {
		$all = $request->all();
		$results = $this->formatQuery($all);

		// Get the page size and pass it in
		$page_size = \App\Constant::where('name', 'browse.listings.pagesize')
			->first()->value;

		return view('results', ['jobs' => $results, 'page_size' => $page_size]);
	}

	/**
   * Shows the requested job posting by ID.
   *
   * @param Request $request The HTTP Request
   *
   * @return \Illuminate\View\View The single job posting view
	 */
	public function show_jobPosting(Request $request){ // Gets the job, as well as it's associated things
		$id 		= $request->get('id');
		$job 		= \App\Posting::with("employer.contact")->find($id);

//dd($job);

		$regionName = $job->region->description;
		$termName 	= $job->term->description;
		$employer 	= $job->employer;
		$contact 	= $job->employer->contact;

		// Gets info on the job's fields
		$fieldIDs = DB::table('field_posting')
							->where('posting_id', $id)
							->select('field_id')
							->get();

		$jobInfo = $this->formatJobInfo($employer, $contact, $job, $termName, $regionName, $fieldIDs);

		return view("jobDetail", ['job' => $jobInfo]);
	}
	
	///    Helper Functions  
// ===============================================================================================
	/**
	 * @param \App\Employer $employer
	 * @param \App\Contact  $contact
	 * @param \App\Posting  $job
	 * @param string        $termName
	 * @param string        $regionName
	 * @param array         $fieldIDs
	 *
	 * @return array
	 */
	public function formatJobInfo($employer, $contact, $job, $termName, $regionName, $fieldIDs)
	{
		$jobInfo = array();

	//	dd($employer); //empltype_id

		if(isset($employer)) {
			// The information about the employer
			$jobInfo["employerName"]			= $employer->name;
			$jobInfo["address1"]				= $employer->address1;
			$jobInfo["address2"]				= $employer->address2;
			$jobInfo["city"]					= $employer->city;
			$jobInfo["state"]					= $employer->state;
			$jobInfo["postal_code"]				 = $employer->postal_code;
			$jobInfo["suppress_emp_and_contact"] = $employer->suppress_emp_and_contact==1?"Yes":"No";

			$empltype_id = $employer->empltype_id;
			$empltype = DB::table('employertypes')->where('id',$empltype_id)->select('description')->get()[0];
			$empltype = $empltype->description;
			
			//dd($empltype);
			//$classificationlevel = $class->description;
			//dd($x); //empltype_id

		} else {
			$jobInfo["employerName"]		= '';
			$jobInfo["address1"]			= '';
			$jobInfo["address2"]			= '';
			$jobInfo["city"]				= '';
			$jobInfo["state"]				= '';
			$jobInfo["postal_code"]			= '';

			$jobInfo["suppress_emp_and_contact"] = '';
		}

		if(isset($contact)) { // The information about the contact
			$jobInfo["contactName"]			= $contact->name;
			$jobInfo["contactTitle"]		= $contact->title;
			$jobInfo["phone"]				= $contact->phone;
			$jobInfo["phone_ext"]			= $contact->phone_ext;
			$jobInfo["email"] 				= $contact->email;
		}
		else {
			$jobInfo["contactName"]			= '';
			$jobInfo["contactTitle"]		= '';
			$jobInfo["phone"]				= '';
			$jobInfo["phone_ext"]			= '';
			$jobInfo["email"] 			    = '';
		}

		// The information about the job itself
		$jobInfo["postingID"]						= $job->id;
		$jobInfo["term"]							= $termName;
		$jobInfo["region"]							= $regionName;
		$jobInfo["worksite"]						= $job->worksite;

		$classificationlevel_id						= $job->classificationlevel_id; // xxx

		$class = DB::table('classificationlevels')->where('id',$classificationlevel_id)->select('description')->get()[0];
		$classificationlevel = $class->description;

		$jobInfo["classificationlevel"]				= $classificationlevel;
		$jobInfo["title"]							= $job->title;
		$jobInfo["description"]						= $job->description;
		$jobInfo["special_requirements"]		 	= $job->special_requirements;
		$jobInfo["work_schedule"]					= $job->work_schedule;
		$jobInfo["weekly_hours"] 					= $job->weekly_hours;
		$jobInfo["fws_required"]					= $job->fws_required==1?"Yes":"No";
		$jobInfo["positions_available"] 		 	= $job->positions_available;
		$jobInfo["paid"]						 	= $job->paid==1?"Yes":"No";
		$jobInfo["wage"]  							= $job->wage;
		$jobInfo["supervisorname"]  				= $job->supervisorname;

		$jobInfo["empltype"]  						= $empltype;

		// The date info
		$start_year = substr($job->employment_start_date,0,4);
		$start_day  = substr($job->employment_start_date,8,2);
		$start_mon  = substr($job->employment_start_date,5,2);
		$end_year   = substr($job->employment_end_date,0,4);
		$end_day    = substr($job->employment_end_date,8,2);
		$end_mon    = substr($job->employment_end_date,5,2);
		$jobInfo["employment_start_date"] = $start_mon."/".$start_day."/".$start_year;
		$jobInfo["employment_end_date"]   = $end_mon."/".$end_day."/".$end_year;

		// The career field info for the job.
		$jobInfo["field1"] = "";
		$jobInfo["field2"] = "";
		$jobInfo["field3"] = "";

//	dd($jobInfo);


		for($i =0; $i < count($fieldIDs); $i++){
			$fieldIDs[$i] = $fieldIDs[$i]->field_id;
			$fieldText = \App\Field::find($fieldIDs[$i])->description;
			$jobInfo["field".($i+1)] = $fieldText;
		}

		return $jobInfo;
	}

	/**
	 * Formats the search query
	 *
	 * @param array $all
	 *
	 */
	public function formatQuery(array $all)
	{
		$search = \App\Posting::select(
		'postings.id as postingID',
		'title',
		'fws_required',
		'regions.description as regionName',
		'terms.description as termName'
		)
			->join('field_posting', 'postings.id', '=', 'field_posting.posting_id')
			->join('regions', 'regions.id', '=', 'postings.region_id')
			->join('terms', 'terms.id', '=', 'postings.term_id')
			->where('approved', '1')
			->where('expiration_date', '>=', date('Y-m-d'))
			->where('activation_date', '<=', date('Y-m-d'));

		if(!empty($all["term"]) && $all["term"] != "any") {
			// Want to be able to see the term requested.
			$search = $search->where('terms.id', $all["term"]);
		}
		if(!empty($all["region"]) && $all["region"] != "any") {
			// Want to be able to see the region requested.
			$search = $search->where('regions.id', $all["region"]);
		}
		if(!empty($all["field"]) && $all["field"] != "any") {
			// Want to be able to see the field requested.
			$search = $search->where('field_posting.field_id', $all["field"]);
		}
		if(!empty($all["extra"])) {
			$extra = $all["extra"];
			$text = $all["criteria"];
			$search = $this->formatExtra($search, $text, $extra);
		}

		$search = $search->groupBy("postings.id");
		$results = $search->get();
		return $results;
	}


	/**
	 * Formats the textual search of the query
	 * @param        $search The search query
	 * @param string $text
	 * @param int    $extra
	 */
	public function formatExtra($search, $text, $extra)
	{

		if($text != "") {
			switch($extra) {
				case 1:
					$search = $search->where('postings.title', 'like', "%$text%");
					break;
				case 2:
					$search = $search->where('postings.description', 'like', "%$text%");
					break;
				case 3:
					$search = $search->where('wage', 'like', "%$text%");
					break;
				case 4:
					$search = $search->where('postings.id', 'like', "%$text%");
					break;
			}
		}
		return $search;
	}
}
