<?php
namespace App\Http\Controllers;
use App\Affiliates;
use App\Branch;
use App\CallBackRequest;
use App\Components\CommonComponent;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeblineController;
use App\Information;
use App\Product;
use App\QuotePdf;
use App\Quotes;
use App\UnderwritingQuestions;
use App\UserInfo;
use Auth;
use Carbon\Carbon;
use Config;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Input;
use Mail;
use PDF;
use Response;
use Session;
use Cache;
use App\Http\Controllers\HelperController;

class GetQuoteController extends Controller {
	public function __construct() {
		$this->helper = new HelperController();
		// This is for profile pic
		$user_info = '';
		if (Auth::check()) {
			$user_info = DB::table('users')
				->where('users.id', Auth::user()->id)
				->join('user_info', 'user_info.user_id', '=', 'users.id')
				->select('user_info.*')
				->first();
		}
		return $user_info;

	}

	public function getQuote(Request $request) {

		try
		{
			//$id = Auth::user()->id;
			if ($request->isMethod('post')) {


				$post_data = $request->all();
				//print_r($post_data);
				//  exit;

				// Remove all white spaces before validating data

				array_map('trim', $request->all());

				// validate the form data -- start
				$insurance_startdate = sprintf("%s/%s/%s", $request->input('insurance_yy'), $request->input('insurance_mm'), $request->input('insurance_dd'));

				$rules = array(
					'title' => 'required',
					'first_name' => 'required|min:3|max:30',
					'last_name' => 'required|max:30',
					'day' => 'required',
					'month' => 'required',
					'year' => 'required',
					'residential_status' => 'required',
					//  'insurance_start_date_hidden'      => 'required|date',
					// 'loan_repayment' => 'required'
				);
				if (isset($post_data['residential_status']) && $post_data['residential_status'] == 'tenant') {
					$rules['monthly_rent'] = 'required|numeric';
				}

				if (isset($post_data['residential_status']) && $post_data['residential_status'] == 'owner') {
					$rules['mortgage_type'] = 'required';
				}

				if (isset($post_data['mortgage_type']) && $post_data['mortgage_type'] == '1') {
					$rules['mm_repay_1'] = 'required|numeric';
					$rules['mortgage_duration_year'] = 'required';
					$rules['mortgage_duration_month'] = 'required';
				}

				if (isset($post_data['mortgage_type']) && $post_data['mortgage_type'] == '2') {
					$rules['mm_repay_2'] = 'required|numeric';
				}

				// if(isset($post_data['loan_repayment']) && $post_data['loan_repayment'] == '1')
				// {
				//     $rules['taken_loan'] = 'required';
				// }

				if (isset($post_data['taken_loan']) && $post_data['taken_loan'] == '1') {
					$rules['monthly_loan_repay'] = 'required|numeric';
					$rules['loan_duration_year'] = 'required';
					$rules['loan_duration_month'] = 'required';
				}

				if (isset($post_data['taken_loan']) && $post_data['taken_loan'] == '0') {
					$rules['monthly_loan_repay'] = 'required|numeric';
				}

				$rules['monthly_gross_income'] = 'required|numeric';
				$rules['monthly_benifit_amount'] = 'required|numeric|max:2500';
				$rules['industry_type'] = 'required|exists:industries,industry_name';
				$rules['occupation_type'] = 'required|exists:occupations,occupation_name';

				$rules['cover_type'] = 'required';
				$rules['excessperiod'] = 'required';


				$messages = [
					// 'policy_start_date.after' => 'Insurance Start Date should not be in past or more than 30 days in the future',
				  //   'policy_start_date.before' => 'Insurance Start Date should not be in past or more than 30 days in the future',
					 //Additional custom error messages
				 ];


				$validator = Validator::make($post_data, $rules);

				if ($validator->fails()) {
					return redirect()
						->back()
						->withErrors($validator)
						->withInput();
				}

				// validate the form data -- end
				// echo "<pre>";
				// print_r($post_data);
				// exit;

				// validate the form data -- end
				// echo '<pre>';
				// print_R(Auth::user()->role);
				// echo '</pre>';
				// exit;
				if (Auth::check() && Auth::user()->role == 2) {
					//Default Affiliate uid
					$uid = Config::get('constant.BI_UID');
				} elseif (Auth::check()) {
					if (Auth::user()->role == 6) {
						$uid = Auth::user()->branch->branch_affliate_admin_uid;
					} else {
						$affiliate_data = DB::table('users')
						// ->join('affiliate_users','affiliate_users.user_id','=','users.id')
							->join('affiliates', 'affiliates.uid', '=', 'users.uid')
							->where('users.id', '=', Auth::user()->id)
							->select('affiliates.uid')
							->first();
						$uid = $affiliate_data->uid;
					}

				} else {
					//Default Affiliate uid
					$uid = Config::get('constant.BI_UID');
				}

				$insurance_startdate = sprintf("%s/%s/%s", $request->input('insurance_yy'), $request->input('insurance_mm'), $request->input('insurance_dd'));

				$oneyearfromins_startdate = date('Y-m-d', strtotime($insurance_startdate . "+1 year"));
				$insurance_enddate = date('Y-m-d', strtotime($oneyearfromins_startdate . "-1 day"));

				$dob = $request->input('year') . '-' . $request->input('month') . '-' . $request->input('day');

				$start_date = $request->input('insurance_yy') . '-' . $request->input('insurance_mm') . '-' . $request->input('insurance_dd');

				$age = date_diff(date_create($dob), date_create($start_date))->y;

				//echo $age;

				$residential_status = $request->input('residential_status');

				$mortgage_type = $monthly_mortgage_repay = $monthly_loan_repay = "";
				$mortgage_duration_month = $mortgage_duration_year = 0;
				$monthly_gross_income = $monthly_benifit_amount = 0;
				$industry_type_id = $occupation_type_id = 0;
				$loan_duration_year = $loan_duration_month = $monthly_rent = 0;
				$cover_type = "";
				$excessperiod = 0;
				$taken_loan = '';

				if ($residential_status == 'owner') {
					// Home Owner
					$mortgage_type = $request->input('mortgage_type');
					if ($mortgage_type == 1) {
						//New Mortgage
						$monthly_mortgage_repay = $request->input('mm_repay_1');
						if ($request->input('mortgage_duration_month') != "") {
							$mortgage_duration_month = $request->input('mortgage_duration_month');
						}

						if ($request->input('mortgage_duration_year') != "") {
							$mortgage_duration_year = $request->input('mortgage_duration_year');
						}

					}
					if ($mortgage_type == 2) {
						//Existing Mortgage
						$monthly_mortgage_repay = $request->input('mm_repay_2');
					}
				} else if ($residential_status == 'tenant') {
					$monthly_rent = $request->input('monthly_rent');
				}

				// $loan_repayment = $request->input('loan_repayment');

				// if($loan_repayment == 1)
				// {
				//     $taken_loan = $request->input('taken_loan');
				//     $monthly_loan_repay = $request->input('monthly_loan_repay');
				//     if($taken_loan == 1)
				//     {
				//         if($request->input('loan_duration_year') != "")
				//             $loan_duration_year = $request->input('loan_duration_year');
				//         if($request->input('loan_duration_month') != "")
				//             $loan_duration_month = $request->input('loan_duration_month');
				//     }
				// }

				$monthly_gross_income = $request->input('monthly_gross_income') / 12;
				$benifit_amount = $monthly_benifit_amount = $request->input('monthly_benifit_amount');
				$industry_type_id = $request->input('industry_type_id');
				$occupation_type_id = $request->input('occupation_type_id');
				$cover_type = $request->input('cover_type');
				$excess_period = $excessperiod = trim($request->input('excessperiod'));
				// For AS products
				if ($excess_period == 28) {
					$excess_period = 30;
				} elseif ($excess_period == 56) {
					$excess_period = 60;
				} else {
					$excess_period = $request->input('excessperiod');
				}
			//	 dd($request->input());
				// echo '<pre>';
				// print_r($request->input());
				// echo '</pre>';

				if ($industry_type_id == "") {
					$industry_type_id = CommonComponent::getIndustryDetails($request->input('industry_type'));
				}

				if ($occupation_type_id == "") {
					$occupation_type_id = CommonComponent::getOccupationDetails($request->input('occupation_type'));
				}

				$quote_data = new quotes;
				$quote_data->affiliate_uid = $uid;
				$quote_data->dob = $dob;
				$quote_data->age = $age;
				$quote_data->residential_status = $residential_status;
				$quote_data->mortgage_type = $mortgage_type;
				$quote_data->monthly_mortgage_repay = $monthly_mortgage_repay;
				$quote_data->mortgage_duration_month = $mortgage_duration_month;
				$quote_data->mortgage_duration_year = $mortgage_duration_year;
				$quote_data->monthly_rent = $monthly_rent;

				// $quote_data->loan_repayment = $loan_repayment;
				// $quote_data->taken_loan = $taken_loan;
				$quote_data->monthly_loan_repay = $monthly_loan_repay;
				$quote_data->monthly_gross_income = $monthly_gross_income;
				$quote_data->monthly_benifit_amount = $monthly_benifit_amount;
				$quote_data->industry_type_id = $industry_type_id;
				$quote_data->occupation_id = $occupation_type_id;
				$quote_data->cover_type = $cover_type;

				$quote_data->age_or_term = $request->input('age_or_term');
				$quote_data->cease_cover = $request->input('cease_cover');
				$quote_data->term_in_year = $request->input('term_in_year');

				$quote_data->excess_period = $excess_period;
				$quote_data->loan_duration_month = $loan_duration_month;
				$quote_data->loan_duration_year = $loan_duration_year;

				$quote_data->save();

				$inserted_id = $quote_data->id;

				//echo $inserted_id;
				//   exit;
				if ($inserted_id) {
					$quote_details = CommonComponent::getQuoteDetails($inserted_id);

					$monthlycover = $quote_details['monthly_benifit_amount'];
					$monthlybenefit = $monthlycover;

					$affiliated_uid = $quote_details['affiliate_uid'];
					if ($affiliated_uid != '') {
						$affiliation_data = Affiliates::where('uid', $affiliated_uid)->first();
						$lead_source_field = $affiliation_data->name;
					} else {
						$lead_source_field = 'Web Site';
					}

					$personal_dob = sprintf("%s", CommonComponent::actualDateFormat($dob));
					if (Auth::check()) {
						$user_id = Auth::user()->id;
					} else {
						$user_id = 0;
					}



					$personal_data = new Information;
					if ($user_id != 0) {
						$personal_data->created_id_by = $user_id;
					}

					$monthlycover = $quote_details['monthly_benifit_amount'];
					$monthlybenefit = $monthlycover;

					$personal_data->quote_id = $inserted_id;
					$personal_data->title = $request->input('title');
					$personal_data->gender = $request->input('sex');
					$personal_data->smoker = $request->input('smoker');
					$personal_data->increasing_benefit = $request->input('txtIncreasingBenefit');

					$fname_convert = str_replace("'", "’", $request->input('first_name'));
					$fname_convert = trim($fname_convert);
					$fname_convert = preg_replace("/[[:blank:]]+/", " ", $fname_convert);
					$lname_convert = str_replace("'", "’", $request->input('last_name'));
					$lname_convert = trim($lname_convert);
					$lname_convert = preg_replace("/[[:blank:]]+/", " ", $lname_convert);
					$personal_data->fname = $fname_convert;
					$personal_data->lname = $lname_convert;
					$personal_data->full_name = $fname_convert . " " . $lname_convert;

					$personal_data->dob = $personal_dob;

					$occupation_name=CommonComponent::getOccupationDetailsById($quote_details['occupation_id']);

					$personal_data->occupation = $occupation_name;
					$personal_data->salary = $monthly_gross_income;

					$personal_data->insurance_startdate = $insurance_startdate;
					$personal_data->insurance_enddate = $insurance_enddate;
					$personal_data->typeofcover = $quote_details['cover_type'];
					$personal_data->age = $quote_details['age'];

					//new fields from the personal details page to get quote - AIB-1 Change request

					$personal_data->premiseName = $request->input('premise');
					$personal_data->address1 = $request->input('line1');
					$personal_data->address2 = $request->input('line2');
					$personal_data->address3 = $request->input('line3');
					$personal_data->address4 = $request->input('line4');
					$personal_data->postcode = strtoupper($request->input('postcode'));
					$personal_data->formattedPO = $request->input('formattedPO');
					$personal_data->postaltown = $request->input('town');
					$personal_data->county = ($request->input('county') != '' ? $request->input('county') : '');
					$personal_data->email = $request->input('email');
					$personal_data->telephone = $request->input('telephone');
					$personal_data->transfer = ($request->input('transfer') != '' ? $request->input('transfer') : '');
					$personal_data->current_provider = ($request->input('current_provider') != '' ? $request->input('current_provider') : '');
					$personal_data->current_policy_date = ($request->input('current_policy_date') != '' ? $request->input('current_policy_date') : '');
					$personal_data->is_webline_product = 'No';
					$personal_data->emp_status = $request->input('emp_status');
					$personal_data->employer_name = $request->input('employer_name');
				//	$personal_data->monthlybenefit = $request->input('telephone');


					$personal_data->affid = $affiliated_uid;

					$personal_data->ip = $_SERVER['REMOTE_ADDR'];
					$personal_data->date_added = date("Y-m-d");
					$personal_data->time_added = date("H:i:s");

					$personal_data->excessperiod = $excess_period;
					$personal_data->monthlybenefit = $monthlybenefit;
					$personal_data->lead_source_field = $lead_source_field;

					$personal_data->insurer = Config::get('constant.INSURER');

					$personal_data->insurance_enddate = $insurance_enddate;
					$personal_data->status = "-1";

					$saved = $personal_data->save();
					if (!$saved) {
						Session::flash('failure', 'There was a problem. Please try again later.');
						return back()->withInput();
					}

					/*// Pass the data into webline api
					$monthly_gross_income = (int) $request->input('monthly_gross_income');
					$annual_earnings = $monthly_gross_income * 12;
					// $annual_earnings = $monthly_gross_income;
					$monthly_benifit_ammount = (int) $request->input('monthly_benifit_amount');

					
						                           
					
					switch ($excess_period) {
					case 1:
						$DefermentOpts = 2048;
						break;
					case 7:
						$DefermentOpts = 4096;
						break;
					case 28:
					case 30:
						$DefermentOpts = 1;
						break;
					case 56:
					case 60:
						$DefermentOpts = 2;
						break;
					case 91:
						$DefermentOpts = 4;
						break;
					case 182:
						$DefermentOpts = 8;
						break;
					case 364:
						$DefermentOpts = 16;
						break;
					case 392:
						$DefermentOpts = 32;
						break;
					case 728:
						$DefermentOpts = 64;
						break;
					case 784:
						$DefermentOpts = 128;
						break;
					default:
						$DefermentOpts = 1;
					}
					$request->input('sex');
					//dd($request->input());
					$ceaseAge = $request->input('cease_cover');
					$txtTermYears = $request->input('term_in_year');
					if ($ceaseAge != '') {
						$txtTermYears = -1;
					} else if ($txtTermYears != '') {
						$ceaseAge = -1;
					}
					echo $DefermentOpts;
					$webline_post_data = array(
						"sex" => $request->input('sex'),
						"dob" => $dob,
						"smoker" => $request->input('smoker'),
						"title" => $request->input('title'),
						"forename" => $request->input('first_name'),
						"surname" => $request->input('last_name'),
						"earnings" => $annual_earnings,
						"term" => $request->input('term_in_year'),
						"ceaseage" => $request->input('cease_cover'),
						"frequency" => 'Monthly',
						"benefit" => $monthly_benifit_ammount,
						"quot_id" => $inserted_id,
						"deferment_options" => $DefermentOpts,
					);*/
					// If cover type equals Accidence and Sickness to then only call the webline api
					if ($cover_type == 'AS') {

						//print_r($webline_post_data);

						// check the webline products or not based on Affiliate id
					//	$status_check = CommonComponent::checkWeblineBasedonAffiliate($uid);

						// echo "status check".$status_check;

						// exit;

						//if ($status_check != 0) {
							// CommonComponent::DoQuote($webline_post_data);
						//	$webline_service = new WeblineController();
						//	$webline_service->getProducts($webline_post_data);
						//}
					}
					// echo '<pre>';
					// print_r($webline_post_data);
					// echo '</pre>';
					// exit;

					return redirect('product-list/' . encryptUrl($inserted_id));
				} else {
					Session::flash('failure', 'There was a problem. Please try again later.');
					return back();
				}
			} // $request->isMethod('post') -- end
			else {
				$months = array("01" => "Jan", "02" => "Feb", "03" => "Mar", "04" => "Apr", "05" => "May", "06" => "Jun", "07" => "Jul", "08" => "Aug", "09" => "Sep", "10" => "Oct", "11" => "Nov", "12" => "Dec",
				);
				$days = array("01" => "01", "02" => "02", "03" => "03", "04" => "04", "05" => "05", "06" => "06", "07" => "07", "08" => "08", "09" => "09", "10" => "10", "11" => "11", "12" => "12", "13" => "13", "14" => "14", "15" => "15", "16" => "16", "17" => "17", "18" => "18", "19" => "19", "20" => "20", "21" => "21", "22" => "22", "23" => "23", "24" => "24", "25" => "25", "26" => "26", "27" => "27", "28" => "28", "29" => "29", "30" => "30", "31" => "31",
				);

				$user_info = $this->__construct();
				return view('frontend.get_a_quote', [
					'months' => $months,
					'days' => $days,
					'user_info' => $user_info,
					"current_year" => date("Y"),
					"current_month" => date("m"),
					"current_date" => date("d"),

				]);
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Load the Mortagage partial
	public function mortgageTypes(Request $request) {
		try
		{
			if ($request->ajax()) {
				$view = view('slices.frontend.get-a-quot.mortgage_type');
				//$view=$view->render();
				//$responseData->responseSuccess($view);
				return $view;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Load the New Mortagage partial
	public function ajaxNewMortgage(Request $request) {
		try
		{
			if ($request->ajax()) {
				$view = view('slices.frontend.get-a-quot.new_mortgage');
				//$view=$view->render();
				//$responseData->responseSuccess($view);
				return $view;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Load the Existing Mortagage partial
	public function ajaxExistingMortgage(Request $request) {
		try
		{
			if ($request->ajax()) {
				$view = view('slices.frontend.get-a-quot.existing_mortgage');
				return $view;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Load the Existing Mortagage partial
	public function ajaxTenant(Request $request) {
		try
		{
			if ($request->ajax()) {
				$view = view('slices.frontend.get-a-quot.tenant');
				return $view;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Load the Load Reppayment partial
	public function ajaxLoadRepayment(Request $request) {
		try
		{
			if ($request->ajax()) {
				$view = view('slices.frontend.get-a-quot.load_repayment_yes');
				return $view;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Have you taken loan in the last 60 days -- label
	public function ajaxTakenLoan60days(Request $request) {
		try
		{
			if ($request->ajax()) {
				$val = (int) $request->val;
				if ($val == 1) {
					$view = view('slices.frontend.get-a-quot.load_takenload60days_yes');
					return $view;
				} else {
					$view = view('slices.frontend.get-a-quot.load_takenload60days_no');
					return $view;
				}
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Autocomplete industry types
	public function ajaxSearchIndustryType(Request $request) {
		$query = $request->get('term', '');
		$industries = DB::table('industries')
			->where('industry_name', 'LIKE', '%' . $query . '%')
			->where('is_active', '1')
			->get();

		$data = array();
		foreach ($industries as $industry) {
			$data[] = array('value' => $industry->industry_name, 'id' => $industry->id);
		}
		if (count($data)) {
			return $data;
		} else {
			return ['value' => 'No Result Found', 'id' => ''];
		}

	}

	// Autocomplete occupation types
	public function ajaxSearchOccupationType(Request $request) {
		$query = $request->get('term', '');
		$occupations = DB::table('occupations')
			->where('occupation_name', 'LIKE', '%' . $query . '%')
			->where('is_active', '1')
			->get();
		$data = array();
		foreach ($occupations as $occupation) {
			$data[] = array('value' => $occupation->occupation_name, 'id' => $occupation->id);
		}
		if (count($data)) {
			return $data;
		} else {
			return ['value' => 'No Result Found', 'id' => ''];
		}

	}

	// product list
	public function productList(Request $request) {
		try
		{
			//Cache::flush();

			$quote_id = decryptUrl($request->id);
			// $quote_id=decryptUrl($quote_id);

			if (isset($quote_id) && $quote_id != "") {
				//Fetch Quote Details
				$quote_dtls = array();
				$quote_dtls = CommonComponent::getQuoteInfo($quote_id);

				if (count($quote_dtls) > 0) {
					$quote_id = decryptUrl($request->id);
					//Quote Details
					$benifit_amount = $quote_dtls['monthly_benifit_amount']; // R5
					$cover_type = $quote_dtls['cover_type'];

					$excess_period = $quote_dtls['excess_period'];

					$grid_number = 1;
					$age = date_diff(date_create($quote_dtls['dob']), date_create('today'))->y;
					$term_in_year = (int) $quote_dtls['term_in_year'] + $quote_dtls['age'];

					
					/* For webline products Cease or term ages between 65 to 70 then doesn't show normal products, below 65 only should show our products. */
					if ($cover_type == 'AS') {


						$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);

						//echo "in this";
			       // exit;


						// disabled the code as we disabled the webline and other options

					/*	if (!empty($quote_dtls['cease_cover']) && $quote_dtls['cease_cover'] > 65) {
							$products_list = CommonComponent::getSheperdsProductsByRules($quote_id, array(), $grid_number);
						} elseif (!empty($quote_dtls['cease_cover']) && $quote_dtls['cease_cover'] <= 65) {

							$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);

						} elseif (!empty($quote_dtls['term_in_year']) && $term_in_year > 65) {

							$products_list = CommonComponent::getSheperdsProductsByRules($quote_id, array(), $grid_number);
						} elseif (!empty($quote_dtls['term_in_year']) && $term_in_year <= 65) {

							$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);
						} else {
							$products_list = '';
						}*/

					} else {
						$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);
					}

				//dd($products_list);
				//	$products_list_webline = CommonComponent::getProductsWebline($quote_id, true);

					$information_data = Information::where('quote_id', '=', $quote_id)->first();

					if (isset($products_list) && $products_list != '' && $information_data->benefit_period != 0) {
						$res_count = count($products_list);
						for ($i = 0; $i < $res_count; $i++) {
							if ($products_list[$i]['product_benifit_period'] != $information_data->benefit_period) {
								unset($products_list[$i]);
							}

						}
						$products_list = array_values($products_list);
					}
					// echo $quote_id;
					// echo "<pre>";
					// print_r($products_list_webline);
					// echo '</pre>';
					// die;
					$user_info = $this->__construct();

					return view('frontend.product_list', [
						'quote_id' => $quote_id,
						'cover_type' => $quote_dtls['cover_type'],
						'excess_period' => $quote_dtls['excess_period'],
						'benifit_period' => $information_data->benefit_period,
						'benifit_amount' => $quote_dtls['monthly_benifit_amount'],
						'ajax_call_from' => 'add_quote',
						'products_list' => $products_list,
					//	'products_list_webline' => $products_list_webline,
						'user_info' => $user_info,
					]);
				} else {
					Session::flash('failure', 'Invalid quote');
					return redirect('get-a-quote');
					exit;
				}
			} else {
				Session::flash('failure', 'Invalid quote');
				return redirect('get-a-quote');
				exit;
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// call back form data insertion
	public function callBack(Request $request) {
		try
		{
			$post_data = $request->all();

			// Remove all white spaces before validating data

			array_map('trim', $request->all());

			$callback_data = new CallBackRequest;
			$callback_data->phone = $request->phone;
			$callback_data->title = $request->title;
			$callback_data->fname = $request->fname;
			$callback_data->sname = $request->sname;
			$callback_data->calltime = $request->calltime;
			$callback_data->date_added = date("Y-m-d");
			$callback_data->time_added = date("H:i:s");

			$callback_data->save();

			$inserted_id = $callback_data->id;
			echo $inserted_id;
			exit;

		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Edit get a quote form
	public function getQuoteEdit(Request $request) {
		try
		{
			//$id = Auth::user()->id;
			if ($request->isMethod('post')) {

				//$key="webline" . $request->input('qid');
               Session::forget("webline" . $request->input('qid'));

				$request->input('qid');
				$post_data = $request->all();

				// Remove all white spaces before validating data

				array_map('trim', $request->all());

				// validate the form data -- start

				$rules = array(
					'title' => 'required',
					'first_name' => 'required|min:3|max:30|alpha',
					'last_name' => 'required|max:30',
					'day' => 'required',
					'month' => 'required',
					'year' => 'required',
					'residential_status' => 'required',
					// 'loan_repayment' => 'required'
				);
				if (isset($post_data['residential_status']) && $post_data['residential_status'] == 'tenant') {
					$rules['monthly_rent'] = 'required|numeric';
				}

				if (isset($post_data['residential_status']) && $post_data['residential_status'] == 'owner') {
					$rules['mortgage_type'] = 'required';
				}

				if (isset($post_data['mortgage_type']) && $post_data['mortgage_type'] == '1') {
					$rules['mm_repay_1'] = 'required|numeric';
					$rules['mortgage_duration_year'] = 'required';
					$rules['mortgage_duration_month'] = 'required';
				}

				if (isset($post_data['mortgage_type']) && $post_data['mortgage_type'] == '2') {
					$rules['mm_repay_2'] = 'required|numeric';
				}

				/*if(isset($post_data['loan_repayment']) && $post_data['loan_repayment'] == '1')
					                    {
					                        $rules['taken_loan'] = 'required';
				*/

				if (isset($post_data['taken_loan']) && $post_data['taken_loan'] == '1') {
					$rules['monthly_loan_repay'] = 'required|numeric';
					$rules['loan_duration_year'] = 'required';
					$rules['loan_duration_month'] = 'required';
				}

				if (isset($post_data['taken_loan']) && $post_data['taken_loan'] == '0') {
					$rules['monthly_loan_repay'] = 'required|numeric';
				}

				$rules['monthly_gross_income'] = 'required|numeric';
				$rules['monthly_benifit_amount'] = 'required|numeric';
				$rules['industry_type'] = 'required|exists:industries,industry_name';
				$rules['occupation_type'] = 'required|exists:occupations,occupation_name';

				$rules['cover_type'] = 'required';
				$rules['excessperiod'] = 'required';

				$validator = Validator::make($post_data, $rules);

				if ($validator->fails()) {
					return redirect()
						->back()
						->withErrors($validator)
						->withInput();
				}
				// echo "<pre>";
				// print_r($_POST);
				// exit;

				// validate the form data -- end

				// validate the form data -- end

				if (Auth::check()) {
					$affiliate_data = DB::table('users')
						->join('affiliate_users', 'affiliate_users.user_id', '=', 'users.id')
						->join('affiliates', 'affiliates.id', '=', 'affiliate_users.affiliate_id')
						->where('users.id', '=', Auth::user()->id)
						->select('affiliates.uid')
						->first();
					//dd($affiliate_data);

					//assign Affiliate uid
					if (isset(Auth::user()->uid)) {
						$uid = Auth::user()->uid;
					} else {
						$uid = Config::get('constant.BI_UID');
					}

					//Checking UID exists on URL or not
					/*if(isset($_REQUEST['uid']) && $_REQUEST['uid'] != "" && CommonComponent::isAffiliteExists($_REQUEST['uid'])){
	                        $uid = $_REQUEST['uid'];
*/
				} else {
					//Default Affiliate uid
					$uid = Config::get('constant.BI_UID');
				}

				// Checking UID exists on URL or not
				if (isset($_REQUEST['uid']) && $_REQUEST['uid'] != "" && CommonComponent::isAffiliteExists($_REQUEST['uid'])) {
					$uid = $_REQUEST['uid'];
				}

				$insurance_startdate = sprintf("%s/%s/%s", $request->input('insurance_yy'), $request->input('insurance_mm'), $request->input('insurance_dd'));

				$oneyearfromins_startdate = date('Y-m-d', strtotime($insurance_startdate . "+1 year"));
				$insurance_enddate = date('Y-m-d', strtotime($oneyearfromins_startdate . "-1 day"));

				$dob = $request->input('year') . '-' . $request->input('month') . '-' . $request->input('day');

				$start_date = $request->input('insurance_yy') . '-' . $request->input('insurance_mm') . '-' . $request->input('insurance_dd');

				$age = date_diff(date_create($dob), date_create($start_date))->y;

				/* $dob = $request->input('year').'-'.$request->input('month').'-'.$request->input('day');

                    $age = date_diff(date_create($dob), date_create('today'))->y;*/
				$residential_status = $request->input('residential_status');

				$mortgage_type = $monthly_mortgage_repay = $monthly_loan_repay = "";
				$mortgage_duration_month = $mortgage_duration_year = 0;
				$monthly_gross_income = $monthly_benifit_amount = 0;
				$industry_type_id = $occupation_type_id = 0;
				$loan_duration_year = $loan_duration_month = $monthly_rent = 0;
				$cover_type = "";
				$excessperiod = 0;
				$taken_loan = '';

				if ($residential_status == 'owner') {
					// Home Owner
					$mortgage_type = $request->input('mortgage_type');
					if ($mortgage_type == 1) {
						//New Mortgage
						$monthly_mortgage_repay = $request->input('mm_repay_1');
						if ($request->input('mortgage_duration_month') != "") {
							$mortgage_duration_month = $request->input('mortgage_duration_month');
						}

						if ($request->input('mortgage_duration_year') != "") {
							$mortgage_duration_year = $request->input('mortgage_duration_year');
						}

					}
					if ($mortgage_type == 2) {
						//Existing Mortgage
						$monthly_mortgage_repay = $request->input('mm_repay_2');
					}
				} else if ($residential_status == 'tenant') {
					$monthly_rent = $request->input('monthly_rent');
				}

				/*$loan_repayment = $request->input('loan_repayment');

					                    if($loan_repayment == 1)
					                    {
					                        $taken_loan = $request->input('taken_loan');
					                        $monthly_loan_repay = $request->input('monthly_loan_repay');
					                        if($taken_loan == 1)
					                        {
					                            if($request->input('loan_duration_year') != "")
					                                $loan_duration_year = $request->input('loan_duration_year');
					                            if($request->input('loan_duration_month') != "")
					                                $loan_duration_month = $request->input('loan_duration_month');
					                        }
				*/

				$monthly_gross_income = $request->input('monthly_gross_income') / 12;
				$benifit_amount = $monthly_benifit_amount = $request->input('monthly_benifit_amount');
				$industry_type_id = $request->input('industry_type_id');
				$occupation_type_id = $request->input('occupation_type_id');
				$cover_type = $request->input('cover_type');
				$excess_period = $excessperiod = trim($request->input('excessperiod'));
				// For AS products
				if ($excess_period == 28) {
					$excess_period = 30;
				} elseif ($excess_period == 56) {
					$excess_period = 60;
				} else {
					$excess_period = $request->input('excessperiod');
				}

				$age_or_term = $request->input('age_or_term');

				$cease_cover = $request->input('cease_cover');
				$term_in_year = $request->input('term_in_year');

				// if($term_in_year == '' ){
				//     //$term_in_year == -1;
				// }
				// if($cease_cover == ''){
				//     //$cease_cover = -1;
				// }

				$qid = (int) $request->input('qid');

				$quote_update_status = quotes::where('id', $qid)
					->update([
						'affiliate_uid' => $uid,
						'dob' => $dob,
						'age' => $age,
						'residential_status' => $residential_status,
						'mortgage_type' => $mortgage_type,
						'monthly_mortgage_repay' => $monthly_mortgage_repay,
						'mortgage_duration_month' => $mortgage_duration_month,
						'mortgage_duration_year' => $mortgage_duration_year,
						'monthly_rent' => $monthly_rent,
						//'loan_repayment' => $loan_repayment,
						'taken_loan' => $taken_loan,
						'monthly_loan_repay' => $monthly_loan_repay,
						'monthly_gross_income' => $monthly_gross_income,
						'monthly_benifit_amount' => $monthly_benifit_amount,
						'industry_type_id' => $industry_type_id,
						'occupation_id' => $occupation_type_id,
						'cover_type' => $cover_type,
						'excess_period' => $excess_period,
						'loan_duration_month' => $loan_duration_month,
						'loan_duration_year' => $loan_duration_year,
						'age_or_term' => $age_or_term,
						'cease_cover' => $cease_cover,
						'term_in_year' => $term_in_year,

					]);

				if ($quote_update_status) {
					$quote_details = CommonComponent::getQuoteDetails($qid);
					$occupation_name=CommonComponent::getOccupationDetailsById($quote_details['occupation_id']);
					$insurance_startdate = sprintf("%s/%s/%s", $request->input('insurance_yy'), $request->input('insurance_mm'), $request->input('insurance_dd'));

					$monthlycover = $quote_details['monthly_benifit_amount'];
					$monthlybenefit = $monthlycover;

					$oneyearfromins_startdate = date('Y-m-d', strtotime($insurance_startdate . "+1 year"));
					$insurance_enddate = date('Y-m-d', strtotime($oneyearfromins_startdate . "-1 day"));

					$affiliated_uid = $quote_details['affiliate_uid'];
					if ($affiliated_uid != '') {
						$affiliation_data = Affiliates::where('uid', $affiliated_uid)->first();

						$lead_source_field = $affiliation_data->name;
					} else {
						$lead_source_field = 'Web Site';
					}

					$personal_dob = sprintf("%s", CommonComponent::actualDateFormat($dob));

					$fname_convert = str_replace("'", "’", $request->input('first_name'));
					$fname_convert = trim($fname_convert);
					$fname_convert = preg_replace("/[[:blank:]]+/", " ", $fname_convert);
					$lname_convert = str_replace("'", "’", $request->input('last_name'));
					$lname_convert = trim($lname_convert);
					
					$saved = Information::where('quote_id', $qid)
						->update([
							'title' => $request->input('title'),
							'gender' => $request->input('sex'),
							'smoker' => $request->input('smoker'),
							'increasing_benefit' => $request->input('txtIncreasingBenefit'),
							'fname' =>$fname_convert,
							'lname' => $lname_convert,
							'full_name' => $fname_convert . " " . $lname_convert,
							'dob' => $personal_dob,
							'premiseName' => $request->input('premise'),
							'address1' => $request->input('line1'),
							'address2' => $request->input('line2'),
							'address3' => $request->input('line3'),
							'address4' => $request->input('line4'),
							'postcode' => strtoupper($request->input('postcode')),
							'formattedPO' => $request->input('formattedPO'),
							'postaltown' => $request->input('town'),
							'county' => ($request->input('county') != '' ? $request->input('county') : ''),
							'email'=> $request->input('email'),
							'telephone'=>  $request->input('telephone'),
							'transfer'=>  ($request->input('transfer') != '' ? $request->input('transfer') : ''),	
							'current_provider'=>  ($request->input('current_provider') != '' ? $request->input('current_provider') : ''),	
							'emp_status'=>  $request->input('emp_status'),	
							'employer_name'=>  $request->input('employer_name'),
							'occupation' => $occupation_name,
							'salary' => $monthly_gross_income,
							'insurance_startdate' => $insurance_startdate,
							'typeofcover' => $quote_details['cover_type'],
							'age' => $quote_details['age'],
							'affid' => $affiliated_uid,
							'ip' => $_SERVER['REMOTE_ADDR'],
							'date_added' => date("Y-m-d"),
							'time_added' => date("H:i:s"),
							'excessperiod' => $excess_period,
							'monthlybenefit' => $monthlybenefit,
							'lead_source_field' => $lead_source_field,
							'insurer' => Config::get('constant.INSURER'),
							'insurance_enddate' => $insurance_enddate,
							//'status' => "1",
						]);
					if (!$saved) {
						Session::flash('failure', 'There was a problem. Please try again later.');
						return back()->withInput();
					}

					// Pass the data into webline api
					$monthly_gross_income = (int) $request->input('monthly_gross_income');

					$annual_earnings = $monthly_gross_income * 12;
					// $annual_earnings = $monthly_gross_income;
					$monthly_benifit_ammount = (int) $request->input('monthly_benifit_amount');

					/*
						                            1 day = 2048
						                            1 week = 4096
						                            4 weeks = 1
						                            8 weeks = 2
						                            13 weeks = 4
						                            26 weeks = 8
						                            52 weeks = 16
						                            56 weeks = 32
						                            104 weeks = 64
						                            112 weeks = 128
					*/
					switch ($excess_period) {
					case 1:
						$DefermentOpts = 2048;
						break;
					case 7:
						$DefermentOpts = 4096;
						break;
					case 28:
					case 30:
						$DefermentOpts = 1;
						break;
					case 56:
					case 60:
						$DefermentOpts = 2;
						break;
					case 91:
						$DefermentOpts = 4;
						break;
					case 182:
						$DefermentOpts = 8;
						break;
					case 364:
						$DefermentOpts = 16;
						break;
					case 392:
						$DefermentOpts = 32;
						break;
					case 728:
						$DefermentOpts = 64;
						break;
					case 784:
						$DefermentOpts = 128;
						break;
					default:
						$DefermentOpts = 1;
					}

					$ceaseAge = $request->input('cease_cover');
					$txtTermYears = $request->input('term_in_year');
					if ($ceaseAge != '') {
						$txtTermYears = -1;
					} else if ($txtTermYears != '') {
						$ceaseAge = -1;
					}
					echo $DefermentOpts;
				//	exit;
					$webline_post_data = array(
						"sex" => $request->input('sex'),
						"dob" => $dob,
						"smoker" => $request->input('smoker'),
						"title" => $request->input('title'),
						"forename" => $request->input('first_name'),
						"surname" => $request->input('last_name'),
						"earnings" => $annual_earnings,
						"term" => $request->input('term_in_year'),
						"ceaseage" => $request->input('cease_cover'),
						"frequency" => 'Monthly',
						"benefit" => $monthly_benifit_ammount,
						"quot_id" => $qid,
						"deferment_options" => $DefermentOpts,
					);

					DB::table('temp_quot_webline_products')->where('QuoteId', '=', $qid)->delete();
					DB::table('temp_quot_webline_documents')->where('QuoteId', '=', $qid)->delete();
					// If cover type equals Accidence and Sickness to then only call the webline api
					if ($cover_type == 'AS') {
						// check the webline products or not based on Affiliate id
						$status_check = CommonComponent::checkWeblineBasedonAffiliate($uid);
						if ($status_check != 0) {
							// CommonComponent::DoQuote($webline_post_data);
							$webline_service = new WeblineController();
							$webline_service->getProducts($webline_post_data);
						}
					}

					// echo '<prE>';
					// print_r($result);
					// exit;

					return redirect('product-list/' . encryptUrl($qid));

				} else {
					Session::flash('failure', 'There was a problem. Please try again later.');
					return back();
				}
			} // $request->isMethod('post') -- end
			else {

				$quote_id = $request->id;

				$quote_id = (int) decryptUrl($quote_id);

				//echo $quote_id;
				// exit;
				// check the quote data exist or not
				$quote_data = DB::table('quotes')
					->join('occupations', 'occupations.id', '=', 'quotes.occupation_id')
					->join('industries', 'industries.id', '=', 'quotes.industry_type_id')
					->where('quotes.id', '=', $quote_id)
					->select('quotes.*', 'occupations.occupation_name', 'industries.industry_name')
					->first();
				//$quote_data = (array)$query_result;

				//$quote_data = CommonComponent::getQuoteDetails($quote_id);
				if ($quote_data === null || $quote_data == '') {
					Session::flash('failure', 'Product details does not exist.');
					return redirect('product-list/' . $quote_id);
				}

				$information_data = Information::where('quote_id', '=', $quote_id)->first();


				$complete_address = ($information_data->premiseName != '' ? $information_data->premiseName . "<br>" : '') . ($information_data->address1 != '' ? $information_data->address1 . "<br>" : '') . ($information_data->address2 != '' ? $information_data->address2 . "<br>" : '') . ($information_data->address3 != '' ? $information_data->address3 . "<br>" : '') . ($information_data->address4 != '' ? $information_data->address4 . "<br>" : '') . ($information_data->postaltown != '' ? $information_data->postaltown . "<br>" : '') . ($information_data->country != '' ? $information_data->country . "<br>" : '');


				$months = array("01" => "Jan", "02" => "Feb", "03" => "Mar", "04" => "Apr", "05" => "May", "06" => "Jun", "07" => "Jul", "08" => "Aug", "09" => "Sep", "10" => "Oct", "11" => "Nov", "12" => "Dec",
				);
				$days = array("01" => "01", "02" => "02", "03" => "03", "04" => "04", "05" => "05", "06" => "06", "07" => "07", "08" => "08", "09" => "09", "10" => "10", "11" => "11", "12" => "12", "13" => "13", "14" => "14", "15" => "15", "16" => "16", "17" => "17", "18" => "18", "19" => "19", "20" => "20", "21" => "21", "22" => "22", "23" => "23", "24" => "24", "25" => "25", "26" => "26", "27" => "27", "28" => "28", "29" => "29", "30" => "30", "31" => "31",
				);

				$dob = explode("-", $quote_data->dob);
				$dob[0] = (int) $dob[0];
				$loan_duration_month = str_pad($quote_data->loan_duration_month, 2, "0", STR_PAD_LEFT);
				$loan_duration_year = str_pad($quote_data->loan_duration_year, 2, "0", STR_PAD_LEFT);
				$user_info = $this->__construct();
				// echo "<pre>";
				// print_r($user_info);
				// exit;

				return view('frontend.get-a-quote-edit', [
					'months' => $months,
					'days' => $days,
					'quote_data' => $quote_data,
					'information_data' => $information_data,
					'dob' => $dob,
					'loan_duration_year' => $loan_duration_year,
					'loan_duration_month' => $loan_duration_month,
					'user_info' => $user_info,
					"current_year" => date("Y"),
					"current_month" => date("m"),
					"current_date" => date("d"),
					"complete_address" => $complete_address,

				]);
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Personal details page
	public function addPersonalDetails($quote_id, $product_id, $webline = null, $affiliate = null) {
		try
		{
			//echo $affiliate;
			//exit;
			$quote_id = (int) decryptUrl($quote_id);

			$information_data = Information::where('quote_id', '=', $quote_id)
			// ->where('accountnumber','!=','')
			// ->where('policy_number','!=','')
				->first();

			// print_r($information_data);

			// exit;
			if ($information_data->policy_number_full != "") {

				return response()->view('errors.404-policy');
				exit;
			}

			// $from_date= Carbon::createFromFormat('Y-m-d', $information_data->insurance_startdate);

			$from_date = Carbon::parse($information_data->insurance_startdate);
			$now = Carbon::today();

			$diff = $now->diffInDays($from_date);
			// $diff=$now-$from_date;

			if ($from_date < $now && $affiliate == "affiliate") {

				return response()->view('errors.404-policy-invaliddate');
				exit;

			}

			/*elseif($from_date < $now && $diff>30)
				                {
				                    return response()->view('errors.404-policy-invaliddate');
				                        exit;
			*/

			$product_id = (int) $product_id;
			if (isset($quote_id) && $quote_id != '' && isset($product_id) && $product_id != '') {

				// check the quote id is exist or not
				$quote_data = Quotes::where('id', '=', $quote_id)->first();
				if ($quote_data === null) {
					Session::flash('failure', 'Invalid Quote');
					return redirect('get-a-quote');
				} else {
					if ($webline == 'webline') {
						// check the product data exist or not
						$webline_product_details = DB::table('temp_quot_webline_products')
							->where('id', $product_id)
							->first();
						$product_details = array();
						$product_details['product_name'] = $webline_product_details->ProductName;
						$product_details['id'] = $webline_product_details->id;
						$product_details['product_info1'] = '';
						$product_details['product_info2'] = '';
						$product_details['disclaimer'] = $webline_product_details->NotesHTML;
						$product_details['self_decleration'] = '';
						$product_details['policy_wordings_doc'] = '';
						$product_details['keyfacts_doc'] = '';
						$product_details['your_policy_doc_text'] = '';
						$product_details['benifit_period'] = '';
						$product_details['buy_with_confidence'] = '';

						$product_details = (object) $product_details;
						$monthly_cost = '';

					} else {
						// If user select cover type as Unemployement than it should display ASU 14 days and 30 days products and then update the quote table and information table --  new requirement -- 22-11-2017 -- start
						$quote_details = CommonComponent::getQuoteDetails($quote_id);
						if ($quote_details['cover_type'] == 'U' && $product_id == Config::get('constant.APRIL_UK_SHORTERM_INCOME_PROTECTION')) {
							if ($webline == '30 days') {
								$excess_period_asu = 30;
							}

							if ($webline == '14 days') {
								$excess_period_asu = 14;
							}

							if ($excess_period_asu) {
								quotes::where('id', $quote_id)
									->update([
										'cover_type' => 'ASU',
										'excess_period' => $excess_period_asu,
									]);
								Information::where('quote_id', $quote_id)
									->update([
										'typeofcover' => 'ASU',
										'excessperiod' => $excess_period_asu,
									]);
							}
						} //From search excess period needs to be update - str
						if ($product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {
							if ($webline) {
								switch ($webline) {
								case 'Back to day 1':
									$excess_period_url = 1;
									break;
								case '1 Week':
									$excess_period_url = 7;
									break;
								case '4 Weeks':
									$excess_period_url = 30;
									break;
								case '8 Weeks':
									$excess_period_url = 60;
									break;
								case '13 Weeks':
									$excess_period_url = 91;
									break;
								case '26 Weeks':
									$excess_period_url = 182;
									break;
								case '52 Weeks':
									$excess_period_url = 364;
									break;
								default:
									$excess_period_url = 1;
								}
							} else {
								$excess_period_url = '';
							}

						} else {
							if ($webline) {
								switch ($webline) {
								case 'Back to day 1':
									$excess_period_url = 1;
									break;
								case '14 days':
									$excess_period_url = 14;
									break;
								case '30 days':
									$excess_period_url = 30;
									break;
								case '60 days':
									$excess_period_url = 60;
									break;
								case '90 days':
									$excess_period_url = 90;
									break;
								case '120 days':
									$excess_period_url = 120;
									break;
								default:
									$excess_period_url = 1;
								}
							} else {
								$excess_period_url = '';
							}

						}

						if ($excess_period_url && $webline != 'null') {
							//echo "in this sectim";
							quotes::where('id', $quote_id)
								->update([
									'excess_period' => $excess_period_url,
								]);
							Information::where('quote_id', $quote_id)
								->update([
									'excessperiod' => $excess_period_url,
								]);
						}

						// From search excess period needs to be update - end
						// check the product data exist or not
						$product_details = DB::table('products')
							->where('id', $product_id)
							->first();

						$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $product_id);
						//     print_r('chamu');
						// exit;
					}

					if ($product_details === null && $product_details == '') {
						Session::flash('failure', 'Product details does not exist.');
						return redirect('product-list/' . $quote_id);
					}

					$personal_data = Information::where('quote_id', '=', $quote_id)->first();

					// Get the quote information as array
					$quote_details = CommonComponent::getQuoteDetails($quote_id);

					if ($quote_details['cover_type'] == "U") {
						$cover_type = "Unemployment only";
					} else if ($quote_details['cover_type'] == "AS") {
						$cover_type = "Accident & Sickness only";
					} else {
						$cover_type = "Unemployment, Accident & Sickness";
					}

					$complete_address = ($personal_data->premiseName != '' ? $personal_data->premiseName . "<br>" : '') . ($personal_data->address1 != '' ? $personal_data->address1 . "<br>" : '') . ($personal_data->address2 != '' ? $personal_data->address2 . "<br>" : '') . ($personal_data->address3 != '' ? $personal_data->address3 . "<br>" : '') . ($personal_data->address4 != '' ? $personal_data->address4 . "<br>" : '') . ($personal_data->postaltown != '' ? $personal_data->postaltown . "<br>" : '') . ($personal_data->country != '' ? $personal_data->country . "<br>" : '');

					$insurance_startdate = array();

					$insurance_startdate[2] = "0000";
					$insurance_startdate[1] = "00";

					if (isset($personal_data->insurance_startdate) && !empty($personal_data->insurance_startdate)) {
						$insurance_startdate = explode("-", $personal_data->insurance_startdate);
					}

					//  print_r($personal_data->insurance_startdate);

					// exit;

					// Update the user id
					Information::where('quote_id', $quote_id)
						->update([
							'user_id' => isset(Auth::user()->id) ? Auth::user()->id : '',
						]);

					// $products_list_webline = CommonComponent::getProductsWebline($quote_id);

					//Fetch Product Details
					$product_dtls = CommonComponent::getProductDetails($product_id);

					$user_info = $this->__construct();

					//   print_r($insurance_startdate);
					//exit;

					//print_r($affiliate);
					//exit;
					$aff_profile_id = CommonComponent::getAffiliateProfileType($personal_data->affid);
					// echo "profile id".$aff_profile_id;

					return view('frontend.personal_details', [
						'product_details' => $product_details,
						'best_mortgage' => Config::get('constant.BEST_MORTGAGE'),
						'best_loan' => Config::get('constant.BEST_LOAN'),
						'simple_income' => Config::get('constant.SIMPLE_INCOME'),
						'instaprotect' => Config::get('constant.INSTAPROTECT'),
						'cover_type' => $cover_type,
						'quote_details' => $quote_details,
						'monthly_cost' => $monthly_cost,
						'insurer' => $product_dtls['insurer'],
						"current_year" => date("Y"),
						"current_month" => date("m"),
						"current_date" => date("d"),
						"personal_data" => $personal_data,
						"complete_address" => $complete_address,
						"insurance_startdate" => $insurance_startdate,
						'user_info' => $user_info,
						'affiliate' => $affiliate,
						'profile_id' => $aff_profile_id,

					]);
				} // quote data check else end

			} else {
				Session::flash('failure', 'Invalid Details');
				return redirect('get-a-quote');
			}

		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			exit;
		}
	}
	// Get the post code
	public function postcodeValidate(Request $request) {
		if ($request->ajax()) {
			//$accountnumber=$_POST['accountnumber'];
			$pocode = $request->pocode;

			$Key = 'ZC52-WY44-WK19-XB35';

			//Build the url
			$url = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/FindByPostcode/v1.00/json.ws?";
			$url .= "&Key=" . urlencode($Key);
			$url .= "&Postcode=" . urlencode($pocode);

			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$data = curl_exec($ch);
			curl_close($ch);
			print_r($data);
			exit;
			echo $data;
		}
	}

	// Get the address based on post code
	public function postcodeFetch(Request $request) {
		if ($request->ajax()) {
			$id = $request->id;

			$Key = 'ZC52-WY44-WK19-XB35';

			//Build the url
			$url = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/RetrieveById/v1.20/json.ws?";
			$url .= "&Key=" . urlencode($Key);
			$url .= "&Id=" . urlencode($id);

			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$data = curl_exec($ch);
			curl_close($ch);

			echo $data;
		}
	}

	// Add personal details
	public function addPersonalDetailsPost(Request $request) {
		try
		{
			$req = $request->input();
			print_r($req);
			//exit;
			if ($req['formattedPO'] == '' && empty($req['formattedPO'])) {
				\Flash::error('Please select address information.');
				return back()->withInput();
			}

			$quote_id = (int) $request->input('quot_id');
			$product_id = (int) $request->input('product_id');
			// Get the quote details
			$quote_details = CommonComponent::getQuoteDetails($quote_id);

			// Get the product infirmation
			$product_details = CommonComponent::getProductDetails($product_id);

			/*
				            echo "<pre>";
				            echo "------------Post data----------";
				            print_r($_POST);
				            echo "------------Quot details----------";
				            print_r($quote_details);
				            echo "------------Product details----------";
				            print_r($product_details);
				            exit;
			*/

			//print_r($product_details);
			//exit;

			$insurer = $product_details['insurer_crm'];

			//echo $insurer;
			/*exit;
	            if($product_id=="1")
	            $insurer= "Best_Income_Covea";
	            elseif($product_id=="2")
	            $insurer= "Best_Ultra_Covea";
	            else
*/

			//echo "product_id".$product_id."insurer".$insurer;
			// exit;

			$dob = sprintf("%s", CommonComponent::actualDateFormat($quote_details['dob']));
			// $insurance_startdate = sprintf("%s/%s/%s",$request->input('insurance_yy'),$request->input('insurance_mm'),$request->input('insurance_dd'));

			$monthlycover = $quote_details['monthly_benifit_amount'];
			$monthlybenefit = $monthlycover;
			$monthlycost = CommonComponent::getQuoteProductCost($quote_id, $product_id);

			// $oneyearfromins_startdate = date('Y-m-d',strtotime($insurance_startdate . "+1 year"));
			// $insurance_enddate = date('Y-m-d',strtotime($oneyearfromins_startdate . "-1 day"));

			$affiliated_uid = $quote_details['affiliate_uid'];
			if ($affiliated_uid != '') {
				$affiliation_data = Affiliates::where('uid', $affiliated_uid)->first();

				$lead_source_field = $affiliation_data->name;
			} else {
				$lead_source_field = 'Web Site';
			}

			$product_dtls = CommonComponent::getProductDetails($product_id);
			if (Auth::check()) {
				$user_id = Auth::user()->id;
			} else {
				$user_id = 0;
			}
			$personaldata_update_status = Information::where('quote_id', $quote_id)
				->update([
					'product_id' => $product_id,
					//  'insurance_startdate' => $insurance_startdate,
					'premiseName' => $request->input('premise'),
					'address1' => $request->input('line1'),
					'address2' => $request->input('line2'),
					'address3' => $request->input('line3'),
					'address4' => $request->input('line4'),
					'postcode' => strtoupper($request->input('postcode')),
					'formattedPO' => $request->input('formattedPO'),
					'postaltown' => $request->input('town'),
					'county' => ($request->input('country') != '' ? $request->input('country') : ''),
					'email' => $request->input('email'),
					'telephone' => $request->input('telephone'),
					'date_added' => date("Y-m-d"),
					'time_added' => date("H:i:s"),
					'monthlybenefit' => $monthlybenefit,
					'benefit_period' => $product_dtls['benifit_period'],
					'monthlycost' => $monthlycost,
					'lead_source_field' => $lead_source_field,
					'insurer' => $insurer,
					'transfer' => ($request->input('transfer') != '' ? $request->input('transfer') : ''),
					'current_provider' => ($request->input('current_provider') != '' ? $request->input('current_provider') : ''),
					'current_policy_date' => ($request->input('current_policy_date') != '' ? $request->input('current_policy_date') : ''),
					'is_webline_product' => 'No',
					'emp_status' => $request->input('emp_status'),
					'employer_name' => $request->input('employer_name'),
					//  'insurance_enddate' => $insurance_enddate,
					'marketingOptOut' => $request->input('marketingOptOut'),
					'declaration_confirm' => $request->input('declaration_confirm'),
					'created_id_by' => $user_id,
				]);

			if (!$personaldata_update_status) {
				\Flash::error('There was a problem. Please try again later.');
				// Session::flash('failure', 'There was a problem. Please try again later.');
				return back()->withInput();
			} else {
				/*// Insert personal data into the CRM -- start
					                $personal_data = Information::where('quote_id', '=', $quote_id)->first();
					                $product_data = Product::where('id', '=', $personal_data->product_id)->first();

					                $quote_data = DB::table('quotes')
					                    ->join('industries', 'industries.id', '=', 'quotes.industry_type_id')
					                    ->join('occupations', 'occupations.id', '=', 'quotes.occupation_id')
					                    ->where('quotes.id', '=', $quote_id)
					                    ->select('quotes.*', 'industries.industry_name', 'occupations.occupation_name')
					                    ->first();
					                $crm_response = CommonComponent::insertPersonalDataIntoCRM($personal_data,$quote_data,$product_data);

					                // Insert personal data into the CRM -- end

					                if($crm_response['id'] == -1)
					                {
					                    \Flash::error('There was a problem while inserting data into the database. Please try again later.');
					                    // Session::flash('failure', "There was a problem while inserting data into the database. Please try again later.");
					                    return back()->withInput();
					                    $Mail_subject = array(
					                        'personal_data' => $personal_data,
					                        'product_data' => $product_data,
					                    );

					                    $mailsent = Mail::send(['html' => 'auth.emails.crm-disconnected-mail'], $Mail_subject, function ($message) use ($Mail_subject,$personal_data)
					                    {
					                        $message->from('info@bestinsurance.co.uk', 'info@bestinsurance.co.uk');
					                        // $message->to('chamundeswari.somu@quadone.com')->subject('New policy details from '.$personal_data->fname);

					                        $message->to('admin@bestinsurance.co.uk')->subject('New policy details from '.$personal_data->fname);
					                    });
					                   return redirect('cover/'.$quote_id.'/'.$product_id);
					                }
					                else
					                {
					                    $rid = $crm_response['id'];
					                    $personaldata_update_status = information::where('quote_id', $quote_id)
					                        ->update([
					                            'crm_id' => $rid,
					                        ]);

				*/
				return redirect('cover/' . encryptUrl($quote_id) . '/' . $product_id);
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			exit;
		}
	} // End addPersonalDetailsPost()

	// Cover page (Underwritting questions)
	public function cover(Request $request) {
		try
		{
			$quote_id = (int) decryptUrl($request->quote_id);

			if ($request->excess_period == 28) {
				$excess_period = 30;
			} elseif ($request->excess_period == 56) {
				$excess_period = 60;
			} else {
				$excess_period = $request->excess_period;
			}
		
		
			Information::where(['quote_id' =>  $quote_id])
			->update([
				'excessperiod' => $excess_period,
			
			]);
		
			Quotes::where(['id' =>  $quote_id])
			->update([
				'excess_period' => $excess_period,
			
			]);

			$information_data = Information::where('quote_id', '=', $quote_id)
				->where('accountnumber', '!=', '')
				->where('policy_number', '!=', '')
				->first();

			// print_r($information_data);

			// exit;
			if ($information_data) {

				//return response()->view('errors.404-policy');
				//exit;
			}


			$information_first = Information::where('quote_id', '=', $quote_id)
				
				->first();

				$currentDate=date('Y-m-d');
				$currentDate = date('Y-m-d', strtotime($currentDate)); 
				$insuranceStartdate= date('Y-m-d', strtotime($information_first->insurance_startdate));   

			
			if($insuranceStartdate < $currentDate)
			{

				Information::where(['quote_id' =>  $quote_id])
				->update([
				'insurance_startdate' => date('Y-m-d'),
			
			]);
			}
			
			//exit;

			$product_id = (int) $request->product_id;

			$product_details = CommonComponent::getProductDetails($product_id);
			$insurer = $product_details['insurer_crm'];
			$monthlycost = CommonComponent::getQuoteProductCost($quote_id, $product_id);

			$personaldata_update_status = Information::where('quote_id', $quote_id)
							->update([
								'product_id' => $product_id,
								'insurer' => $insurer,
								'monthlycost' => $monthlycost,
								]);
					
			if (isset($quote_id) && $quote_id != '' && isset($product_id) && $product_id != '') {
				// check the personal information id is exist or not
				$personal_data = Information::where('quote_id', '=', $quote_id)->first();
				if ((isset($personal_data) && $personal_data != '') && ($personal_data->product_id == $product_id)) {
					// Get the product details
					$product_details = DB::table('products')
						->where('id', $product_id)
						->first();

					// Get the quote information as array
					$quote_details = CommonComponent::getQuoteDetails($quote_id);
				//	dd($quote_details);

					$questions = CommonComponent::getProductQuestions($personal_data->product_id,$quote_details['cover_type']);

					// Remove the id ,product id and posted date-time from the list
					$questions = (array) $questions;
					array_forget($questions, 'id');
					array_forget($questions, 'product_id');
					array_forget($questions, 'posted_datetime');
					array_forget($questions, 'cover_type');

					if($personal_data->product_id=="35")
						array_forget($questions, 'question15');

					if($personal_data->product_id=="36")
						array_forget($questions, 'question14');


					if($personal_data->product_id=="38")
					{
						array_forget($questions, 'question14');
						array_forget($questions, 'question15');
						array_forget($questions, 'question16');
					}

					if($personal_data->product_id=="40")
					{
						array_forget($questions, 'question10');
						array_forget($questions, 'question11');
						//array_forget($questions, 'question16');
					}

					if($personal_data->product_id=="37")
						array_forget($questions, 'question9');

					$questions = (object) $questions;

					$underwriting_questions_data = UnderwritingQuestions::where(['quote_id' => $quote_id, 'product_id' => $product_id])->first();
					$user_info = $this->__construct();

					// Get the quote information as array
				//	$quote_details = CommonComponent::getQuoteDetails($quote_id);
					$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $product_id);

					$affiliation_data = Affiliates::where('uid', $personal_data->affid)->first();

					

					$questions = (array) $questions;
					array_forget($questions, 'id');
					array_forget($questions, 'product_id');
					array_forget($questions, 'posted_datetime');
					$questions = (object) $questions;

					// $underwriting_questions_data = UnderwritingQuestions::where('quote_id', $personal_data->quote_id)->first();

					if ($affiliation_data != '') {
						$affiliatename = $affiliation_data['Legal_Entity'];
					} else {
						$affiliatename = 'Best Risk Management & Fin';
					}

					$typeofcover = $personal_data->typeofcover;
					switch ($typeofcover) {
					case 'ASU':
						$policy = "Unemployment, Accident & Sickness";
						break;

					case 'U':
						$policy = "Unemployment only";
						break;

					case 'AS':
						$policy = "Accident & Sickness only";
						break;

					}

					$excess = $quote_details['excess_period'];
					// print_r($excess);

					if ($product_id == 15 || $product_id == 14) {
						switch ($excess) {
						case 1:
							$excess_period = 'Back to day 1';
							break;
						case 7:
							$excess_period = '1 Week';
							break;
						case 14:
							$excess_period = '2 weeks';
							break;
						case 28:
							$excess_period = '4 weeks';
							break;
						case 30:
							$excess_period = '30 Days';
							break;
						case 56:
							$excess_period = '8 weeks';
							break;
						case 60:
							$excess_period = '60 Days';
							break;
						case 91:
							$excess_period = '13 weeks';
							break;
						case 182:
							$excess_period = '26 weeks';
							break;
						case 364:
							$excess_period = '52 weeks';
							break;
						default:
							$excess_period = 'Back to day 1';
						}
					} else {
						switch ($excess) {
						case 1:
							$excess_period = "Back to Day 1";
							break;
						case 14:
							$excess_period = "14 Days";
							break;
						case 30:
							$excess_period = "30 Days";
							break;

						case 60:
							$excess_period = "60 Days";
							break;
						}
					}

					// print_r($excess_period);
					// return;

					$add = "";
					if ($personal_data->premiseName != "") {
						$add .= $personal_data->premiseName . ", ";
					}
					if ($personal_data->address1 != "") {
						$add .= $personal_data->address1;
					}
					if ($personal_data->address2 != "") {
						$add .= ", " . $personal_data->address2;
					}
					if ($personal_data->address3 != "") {
						$add .= ", " . $personal_data->address3;
					}
					if ($personal_data->address4 != "") {
						$add .= ", " . $personal_data->address4;
					}

					if ($personal_data->postaltown != "") {
						$add .= ", " . $personal_data->postaltown;
					}

					if ($personal_data->county != "") {
						$add .= ", " . $personal_data->county;
					}

					if ($personal_data->postcode != "") {
						$add .= ", " . $personal_data->postcode;
					}
					$data = array(
						'product_details' => $product_details,
						'quote_details' => $quote_details,
						'personal_data' => $personal_data,
						'monthly_cost' => $monthly_cost,
						'policy' => $policy,
						'price' => number_format($monthly_cost, 2, '.', ''),
						'add' => $add,
						'affiliation_data' => $affiliation_data,
						'affiliatename' => $affiliatename,
						'questions' => $questions,
						'underwriting_questions' => $underwriting_questions_data,
						'excess_period' => $excess_period,
						'message' => 'is a trading name of Best Risk Management and Financial Service Limited who are authorised and regulated by the Financial Conducts Authority (FCA registration number 583497). Registered office is Gemini Business Centre, 136-140, Old Shoreham Road, Hove BN3 7BD (Registered No. 07095571)',

					);

					view()->share($data);
					$quote_pdf_name = 'Quote_' . time() . '_' . mt_rand() . '.pdf';
					/*return view('slices.frontend.get-a-quot.quote_pdf');
                        exit;*/

					if ($product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {

						// return view('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration', compact('data'));

						$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration', compact('data'))->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);

					} elseif ($product_id == Config::get('constant.SIMPLE_INCOME_INSURANCE_COVEA')) {
						$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.quote_pdf_simple_covea')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
					} else {
						if ($product_id == Config::get('constant.EASIPROTECT') || $product_id == Config::get('constant.KEYSTONE') || $product_id == Config::get('constant.KEYSTONE_18M') || $product_id == Config::get('constant.HOMEOWNER') || $product_id == Config::get('constant.ASSURITY')) {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.easiprotect_quote')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						} else {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.quote_pdf')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						}
					}

					$quote_pdf_data = QuotePdf::where(['quote_id' => $quote_id])->first();
					//$count = count($quote_pdf_data);
					if (empty($quote_pdf_data)) {
						// Insert the record
						$pdf_data = new QuotePdf;
						$pdf_data->quote_id = $quote_id;
						$pdf_data->quote_pdf = $quote_pdf_name;

						$pdf_data->save();

						//$inserted_id = $pdf_data->id;
					} else {
						// Delete the old record and update with new one
						if (file_exists(public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf)) {
							unlink(public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf);
						}
						QuotePdf::where('quote_id', $quote_id)
							->update([
								'quote_pdf' => $quote_pdf_name,
							]);
					}
					/*echo "<pre>";
						                    print_r($questions);
						                    print_r($underwriting_questions_data);
					*/
					if ($product_id == 15 || $product_id == 14) {
						$heights = CommonComponent::getHeights();
						$questions = CommonComponent::getWeblineQuestions();
						$where_array = array(
							'quote_id' => $quote_id,
							'product_id' => $product_id,
							// 'is_webline_product' => 'No'
						);
						$underwriting_questions_data = CommonComponent::getWeblineQuestionAnswers($where_array);
						return view('frontend.new_products_cover_page', [
							'product_details' => $product_details,
							'quote_details' => $quote_details,
							"personal_data" => $personal_data,
							'questions' => $questions,
							'underwriting_questions_data' => $underwriting_questions_data,
							'user_info' => $user_info,
							'quote_pdf_name' => $quote_pdf_name,
							'cover_page' => 'yes',
							'heights' => $heights,
						]);
					} else {
						return view('frontend.cover_page', [
							'product_details' => $product_details,
							'quote_details' => $quote_details,
							"personal_data" => $personal_data,
							'questions' => $questions,
							'underwriting_questions_data' => $underwriting_questions_data,
							'user_info' => $user_info,
							'quote_pdf_name' => $quote_pdf_name,
							'cover_page' => 'yes',
						]);
					}

				} else {
					abort(404);
				} // quote data check else end
			} else {
				abort(404);
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Cover page data post
	public function coverPost(Request $request) {
		$post_data = $request->all();

		// Remove all white spaces before validating data

		array_map('trim', $post_data);

		$product_id = $post_data['hidden_product_id'];
		$cover_type = $post_data['cover_type'];
		$product_conditions = DB::table('product_conditions')
			->where('product_id', $product_id)
			->where('cover_type', $cover_type)
			->first();
		$product_conditions = (array) $product_conditions;

		//$count_questions = DB::table('product_underwriting_questions')->where('id',$product_id)->count();

		// check the all fields are required or not
		
		for ($i = 1; $i <= $product_conditions['questions_count']; $i++) {
			if (!array_key_exists('question' . $i, $post_data)) {
				Session::flash('failure', 'All fields are required.');
				return back()->withInput();
			}
		}

		// validate the input data
		foreach ($product_conditions as $key1 => $value1) {
			foreach ($post_data as $key2 => $value2) {
				if (($value1 != "-") && ($key1 === $key2) && ($value1 != $value2) && ($value1 != '')) {
				//	Session::flash('failure', $product_conditions[$key1 . '_fail_msg']);


					Session::flash('failure', 'We are sorry, you are not eligible for this policy. Please call us on 0330 330 9465 or email info@bestinsurance.co.uk and one of our specialists will be able to discuss your options and find the right policy for you');

					return back()->withInput();
					exit;
				}
			}
		}

		$underwriting_questions_data = UnderwritingQuestions::where('quote_id', $post_data['hidden_quote_id'])->first();
		if (isset($underwriting_questions_data) && $underwriting_questions_data != '') {
			$saved_status = UnderwritingQuestions::where('quote_id', $post_data['hidden_quote_id'])
				->update([
					'question1' => ((isset($post_data['question1']) && $post_data['question1'] != '') ? $post_data['question1'] : ""),
					'question2' => ((isset($post_data['question2']) && $post_data['question2'] != '') ? $post_data['question2'] : ""),
					'question3' => ((isset($post_data['question3']) && $post_data['question3'] != '') ? $post_data['question3'] : ""),
					'question4' => ((isset($post_data['question4']) && $post_data['question4'] != '') ? $post_data['question4'] : ""),

					'question5' => ((isset($post_data['question5']) && $post_data['question5'] != '') ? $post_data['question5'] : ""),
					'question6' => ((isset($post_data['question6']) && $post_data['question6'] != '') ? $post_data['question6'] : ""),
					'question7' => ((isset($post_data['question7']) && $post_data['question7'] != '') ? $post_data['question7'] : ""),
					'question8' => ((isset($post_data['question8']) && $post_data['question8'] != '') ? $post_data['question8'] : ""),

					'question9' => ((isset($post_data['question9']) && $post_data['question9'] != '') ? $post_data['question9'] : ""),
					'question10' => ((isset($post_data['question10']) && $post_data['question10'] != '') ? $post_data['question10'] : ""),
					'question11' => ((isset($post_data['question11']) && $post_data['question11'] != '') ? $post_data['question11'] : ""),
					'question12' => ((isset($post_data['question12']) && $post_data['question12'] != '') ? $post_data['question12'] : ""),

					'question13' => ((isset($post_data['question13']) && $post_data['question13'] != '') ? $post_data['question13'] : ""),
					'question14' => ((isset($post_data['question14']) && $post_data['question14'] != '') ? $post_data['question14'] : ""),
					'question15' => ((isset($post_data['question15']) && $post_data['question15'] != '') ? $post_data['question15'] : ""),

					'product_id' => $product_id,
				]);

			if($product_id=="40")
				{
				if(isset($post_data['transfer_insurer']) && $post_data['transfer_insurer']!="")
				{
					 $transfer = "Yes";
				 	$current_provider = ($post_data['transfer_insurer'] != '' ? $post_data['transfer_insurer'] : '');
					 $current_policy_date = ($post_data['transfer_insurance_startdate'] != '' ? $post_data['transfer_insurance_startdate'] : '');

					// echo $transfer . "-".$current_provider."-".$current_policy_date;

					 Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							'current_provider' => $current_provider,
							'current_policy_date' => $current_policy_date,
						]);

					// exit;
				}
				else

				{
					$transfer = "No";
					Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							//'current_provider' => $current_provider,
							//'current_policy_date' => $current_policy_date,
						]);
				}
				
			}

			if($product_id=="38")
				{
				if(isset($post_data['transfer_insurer_incomebee']) && $post_data['transfer_insurer_incomebee']!="")
				{
					 $transfer = "Yes";
				 	$current_provider = ($post_data['transfer_insurer_incomebee'] != '' ? $post_data['transfer_insurer_incomebee'] : '');
					 $current_policy_date = ($post_data['transfer_insurance_startdate_incomebee'] != '' ? $post_data['transfer_insurance_startdate_incomebee'] : '');

					// echo $transfer . "-".$current_provider."-".$current_policy_date;

					 Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							'current_provider' => $current_provider,
							'current_policy_date' => $current_policy_date,
						]);

					// exit;
				}
				else

				{
					$transfer = "No";
					Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							//'current_provider' => $current_provider,
							//'current_policy_date' => $current_policy_date,
						]);
				}
				
			}
			return redirect('bank-details/' . encryptUrl($post_data['hidden_quote_id']));
		} else {
			$questions_data = new UnderwritingQuestions;
			$questions_data->question1 = ((isset($post_data['question1']) && $post_data['question1'] != '') ? $post_data['question1'] : "");
			$questions_data->question2 = ((isset($post_data['question2']) && $post_data['question2'] != '') ? $post_data['question2'] : "");
			$questions_data->question3 = ((isset($post_data['question3']) && $post_data['question3'] != '') ? $post_data['question3'] : "");
			$questions_data->question4 = ((isset($post_data['question4']) && $post_data['question4'] != '') ? $post_data['question4'] : "");

			$questions_data->question5 = ((isset($post_data['question5']) && $post_data['question5'] != '') ? $post_data['question5'] : "");
			$questions_data->question6 = ((isset($post_data['question6']) && $post_data['question6'] != '') ? $post_data['question6'] : "");
			$questions_data->question7 = ((isset($post_data['question7']) && $post_data['question7'] != '') ? $post_data['question7'] : "");

			$questions_data->question8 = ((isset($post_data['question8']) && $post_data['question8'] != '') ? $post_data['question8'] : "");
			$questions_data->question9 = ((isset($post_data['question9']) && $post_data['question9'] != '') ? $post_data['question9'] : "");
			$questions_data->question10 = ((isset($post_data['question10']) && $post_data['question10'] != '') ? $post_data['question10'] : "");

			$questions_data->question11 = ((isset($post_data['question11']) && $post_data['question11'] != '') ? $post_data['question11'] : "");
			$questions_data->question12 = ((isset($post_data['question12']) && $post_data['question12'] != '') ? $post_data['question12'] : "");
			$questions_data->question13 = ((isset($post_data['question13']) && $post_data['question13'] != '') ? $post_data['question13'] : "");

			$questions_data->question14 = ((isset($post_data['question14']) && $post_data['question14'] != '') ? $post_data['question14'] : "");

			$questions_data->question15 = ((isset($post_data['question15']) && $post_data['question15'] != '') ? $post_data['question15'] : "");

			$questions_data->question1desc = ((isset($post_data['desc']) && $post_data['desc'] != '') ? $post_data['desc'] : "");
			$questions_data->quote_id = $post_data['hidden_quote_id'];

			$questions_data->product_id = $product_id;

			$saved_status = $questions_data->save();
		}

		if($product_id=="40")
				{
				if(isset($post_data['transfer_insurer']) && $post_data['transfer_insurer']!="")
				{
					 $transfer = "Yes";
				 	$current_provider = ($post_data['transfer_insurer'] != '' ? $post_data['transfer_insurer'] : '');
					 $current_policy_date = ($post_data['transfer_insurance_startdate'] != '' ? $post_data['transfer_insurance_startdate'] : '');

					// echo $transfer . "-".$current_provider."-".$current_policy_date;

					 Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							'current_provider' => $current_provider,
							'current_policy_date' => $current_policy_date,
						]);

					// exit;
				}
				else

				{
					$transfer = "No";
					Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							//'current_provider' => $current_provider,
							//'current_policy_date' => $current_policy_date,
						]);
				}
				
			}

			if($product_id=="38")
				{
				if(isset($post_data['transfer_insurer_incomebee']) && $post_data['transfer_insurer_incomebee']!="")
				{
					 $transfer = "Yes";
				 	$current_provider = ($post_data['transfer_insurer_incomebee'] != '' ? $post_data['transfer_insurer_incomebee'] : '');
					 $current_policy_date = ($post_data['transfer_insurance_startdate_incomebee'] != '' ? $post_data['transfer_insurance_startdate_incomebee'] : '');

					// echo $transfer . "-".$current_provider."-".$current_policy_date;

					 Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							'current_provider' => $current_provider,
							'current_policy_date' => $current_policy_date,
						]);

					// exit;
				}
				else

				{
					$transfer = "No";
					Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'transfer' => $transfer,
							//'current_provider' => $current_provider,
							//'current_policy_date' => $current_policy_date,
						]);
				}
				
			}
		// Update the date and time in information table -- start
		Information::where('quote_id', $post_data['hidden_quote_id'])
			->update([
				'date_added' => date("Y-m-d"),
				'time_added' => date("H:i:s"),
			]);
		// Update the date and time in information table -- end

		if (!$saved_status) {
			Session::flash('failure', 'There was a problem. Please try again later.');
			return back()->withInput();
		} else {
			return redirect('bank-details/' . encryptUrl($post_data['hidden_quote_id']));
		}
		/*
			        echo "<pre>";
			         print_r($product_conditions);
			        print_r($post_data);
			        exit;
		*/

	}

	// Check the cover page validations
	public function getProductConditions(Request $request) {
		if ($request->ajax()) {
			$product_id = (int) $request->product_id;
			$cover_type = $request->cover_type;
			parse_str($request->formdata, $form_data);
			//$form_data = json_encode($form_data);
			$product_conditions = DB::table('product_conditions')
				->where('product_id', $product_id)
				->where('cover_type', $cover_type)
				->first();
			$product_conditions = (array) $product_conditions;

			foreach ($product_conditions as $key1 => $value1) {
				foreach ($form_data as $key2 => $value2) {
					if (($value1 != "-") && ($key1 === $key2) && ($value1 != $value2) && ($value1 != '')) {
						//echo $product_conditions[$key1 . '_fail_msg'];

						echo 'We are sorry, you are not eligible for this policy. Please call us on 0330 330 9465 or email info@bestinsurance.co.uk and one of our specialists will be able to discuss your options and find the right policy for you';

						exit;
					}
				}
			}
		}
	}

	// search the products in product list page
	public function productSearch(Request $request) {
		if ($request->ajax()) {
			$post_data = $request->all();
			// Remove all white spaces before validating data

			array_map('trim', $request->all());
			$qid = (int) decryptUrl($post_data['quote_id']);

			$excess_period = trim($post_data['excess_period']);
			// For AS products
			if ($excess_period == 28) {
				$excess_period = 30;
			}
			if ($excess_period == 56) {
				$excess_period = 60;
			}
			$excess_period_for_new_prod = trim($post_data['excess_period']);
			$quote_update_status = quotes::where('id', $qid)
				->update([
					'cover_type' => $post_data['cover_type'],
					'excess_period' => $excess_period,
					'monthly_benifit_amount' => $post_data['benifit_amount'],
				]);
			$saved = Information::where('quote_id', $qid)
				->update([
					'typeofcover' => $post_data['cover_type'],
					'excessperiod' => $excess_period,
					'monthlybenefit' => $post_data['benifit_amount'],
					'benefit_period' => ((isset($post_data['benifit_period']) && $post_data['benifit_period'] != '') ? $post_data['benifit_period'] : 0),
				]);

			$quote_details = CommonComponent::getQuoteDetails($qid);
			$information_data = Information::where('quote_id', '=', $qid)->first();

			//  print_r($quote_details);
			// exit;
			// Pass the data into webline api

			$monthly_gross_income = (int) $quote_details['monthly_gross_income'];
			//$annual_earnings = $monthly_gross_income*12;
			$annual_earnings = $monthly_gross_income;
			$monthly_benifit_ammount = (int) $quote_details['monthly_benifit_amount'];

			/*
				                            1 day = 2048
				                            1 week = 4096
				                            4 weeks = 1
				                            8 weeks = 2
				                            13 weeks = 4
				                            26 weeks = 8
				                            52 weeks = 16
				                            56 weeks = 32
				                            104 weeks = 64
				                            112 weeks = 128
			*/
			switch ($excess_period) {
			case 1:
				$DefermentOpts = 2048;
				break;
			case 7:
				$DefermentOpts = 4096;
				break;
			case 28:
			case 30:
				$DefermentOpts = 1;
				break;
			case 56:
			case 60:
				$DefermentOpts = 2;
				break;
			case 91:
				$DefermentOpts = 4;
				break;
			case 182:
				$DefermentOpts = 8;
				break;
			case 364:
				$DefermentOpts = 16;
				break;
			case 392:
				$DefermentOpts = 32;
				break;
			case 728:
				$DefermentOpts = 64;
				break;
			case 784:
				$DefermentOpts = 128;
				break;
			default:
				$DefermentOpts = 1;
			}
			if ($post_data['cover_type'] == 'AS') {

				$ceaseAge = $quote_details['cease_cover'];
				$txtTermYears = $quote_details['term_in_year'];
				if ($ceaseAge != '') {
					$txtTermYears = -1;
				} else if ($txtTermYears != '') {
					$ceaseAge = -1;
				}
			} else {
				$ceaseAge = -1;
				$txtTermYears = -1;
			}

		/*	$webline_post_data = array(
				"txtWeblineNumber" => Config::get('constant.WEBLINENUMBER'),
				"txtUsername" => Config::get('constant.WEBLINEUSERNAME'),
				"txtPassword" => Config::get('constant.WEBLINEPASSWORD'),
				"txtOriginator" => Config::get('constant.WEBLINEORIGINATOR'),

				"txtSex" => $information_data->gender,
				"txtDOB" => $quote_details['dob'] . 'T12:00:00',
				"txtSmoker" => $information_data->smoker,
				"txtTitle" => $information_data->title,
				"txtFirstName" => $information_data->fname,
				"txtSurname" => $information_data->lname,
				"txtOccupation" => $quote_details['occupation_name'],
				"txtOccCode" => (string) $quote_details['occupation_code'],
				"txtOccClass" => (string) $quote_details['class'],
				"txtAnnualEarnings" => $annual_earnings,

				"txtPremiumFrequency" => 'Monthly',
				"txtBenefit" => $monthly_benifit_ammount,
				"txtIncreasingBenefit" => $information_data->increasing_benefit,
				'CeaseAge' => $ceaseAge,
				"txtTermYears" => $txtTermYears,
				"txtRevRts" => 'Both',
				'DefermentOpts' => $DefermentOpts,

				"quot_id" => $qid,
			);

			$webline_post_data = array(
				"sex" => $information_data->gender,
				"dob" => $quote_details['dob'],
				"smoker" => $information_data->smoker,
				"title" => $information_data->title,
				"forename" => $information_data->fname,
				"surname" => $information_data->lname,
				"earnings" => $annual_earnings,
				"term" => $txtTermYears,
				"frequency" => 'Monthly',
				"benefit" => $monthly_benifit_ammount,
				"quot_id" => $qid,
			);

			DB::table('temp_quot_webline_products')->where('QuoteId', '=', $qid)->delete();
			DB::table('temp_quot_webline_documents')->where('QuoteId', '=', $qid)->delete();
			*/
			if (Auth::check() && Auth::user()->role == 2) {
				//Default Affiliate uid
				$uid = Config::get('constant.BI_UID');
			} elseif (Auth::check()) {
				/*$affiliate_data = DB::table('users')
					                    ->join('affiliate_users','affiliate_users.user_id','=','users.id')
					                    ->join('affiliates','affiliates.id','=','affiliate_users.affiliate_id')
					                    ->where('users.id', '=', Auth::user()->id)
					                    ->select('affiliates.uid')
				*/

				$uid = Auth::user()->uid;

			} else {
				//Default Affiliate uid
				$uid = Config::get('constant.BI_UID');
			}

			// If cover type equals Accidence and Sickness to then only call the webline api
			/*if ($post_data['cover_type'] == 'AS' || $post_data['cover_type'] == '') {
				// check the webline products or not based on Affiliate id
				$status_check = CommonComponent::checkWeblineBasedonAffiliate($uid);
				if ($status_check != 0) {
					// CommonComponent::DoQuote($webline_post_data);
					$webline_service = new WeblineController();
					$webline_service->getProducts($webline_post_data);
				}

			}*/

			echo true;
		} else {
			abort(404);
		}
	}
	// Bank details page
	public function bankDetails(Request $request) {
		try
		{
			if ($request->isMethod('post')) {
				$post_data = $request->all();
				array_map('trim', $post_data);
				// Validate the form data - start
				$rules['accountname1'] = 'required';
				$rules['accountnumber1'] = 'required|numeric';
				$rules['accountnumber2'] = 'required|numeric';
				$rules['accountnumber3'] = 'required|numeric';
				$rules['accountnumber4'] = 'required|numeric';
				$rules['accountnumber5'] = 'required|numeric';
				$rules['accountnumber6'] = 'required|numeric';
				$rules['accountnumber7'] = 'required|numeric';
				$rules['accountnumber8'] = 'required|numeric';

				$rules['sortcode1'] = 'required|numeric';
				$rules['sortcode2'] = 'required|numeric';
				$rules['sortcode3'] = 'required|numeric';
				$rules['sortcode4'] = 'required|numeric';
				$rules['sortcode5'] = 'required|numeric';
				$rules['sortcode6'] = 'required|numeric';

				/*$rules['iban'] = 'required';
					                $rules['bank'] = 'required';
					                $rules['bankbic'] = 'required';
					                $rules['branch'] = 'required';
					                $rules['branchbic'] = 'required';
					                $rules['town'] = 'required';
					                $rules['postcode'] = 'required';
				*/

				/* Direct debit dates not required for these two products, these are like webline products */
				if ($post_data['hidden_product_id'] == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $post_data['hidden_product_id'] == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {
					$post_data['directdebits'] = '';
					$post_data['preferreddate'] = '';
				} else {
					$rules['preferreddate'] = 'required';
				}

				/*echo '<pre>';
					                print_r($post_data['hidden_product_id']);
					                echo '</pre>';
				*/
				$validator = Validator::make($post_data, $rules);

				if ($validator->fails()) {
					return redirect()
						->back()
						->withErrors($validator)
						->withInput();
				}
				// Validate the form data - end
				$personal_data = Information::where(['quote_id' => $post_data['hidden_quote_id'], 'product_id' => $post_data['hidden_product_id']])->first();

				$product_details = DB::table('products')
					->where('id', $personal_data->product_id)
					->first();

				$accountnumber = $post_data['accountnumber1'] . $post_data['accountnumber2'] . $post_data['accountnumber3'] . $post_data['accountnumber4'] . $post_data['accountnumber5'] . $post_data['accountnumber6'] . $post_data['accountnumber7'] . $post_data['accountnumber8'];

				$sortcode = $post_data['sortcode1'] . $post_data['sortcode2'] . $post_data['sortcode3'] . $post_data['sortcode4'] . $post_data['sortcode5'] . $post_data['sortcode6'];

				//$new_policyno = CommonComponent::get_policy_no($product_id, $id);

				Information::where(['quote_id' => $post_data['hidden_quote_id'], 'product_id' => $post_data['hidden_product_id']])
					->update([
						'accountname' => $post_data['accountname1'],
						'accountname2' => $accountnumber,
						'sortcode' => $sortcode,
						'iban' => $post_data['iban'],
						'bank' => $post_data['bank'],
						'bankbic' => $post_data['bankbic'],
						'branch' => $post_data['branch'],
						'branchbic' => $post_data['branchbic'],
						'branch_address' => $post_data['address'],
						'town' => $post_data['town'],
						'bank_postcode' => $post_data['postcode'],
						'bank_phone' => $post_data['phone'],
						'directdebits' => $post_data['directdebits'],
						'preferreddate' => $post_data['preferreddate'],

						'date_added' => date("Y-m-d"),
						'time_added' => date("H:i:s"),
					]);

				// Insert bank details into the CRM -- start
				/*$personal_data = Information::where('quote_id', '=', $post_data['hidden_quote_id'])->first();
	                $product_data = Product::where('id', '=', $personal_data->product_id)->first();

	                $quote_data = DB::table('quotes')
	                    ->join('industries', 'industries.id', '=', 'quotes.industry_type_id')
	                    ->join('occupations', 'occupations.id', '=', 'quotes.occupation_id')
	                    ->where('quotes.id', '=', $post_data['hidden_quote_id'])
	                    ->select('quotes.*', 'industries.industry_name', 'occupations.occupation_name')
	                    ->first();

*/
				// Insert bank details into the CRM -- start

				return redirect('bank-details-confirmation/' . encryptUrl($post_data['hidden_quote_id']));
			} else {
				$quote_id = (int) decryptUrl($request->quote_id);

				$information_data = Information::where('quote_id', '=', $quote_id)
					->where('accountnumber', '!=', '')
					->where('policy_number', '!=', '')
					->first();

				// print_r($information_data);

				// exit;
				if ($information_data) {

					return response()->view('errors.404-policy');
					exit;
				}

				if (isset($quote_id) && $quote_id != '') {
					// check the personal information id is exist or not
					$personal_data = Information::where('quote_id', '=', $quote_id)->first();
					if (isset($personal_data) && $personal_data != '') {
						// Get the product details
						$product_details = DB::table('products')
							->where('id', $personal_data->product_id)
							->first();

						// Get the quote information as array
						$quote_details = CommonComponent::getQuoteDetails($quote_id);
						$user_info = $this->__construct();

						// Generate the Application PDF -- start

						$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $personal_data->product_id);

						$affiliation_data = Affiliates::where('uid', $personal_data->affid)->first();
						$questions = CommonComponent::getProductQuestions($personal_data->product_id,$quote_details['cover_type']);

						$questions = (array) $questions;
						array_forget($questions, 'id');
						array_forget($questions, 'product_id');
						array_forget($questions, 'posted_datetime');
						array_forget($questions, 'cover_type');
						$questions = (object) $questions;

						$underwriting_questions_data = UnderwritingQuestions::where('quote_id', $personal_data->quote_id)->first();

						if ($affiliation_data != '') {
							$affiliatename = $affiliation_data['Legal_Entity'];
						} else {
							$affiliatename = 'Best Risk Management & Fin';
						}

						$typeofcover = $personal_data->typeofcover;
						switch ($typeofcover) {
						case 'ASU':
							$policy = "Unemployment, Accident & Sickness";
							break;

						case 'U':
							$policy = "Unemployment only";
							break;

						case 'AS':
							$policy = "Accident & Sickness only";
							break;

						}
						$excess = $personal_data->excessperiod;

						/*switch($excess)
							                        {
							                            case 1:
							                                $excess_period="Back to Day 1";
							                                break;

							                            case 30:
							                                $excess_period="30 Days";
							                                break;

							                            case 60:
							                                $excess_period="60 Days";
							                                break;
						*/
						if ($typeofcover == 'AS') {
							switch ($excess) {
							case 1:
								$excess_period = '1 Day';
								break;
							case 7:
								$excess_period = '1 Week';
								break;
							case 14:
								$excess_period = '2 weeks';
								break;
							case 28:
								$excess_period = '4 weeks';
								break;
							case 30:
								$excess_period = '30 Days';
								break;
							case 56:
								$excess_period = '8 weeks';
								break;
							case 60:
								$excess_period = '60 Days';
								break;
							case 91:
								$excess_period = '13 weeks';
								break;
							case 182:
								$excess_period = '26 weeks';
								break;
							case 364:
								$excess_period = '52 weeks';
								break;
							default:
								$excess_period = 1;
							}
						} else {
							switch ($excess) {
							case 1:
								$excess_period = "Back to Day 1";
								break;
							case 14:
								$excess_period = "14 Days";
								break;
							case 30:
								$excess_period = "30 Days";
								break;

							case 60:
								$excess_period = "60 Days";
								break;
							}
						}

						$add = "";
						if ($personal_data->premiseName != "") {
							$add .= $personal_data->premiseName . ", ";
						}
						if ($personal_data->address1 != "") {
							$add .= $personal_data->address1 . ", ";
						}
						if ($personal_data->address2 != "") {
							$add .= ", " . $personal_data->address2;
						}
						if ($personal_data->address3 != "") {
							$add .= ", " . $personal_data->address3;
						}
						if ($personal_data->address4 != "") {
							$add .= ", " . $personal_data->address4;
						}

						if ($personal_data->postaltown != "") {
							$add .= ", " . $personal_data->postaltown;
						}

						if ($personal_data->county != "") {
							$add .= ", " . $personal_data->county;
						}

						if ($personal_data->postcode != "") {
							$add .= ", " . $personal_data->postcode;
						}

						$data = array(
							'product_details' => $product_details,
							'quote_details' => $quote_details,
							'personal_data' => $personal_data,
							'monthly_cost' => $monthly_cost,
							'policy' => $policy,
							'price' => number_format($monthly_cost, 2, '.', ''),
							'add' => $add,
							'affiliation_data' => $affiliation_data,
							'affiliatename' => $affiliatename,
							'questions' => $questions,
							'underwriting_questions' => $underwriting_questions_data,
							'excess_period' => $excess_period,
							'message' => 'is a trading name of Best Risk Management and Financial Service Limited who are authorised and regulated by the Financial Conducts Authority (FCA registration number 583497). Registered office is Gemini Business Centre, 136-140, Old Shoreham Road, Hove BN3 7BD (Registered No. 07095571)',

						);

						view()->share($data);
						$application_pdf_name = 'Application_' . time() . '_' . mt_rand() . '.pdf';

						if ($personal_data->product_id == Config::get('constant.EASIPROTECT') || $personal_data->product_id == Config::get('constant.KEYSTONE') || $personal_data->product_id == Config::get('constant.KEYSTONE_18M') || $personal_data->product_id == Config::get('constant.HOMEOWNER') || $personal_data->product_id == Config::get('constant.ASSURITY')) {
							$application_pdf = PDF::loadView('slices.frontend.get-a-quot.easiprotect_application')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/application/' . $application_pdf_name);
						} elseif ($personal_data->product_id == Config::get('constant.SIMPLE_INCOME_INSURANCE_COVEA')) {
							$application_pdf = PDF::loadView('slices.frontend.get-a-quot.application_pdf_simple_covea')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/application/' . $application_pdf_name);
						} else {
							$application_pdf = PDF::loadView('slices.frontend.get-a-quot.application_pdf')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/application/' . $application_pdf_name);
						}

						$quote_pdf_data = QuotePdf::where(['quote_id' => $quote_id])->first();

						if (isset($quote_pdf_data->application_pdf) && $quote_pdf_data->application_pdf != '') {
							if (file_exists(public_path() . '/uploads/pdf/application/' . $quote_pdf_data->application_pdf)) {
								unlink(public_path() . '/uploads/pdf/application/' . $quote_pdf_data->application_pdf);
							}
						}
						// Update the record
						QuotePdf::where(['quote_id' => $quote_id])
							->update([
								'application_pdf' => $application_pdf_name,
							]);
						// Generate the Application PDF -- end

						return view('frontend.bank_details', [
							'product_details' => $product_details,
							'quote_details' => $quote_details,
							"personal_data" => $personal_data,
							'user_info' => $user_info,
							'bank_details_page' => 'yes',
						]);
					} else {
						abort(404);
					} // quote data check else end
				} else {
					abort(404);
				}
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Validate bank account details
	public function bankAccountValidate(Request $request) {
		if ($request->ajax()) {
			$post_data = $request->all();
			$accountnumber = $post_data['accountnumber'];
			$sortcode = $post_data['sortcode'];

			//$Key='GY18-TA83-EN81-FC58';
			$Key = 'JE96-GY88-CF76-HT79';

			//Build the url
			$url = "https://services.postcodeanywhere.co.uk/BankAccountValidation/Interactive/Validate/v1.00/json.ws?";
			$url .= "&Key=" . urlencode($Key);
			$url .= "&AccountNumber=" . urlencode($accountnumber);
			$url .= "&SortCode=" . urlencode($sortcode);

			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$data = curl_exec($ch);
			curl_close($ch);

			return json_encode($data);
		}
	}

	// Bank details confirmation page
	public function bankDetailsConfirmation(Request $request) {

		try
		{
			if ($request->isMethod('post')) {

				$post_data = $request->all();

				array_map('trim', $post_data);

				$personal_data = Information::where(['quote_id' => $post_data['hidden_quote_id'], 'product_id' => $post_data['hidden_product_id']])->first();

				$product_details = DB::table('products')
					->where('id', $personal_data->product_id)
					->first();

				//print_r($post_data);

				//  exit;

				if ($post_data['hidden_product_id'] == Config::get('constant.BEST_INSURANCE_COVEA') || $post_data['hidden_product_id'] == Config::get('constant.BEST_INSURANCE_ULTRA_COVEA') || $post_data['hidden_product_id'] == Config::get('constant.SIMPLE_INCOME_INSURANCE_COVEA')) {
					$new_policyno = CommonComponent::get_policy_no_covea($post_data['hidden_product_id'], $personal_data->id);
				} else {
					$new_policyno = CommonComponent::get_policy_no($post_data['hidden_product_id'], $personal_data->id);
				}

				if ($post_data['hidden_product_id'] == Config::get('constant.BEST_INCOME_GUARD_120') || $post_data['hidden_product_id'] == Config::get('constant.BEST_INCOME_GUARD_90')) {
					$policy_number_full = $product_details->policy_prefix . $new_policyno . "MMS";
				} else {
					$policy_number_full = $product_details->policy_prefix . $new_policyno;
				}

				$communication = "";

				if (isset($post_data['communication_email'])) {
					$communication = $post_data['communication_email'] . "|";
				}

				if (isset($post_data['communication_phone'])) {
					$communication .= $post_data['communication_phone'] . "|";
				}

				if (isset($post_data['communication_message'])) {
					$communication .= $post_data['communication_message'] . "|";
				}

				if (isset($post_data['communication_post'])) {
					$communication .= $post_data['communication_post'] . "|";
				}

				if (isset($post_data['communication_none'])) {
					$communication .= $post_data['communication_none'];
				}

				if ($communication == "") {
					$communication = "None";
				}

				Information::where(['quote_id' => $post_data['hidden_quote_id'], 'product_id' => $post_data['hidden_product_id']])
					->update([
						'marketingOptOut' => $communication,
						'accountnumber' => $personal_data->accountname2,
						'policy_number' => $new_policyno,

						'policy_number_full' => $policy_number_full,
						'customer_status' => 'Submitted',

					]);
				//$log_id = $this->helper->insertLogInfo($request->id);
				$personal_data = Information::where('quote_id', '=', $post_data['hidden_quote_id'])->first();
				// Get the product details
				$product_details = DB::table('products')
					->where('id', $personal_data->product_id)
					->first();
				$log_id = $this->helper->insertLogInfo($personal_data->id);
				// Get the quote information as array
				$quote_details = CommonComponent::getQuoteDetails($post_data['hidden_quote_id']);
				$monthly_cost = CommonComponent::getQuoteProductCost($post_data['hidden_quote_id'], $personal_data->product_id);

				$affiliation_data = Affiliates::where('uid', $personal_data->affid)->first();

				$questions = CommonComponent::getProductQuestions($personal_data->product_id,$quote_details['cover_type']);

				$questions = (array) $questions;
				array_forget($questions, 'id');
				array_forget($questions, 'product_id');
				array_forget($questions, 'posted_datetime');
				array_forget($questions, 'cover_type');
				$questions = (object) $questions;

				$underwriting_questions_data = UnderwritingQuestions::where('quote_id', $personal_data->quote_id)->first();

				if ($affiliation_data != '') {
					$affiliatename = $affiliation_data['Legal_Entity'];
				} else {
					$affiliatename = 'Best Risk Management & Fin';
				}

				$typeofcover = $personal_data->typeofcover;
				switch ($typeofcover) {
				case 'ASU':
					$policy = "Unemployment, Accident & Sickness";
					break;

				case 'U':
					$policy = "Unemployment";
					break;

				case 'AS':
					$policy = "Accident & Sickness";
					break;

				}
				$excess = $personal_data->excessperiod;
				switch ($excess) {
				case 1:
					$excess_period = "Back to Day 1";
					break;
				case 14:
					$excess_period = "14 Days";
					break;
				case 30:
					$excess_period = "30 Days";
					break;
				case 60:
					$excess_period = "60 Days";
					break;
				}

				$add = "";
				if ($personal_data->premiseName != "") {
					$add .= $personal_data->premiseName . ", ";
				}
				if ($personal_data->address1 != "") {
					$add .= $personal_data->address1 . ", ";
				}
				if ($personal_data->address2 != "") {
					$add .= $personal_data->address2 . ", ";
				}
				if ($personal_data->county != "") {
					$add .= $personal_data->county;
				}

				$quote_pdf_data = QuotePdf::where(['quote_id' => $post_data['hidden_quote_id']])->first();

				// Check whether application and quote pdf's are empty or not -- If both are not empty then final email should send with out generating new pdf's

				if (!isset($quote_pdf_data->application_pdf) && $quote_pdf_data->application_pdf == '' && !isset($quote_pdf_data->quote_pdf) && $quote_pdf_data->quote_pdf == '') {
					$data = array(
						'product_details' => $product_details,
						'quote_details' => $quote_details,
						'personal_data' => $personal_data,
						'monthly_cost' => $monthly_cost,
						'policy' => $policy,
						'price' => number_format($monthly_cost, 2, '.', ''),
						'add' => $add,
						'affiliation_data' => $affiliation_data,
						'affiliatename' => $affiliatename,
						'questions' => $questions,
						'underwriting_questions' => $underwriting_questions_data,
						'excess_period' => $excess_period,
						'message' => 'is a trading name of Best Risk Management and Financial Services Limited who are authorised and regulated by the Financial Conducts Authority (FCA registration number 583497). Registered office is Gemini Business Centre, 136-140, Old Shoreham Road, Hove BN3 7BD (Registered No. 07095571)',

					);

					// Application PDF generation
					if ($product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {

					} else {
						if (!isset($quote_pdf_data->application_pdf) && $quote_pdf_data->application_pdf == '') {
							view()->share($data);
							$application_pdf_name = 'Application_' . time() . '_' . mt_rand() . '.pdf';

							if ($personal_data->product_id == EASIPROTECT || $personal_data->product_id == KEYSTONE || $personal_data->product_id == KEYSTONE_18M || $personal_data->product_id == HOMEOWNER || $personal_data->product_id == ASSURITY) {
								$application_pdf = PDF::loadView('slices.frontend.get-a-quot.easiprotect_application')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/application/' . $application_pdf_name);
							} else {
								$application_pdf = PDF::loadView('slices.frontend.get-a-quot.application_pdf')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/application/' . $application_pdf_name);
							}
							// Update the record
							QuotePdf::where(['quote_id' => $post_data['hidden_quote_id']])
								->update([
									'application_pdf' => $application_pdf_name,
								]);
						}

					}
				}

				// Quote PDF generation
				if (!isset($quote_pdf_data->quote_pdf) && $quote_pdf_data->quote_pdf == '') {

					view()->share($data);
					$quote_pdf_name = 'Quote_' . time() . '_' . mt_rand() . '.pdf';
					print_r('dfg');
					if ($product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {

						return view('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration', compact('data'));

						$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
					} else {

						if ($personal_data->product_id == EASIPROTECT || $personal_data->product_id == KEYSTONE || $personal_data->product_id == KEYSTONE_18M || $personal_data->product_id == HOMEOWNER || $personal_data->product_id == ASSURITY) {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.easiprotect_quote')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						} else {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.quote_pdf')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						}
					}

					// Update the record
					QuotePdf::where(['quote_id' => $post_data['hidden_quote_id']])
						->update([
							'quote_pdf' => $quote_pdf_name,
						]);
				}

				// End -- PDF's generation (quote and application if not exist in table)
				// New product PDF -- start
				if ($personal_data->product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $personal_data->product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {

					$underwriting_questions = CommonComponent::getWeblineQuestions();

					$questions = (array) $underwriting_questions;
					array_forget($questions, 'id');
					array_forget($questions, 'created');
					$questions = (object) $questions;

					$where_array = array(
						'quote_id' => $post_data['hidden_quote_id'],
					);

					$answers = CommonComponent::getWeblineQuestionAnswers($where_array);

					$data = array(
						'questions' => $questions,
						'answers' => $answers,
					);
					view()->share($data);
					$webline_questions_pdf_name = 'Webline_questions_' . time() . '_' . mt_rand() . '.pdf';
					$webline_questions_pdf = PDF::loadView('slices.frontend.get-a-quot.web-api-pages.questions_pdf')->setPaper('a4', 'portrait')->save(public_path() . '/uploads/pdf/admin/' . $webline_questions_pdf_name);
					DB::table('quote_pdfs')
						->where('quote_id', $post_data['hidden_quote_id'])
						->update(['webline_questions_pdf' => $webline_questions_pdf_name]);
				} else {
					$webline_questions_pdf_name = '';
				}
				// New product PDF -- End

				$quote_pdf_data = QuotePdf::where('quote_id', '=', $post_data['hidden_quote_id'])->first();

				if ($product_details->intial_disclosure_doc == "") {
					$disclosure_doc = public_path() . '/assets/policydocuments/BestIDDwithSoDaNLTIP.pdf';
				} else {
					$disclosure_doc = public_path() . '/assets/policydocuments/' . $product_details->intial_disclosure_doc;
				}

				$personal_data = Information::where('quote_id', '=', $post_data['hidden_quote_id'])->first();

				$marketing_communication = $communication;

				/* if(isset($post_data['email']))
					                   $marketing_communication="Email";
					                if(isset($post_data['phone']))
					                   $marketing_communication="Phone";

					               if(isset($post_data['text_message']))
					                   $marketing_communication="Text message";

					               if(isset($post_data['post']))
				*/

				//echo "hello".$marketing_communication;
				//exit;
				$personal_data->marketing_communication = $marketing_communication;
				$product_data = Product::where('id', '=', $personal_data->product_id)->first();

				$quote_data = DB::table('quotes')
					->join('industries', 'industries.id', '=', 'quotes.industry_type_id')
					->join('occupations', 'occupations.id', '=', 'quotes.occupation_id')
					->where('quotes.id', '=', $post_data['hidden_quote_id'])
					->select('quotes.*', 'industries.industry_name', 'occupations.occupation_name')
					->first();
				/* CRM start*/
				$broker_firm = "Best Risk Management & Financial Service Limited";

				$broker_user = "Best Advisor";

				$affiliate_data = Affiliates::where(['uid' => $personal_data['affid']])->first();
				if (Auth::user()) {
					$branch_data = Branch::find(Auth::user()->branch_id);
				}

				// print_r($branch_data);

				if (Auth::user()) {
					$user_info = UserInfo::where(['user_id' => Auth::user()->id])->first();
				}

				if (Auth::user()) {
					$broker_firm = $branch_data->branch_name;
				}

				//print_r($user_info);
				//$broker_user=
				// echo $broker_firm;
				if (Auth::user()) {
					$broker_user = $user_info->first_name . " " . $user_info->last_name;
				}

				// echo $broker_user;

				// exit;

				$crm_response = CommonComponent::insertPersonalDataIntoCRM($personal_data, $quote_data, $product_data, $affiliate_data, $broker_user, $broker_firm);

				//dd($crm_response);

				if ($crm_response['id'] == -1) {
					$Mail_subject = array(
						'personal_data' => $personal_data,
						'product_data' => $product_data,
					);
					$mailsent = Mail::send(['html' => 'auth.emails.crm-disconnected-mail'], $Mail_subject, function ($message) use ($Mail_subject, $personal_data) {
						$message->from('info@bestinsurance.co.uk', 'info@bestinsurance.co.uk');
						// $message->to('chamundeswari.somu@quadone.com')->subject('New policy details from '.$personal_data->fname);

						$message->to('admin@bestinsurance.co.uk')->subject('New policy details from ' . $personal_data->fname);
					});
				} else {
					$rid = $crm_response['id'];
					$personaldata_update_status = Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'crm_id' => $rid,
						]);

					$personal_data = Information::where('quote_id', '=', $post_data['hidden_quote_id'])->first();

					$crm_response = CommonComponent::insertBankDataIntoCRM($personal_data, $quote_data, $product_data);

					$rid = $crm_response['id'];
					$personaldata_update_status = Information::where('quote_id', $post_data['hidden_quote_id'])
						->update([
							'crm_id' => $rid,
						]);
				}
				/* CRM end */

				// Insert bank details into the CRM -- end

				$email_data = array(
					'monthly_cost' => $monthly_cost,
					'personal_data' => $personal_data,
					'name' => $personal_data->fname,
					'email' => $personal_data->email,
					'policy' => $policy,
					'product_id' => $personal_data->product_id,
					'subject' => "Dear " . $personal_data->fname . ", Thank You for your Application",
					'price' => number_format($monthly_cost, 2, '.', ''),
					'add' => $add,
					'application_pdf' => public_path() . '/uploads/pdf/application/' . $quote_pdf_data->application_pdf,
					'quote_pdf' => public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf,
					'policy_wordings_doc' => public_path() . '/assets/policydocuments/' . $product_details->policy_wordings_doc,
					'keyfacts_doc' => public_path() . '/assets/policydocuments/' . $product_details->keyfacts_doc,
					'webline_questions_pdf' => public_path() . '/uploads/pdf/admin/' . $webline_questions_pdf_name,

					'Terms_of_business' => public_path() . '/assets/policydocuments/Terms_of_business.pdf',

					//   if()

					// 'bestidd_pdf' => public_path().'/assets/policydocuments/BestIDDwithSoDaNASU.PDF',

				);

				$mailSuccess = Mail::send(['html' => 'slices.frontend.get-a-quot.quote_email'], $email_data, function ($message) use ($email_data) {
					$message->from('advisor@bestinsurance.co.uk', 'advisor@bestinsurance.co.uk ');
					$message->to($email_data['email'])->subject($email_data['subject']);
					$message->bcc('info@bestinsurance.co.uk');
					$message->bcc('archive@bestinsurance.co.uk');
					// $message->bcc('kesh@bestinsurance.co.uk');
					//$message->bcc('sboseley@bestinsurance.co.uk');
					if ($email_data['product_id'] == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $email_data['product_id'] == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {
						$message->attach($email_data['webline_questions_pdf']);
					} else {
						$message->attach($email_data['application_pdf']);

					}

					/*if(Config::get('constant.SIMPLE_INCOME'))
						                    {
						                        //echo "hi";
						                    }
						                    else

					*/
					$message->attach($email_data['policy_wordings_doc']);
					$message->attach($email_data['keyfacts_doc']);
					$message->attach($email_data['quote_pdf']);
					$message->attach($email_data['Terms_of_business']);

					// }

				});

				if ($mailSuccess) {

					return redirect('quote-confirmation/' . encryptUrl($post_data['hidden_quote_id']));
				} else {
					Session::flash('failure', 'There was a problem. Please try again later.');
					return back()->withInput();
				}

			} else {
				$quote_id = (int) decryptUrl($request->quote_id);

				/* $information_data = Information::where('quote_id', '=', $quote_id)
					                ->where('accountnumber','!=','')
					                ->where('policy_number','!=','')
					                ->first();

					               // print_r($information_data);

					               // exit;
					                if($information_data)
					                {

					                    return response()->view('errors.404-policy');
					                    exit;
				*/

				if (isset($quote_id) && $quote_id != '') {
					// check the personal information id is exist or not
					$personal_data = Information::where('quote_id', '=', $quote_id)->first();
					if (isset($personal_data) && $personal_data != '') {
						// Get the product details
						$product_details = DB::table('products')
							->where('id', $personal_data->product_id)
							->first();

						// Get the quote information as array
						$quote_details = CommonComponent::getQuoteDetails($quote_id);
						$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $personal_data->product_id);
						$user_info = $this->__construct();

						// Get the quote information as array
						// $quote_details = CommonComponent::getQuoteDetails($quote_id);

						if ($quote_details['cover_type'] == "U") {
							$cover_type = "Unemployment only";
						} else if ($quote_details['cover_type'] == "AS") {
							$cover_type = "Accident & Sickness only";
						} else {
							$cover_type = "Unemployment, Accident & Sickness";
						}
						//Fetch Product Details
						$product_dtls = CommonComponent::getProductDetails($personal_data->product_id);
						return view('frontend.bank_details_confirmation', [
							'product_details' => $product_details,
							'quote_details' => $quote_details,
							"personal_data" => $personal_data,
							'monthly_cost' => $monthly_cost,
							'user_info' => $user_info,
							'bank_details_confirmation_page' => 'yes',
							'cover_type' => $cover_type,
							// 'quote_details' => $quote_details,
							'monthly_cost' => $monthly_cost,
							'insurer' => $product_dtls['insurer'],
						]);
					} else {
						abort(404);
					} // quote data check else end
				} else {
					abort(404);
				}
			}
		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	// Quote confirmation page
	public function quoteConfirmation(Request $request) {
		try
		{
			$quote_id = (int) decryptUrl($request->quote_id);
			if (isset($quote_id) && $quote_id != '') {
				// check the personal information id is exist or not
				$personal_data = Information::where('quote_id', '=', $quote_id)->first();
				if (isset($personal_data) && $personal_data != '') {
					// Get the product details
					$product_details = DB::table('products')
						->where('id', $personal_data->product_id)
						->first();

					// Get the quote information as array
					$quote_details = CommonComponent::getQuoteDetails($quote_id);
					$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $personal_data->product_id);
					$quote_pdf_data = QuotePdf::where('quote_id', '=', $quote_id)->first();
					$user_info = $this->__construct();
					// echo '<pre>';
					// print_r($quote_pdf_data);
					// echo '</pre>';
					// exit;

					return view('frontend.quote_details_confirmation', [
						'product_details' => $product_details,
						'quote_details' => $quote_details,
						"personal_data" => $personal_data,
						'monthly_cost' => $monthly_cost,
						'quote_pdf_data' => $quote_pdf_data,
						'user_info' => $user_info,
						'quote_confirmation_page' => 'yes',
					]);
				} else {
					abort(404);
				} // quote data check else end
			} else {
				abort(404);
			}

		} catch (Exception $e) {
			echo 'Caught exception: ', $e->getMessage(), "\n";
			//TODO:: Log the error somewhere
		}
	}

	public function quoteDetailsConfirmation(Request $request) {

		if ($request->isMethod('post')) {

			return redirect('/');
		}
	}

	// Print the bank details
	public function bankDetailsPrint(Request $request) {
		$quote_id = (int) $request->quote_id;
		if (isset($quote_id) && $quote_id != '') {
			// check the personal information id is exist or not
			$personal_data = Information::where('quote_id', '=', $quote_id)->first();
			if (isset($personal_data) && $personal_data != '') {
				// Get the product details
				$product_details = DB::table('products')
					->where('id', $personal_data->product_id)
					->first();

				// Get the quote information as array
				$quote_details = CommonComponent::getQuoteDetails($quote_id);
				$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $personal_data->product_id);
				$user_info = $this->__construct();

				return view('frontend.bank-details-print', [
					'product_details' => $product_details,
					'quote_details' => $quote_details,
					"personal_data" => $personal_data,
					'monthly_cost' => $monthly_cost,
					'user_info' => $user_info,
				]);
			} else {
				abort(404);
			} // quote data check else end
		}
	}

	/**
	 * Download pdf for quote illustration
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function downloadQuoteIllustration($quote_id,$product_id,$excess_period) {
		//PDF file is stored under project/public/download/info.pdf

	//	dd($product_id);

	if ($excess_period == 28) {
		$excess_period = 30;
	} elseif ($excess_period == 56) {
		$excess_period = 60;
	} else {
		$excess_period = $excess_period;
	}


	Information::where(['quote_id' =>  $quote_id])
	->update([
		'excessperiod' => $excess_period,
	
	]);

	Quotes::where(['id' =>  $quote_id])
	->update([
		'excess_period' => $excess_period,
	
	]);


		$personal_data = Information::where('quote_id', '=', $quote_id)->first();
		$quote_details = CommonComponent::getQuoteDetails($quote_id);
		$product_details = DB::table('products')
								->where('id', $product_id)
								->first();
		$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $product_id);

		$affiliation_data = Affiliates::where('uid', $personal_data->affid)->first();
		if ($affiliation_data != '') {
						$affiliatename = $affiliation_data['Legal_Entity'];
					} else {
						$affiliatename = 'Best Risk Management & Fin';
					}

		$typeofcover = $personal_data->typeofcover;
					switch ($typeofcover) {
					case 'ASU':
						$policy = "Unemployment, Accident & Sickness";
						break;

					case 'U':
						$policy = "Unemployment only";
						break;

					case 'AS':
						$policy = "Accident & Sickness only";
						break;

					}

		$excess = $quote_details['excess_period'];
					// print_r($excess);

					if ($product_id == 15 || $product_id == 14) {
						switch ($excess) {
						case 1:
							$excess_period = 'Back to day 1';
							break;
						case 7:
							$excess_period = '1 Week';
							break;
						case 14:
							$excess_period = '2 weeks';
							break;
						case 28:
							$excess_period = '4 weeks';
							break;
						case 30:
							$excess_period = '30 Days';
							break;
						case 56:
							$excess_period = '8 weeks';
							break;
						case 60:
							$excess_period = '60 Days';
							break;
						case 91:
							$excess_period = '13 weeks';
							break;
						case 182:
							$excess_period = '26 weeks';
							break;
						case 364:
							$excess_period = '52 weeks';
							break;
						default:
							$excess_period = 'Back to day 1';
						}
					} else {
						switch ($excess) {
						case 1:
							$excess_period = "Back to Day 1";
							break;
						case 14:
							$excess_period = "14 Days";
							break;
						case 30:
							$excess_period = "30 Days";
							break;

						case 60:
							$excess_period = "60 Days";
							break;
						}
					}


		$add = "";
					if ($personal_data->premiseName != "") {
						$add .= $personal_data->premiseName . ", ";
					}
					if ($personal_data->address1 != "") {
						$add .= $personal_data->address1;
					}
					if ($personal_data->address2 != "") {
						$add .= ", " . $personal_data->address2;
					}
					if ($personal_data->address3 != "") {
						$add .= ", " . $personal_data->address3;
					}
					if ($personal_data->address4 != "") {
						$add .= ", " . $personal_data->address4;
					}

					if ($personal_data->postaltown != "") {
						$add .= ", " . $personal_data->postaltown;
					}

					if ($personal_data->county != "") {
						$add .= ", " . $personal_data->county;
					}

					if ($personal_data->postcode != "") {
						$add .= ", " . $personal_data->postcode;
					}
					$data = array(
						'product_details' => $product_details,
						'quote_details' => $quote_details,
						'personal_data' => $personal_data,
						'monthly_cost' => $monthly_cost,
						'policy' => $policy,
						'price' => number_format($monthly_cost, 2, '.', ''),
						'add' => $add,
						//'affiliation_data' => $affiliation_data,
						'affiliatename' => $affiliatename,						
						'excess_period' => $excess_period,
						
					);

					view()->share($data);
					$quote_pdf_name = 'Quote_' . time() . '_' . mt_rand() . '.pdf';
					/*return view('slices.frontend.get-a-quot.quote_pdf');
                        exit;*/

					if ($product_id == Config::get('constant.SHEPHERDS_FRIENDLY_LONGTERM') || $product_id == Config::get('constant.SHEPHERDS_FRIENDLY_SHORTERM')) {

						// return view('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration', compact('data'));

						$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.shephered_frienddly_quote_illustaration', compact('data'))->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);

					} elseif ($product_id == Config::get('constant.SIMPLE_INCOME_INSURANCE_COVEA')) {
						$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.quote_pdf_simple_covea')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
					} else {
						if ($product_id == Config::get('constant.EASIPROTECT') || $product_id == Config::get('constant.KEYSTONE') || $product_id == Config::get('constant.KEYSTONE_18M') || $product_id == Config::get('constant.HOMEOWNER') || $product_id == Config::get('constant.ASSURITY')) {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.easiprotect_quote')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						} else {
							$quote_pdf = PDF::loadView('slices.frontend.get-a-quot.quote_pdf')->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path() . '/uploads/pdf/quote/' . $quote_pdf_name);
						}
					}

					$quote_pdf_data = QuotePdf::where(['quote_id' => $quote_id])->first();
					//$count = count($quote_pdf_data);
					if (empty($quote_pdf_data)) {
						// Insert the record
						$pdf_data = new QuotePdf;
						$pdf_data->quote_id = $quote_id;
						$pdf_data->quote_pdf = $quote_pdf_name;

						$pdf_data->save();

						//$inserted_id = $pdf_data->id;
					} else {
						// Delete the old record and update with new one
						if (file_exists(public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf)) {
							unlink(public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf);
						}
						QuotePdf::where('quote_id', $quote_id)
							->update([
								'quote_pdf' => $quote_pdf_name,
							]);
					}

		

		$quote_pdf_data = DB::table('quote_pdfs')->where('quote_id', $quote_id)->first();

		// echo '<pre>';
		// print_r();
		// exit;

		$file = public_path() . '/uploads/pdf/quote/' . $quote_pdf_data->quote_pdf;

		$headers = array(
			'Content-Type: application/pdf',
		);

		return Response::download($file, 'Quote-illustration.pdf', $headers);
	}

	/**
	 * Download pdf for quote illustration
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function downloadApplication(Request $request) {
		//PDF file is stored under project/public/download/info.pdf

		$quote_pdf_data = DB::table('quote_pdfs')->where('quote_id', $request->quote_id)->first();

		$file = public_path() . '/uploads/pdf/application/' . $quote_pdf_data->application_pdf;

		$headers = array(
			'Content-Type: application/pdf',
		);

		return Response::download($file, 'Application.pdf', $headers);
	}

	/*
		    * Update the email when onblur will occur in personal details page
	*/
	public function updateEmail(Request $request) {
		$email = trim($request->input('email'));
		$quot_id = trim($request->input('quot_id'));

		$status = Information::where('quote_id', $quot_id)
			->update([
				'email' => $email,
			]);
		return $status;
	}

	/*
		    * Update the phone number when onblur will occur in personal details page
	*/
	public function updatePhone(Request $request) {
		$telephone = trim($request->input('telephone'));
		$quot_id = trim($request->input('quot_id'));

		$status = Information::where('quote_id', $quot_id)
			->update([
				'telephone' => $telephone,
			]);
		return $status;
	}

	/*
		    * Quote continue redirection from dashboard to the perticular page -- Normal products
	*/
	public function quoteContinue(Request $request) {
		$quote_id = trim(decryptUrl($request->quote_id));
		$product_id = trim($request->product_id);

		//$personal_data = Information::where('quote_id', '=', $quote_id)->first();
		$underwriting_questions_data = UnderwritingQuestions::where('quote_id', $quote_id)->count();

		if ($underwriting_questions_data == 0) {
			return redirect('cover/' . encryptUrl($quote_id) . '/' . $product_id);
		} else {
			return redirect('bank-details/' . encryptUrl($quote_id));
		}
	}

	/*
		    * Quote continue redirection from dashboard to the perticular page -- webline products
	*/
	public function weblineQuoteContinue(Request $request) {
		$quote_id = trim(decryptUrl($request->quote_id));
		$product_id = trim($request->product_id);
		$type = trim($request->type);

		//$personal_data = Information::where('quote_id', '=', $quote_id)->first();
		$result = DB::table('webline_underwriting_question_answers')
			->where('quote_id', $quote_id)
			->count();

		if ($result == 0) {
			return redirect('webline-products/cover/' . $quote_id . '/' . $product_id . '/' . $type);
		} else {
			return redirect('webline-products/bank-details/' . $quote_id . '/' . $type);
		}
	}

	/**
	 * Print form in Bank details page for normal products and webline products
	 */
	public function printform($quote_id, $product_id, Request $request) {

		$product = CommonComponent::getProductDetails($product_id);

		return view('frontend.printform', compact('product', 'product_id', 'quote_id'));
	}

	/**
	 * confirmation page with out Bank details
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function bankDetailsConfirmationWithoutBankdetails($quote_id, $product_id, Request $request) {
		// $quote_id = (int)$request->quote_id;
		if (isset($quote_id) && $quote_id != '') {
			// check the personal information id is exist or not
			$personal_data = Information::where('quote_id', '=', $quote_id)->first();
			if (isset($personal_data) && $personal_data != '') {
				// Get the product details
				$product_details = DB::table('products')
					->where('id', $personal_data->product_id)
					->first();

				// Get the quote information as array
				$quote_details = CommonComponent::getQuoteDetails($quote_id);
				$monthly_cost = CommonComponent::getQuoteProductCost($quote_id, $personal_data->product_id);
				$user_info = $this->__construct();

				if ($quote_details['cover_type'] == "U") {
					$cover_type = "Unemployment only";
				} else if ($quote_details['cover_type'] == "AS") {
					$cover_type = "Accident & Sickness only";
				} else {
					$cover_type = "Unemployment, Accident & Sickness";
				}
				//Fetch Product Details
				$product_dtls = CommonComponent::getProductDetails($personal_data->product_id);
				return view('frontend.bank-details-best-income-protection-without-confirm', [
					'product_details' => $product_details,
					'quote_details' => $quote_details,
					"personal_data" => $personal_data,
					'monthly_cost' => $monthly_cost,
					'user_info' => $user_info,
					'bank_details_confirmation_page' => 'yes',
					'cover_type' => $cover_type,
					// 'quote_details' => $quote_details,
					'monthly_cost' => $monthly_cost,
					'insurer' => $product_dtls['insurer'],
					'quote_id' => $quote_id,
					'product_id' => $product_id,
				]);
			} else {
				abort(404);
			} // quote data check else end
		} else {
			abort(404);
		}
	}

	/**
	 * Download cb Credit amount in bank details page
	 * @return [type] [description]
	 */
	public function downloadPaymentPage() {
		$file = public_path() . "/assets/policydocuments/CB_Credit_Agreement.pdf";
		$fileName = 'CB_Credit_Agreement.pdf';

		$headers = array(
			'Content-Type: application/pdf',
		);

		return Response::download($file, $fileName, $headers);
	}

	// quote summary page
	public function quoteSummary(Request $request) {
		$quote_id = decryptUrl($request->quote_id);
		if (isset($quote_id) && $quote_id != "") {
			//Fetch Quote Details
			$quote_dtls = array();
			$quote_dtls = CommonComponent::getQuoteInfoWithIndustryOccuparion($quote_id);

			if (count($quote_dtls) > 0) {
				//Quote Details
				$benifit_amount = $quote_dtls['monthly_benifit_amount']; // R5
				$cover_type = $quote_dtls['cover_type'];
				$excess_period = $quote_dtls['excess_period'];

				$grid_number = 1;
				$age = date_diff(date_create($quote_dtls['dob']), date_create('today'))->y;
				$term_in_year = $quote_dtls['term_in_year'] + $quote_dtls['age'];

				/* For webline products Cease or term ages between 65 to 70 then doesn't show normal products, below 65 only should show our products. */
				if ($cover_type == 'AS') {
					if (!empty($quote_dtls['cease_cover']) && $quote_dtls['cease_cover'] > 65) {
						$products_list = CommonComponent::getSheperdsProductsByRules($quote_id, array(), $grid_number);
					} elseif (!empty($quote_dtls['cease_cover']) && $quote_dtls['cease_cover'] <= 65) {

						$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);

					} elseif (!empty($quote_dtls['term_in_year']) && $term_in_year > 65) {

						$products_list = CommonComponent::getSheperdsProductsByRules($quote_id, array(), $grid_number);
					} elseif (!empty($quote_dtls['term_in_year']) && $term_in_year <= 65) {

						$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);
					} else {
						$products_list = '';
					}

				} else {
					$products_list = CommonComponent::getProductsByRules($quote_id, array(), $grid_number);
				}

				$products_list_webline = CommonComponent::getProductsWebline($quote_id);

				$information_data = Information::where('quote_id', '=', $quote_id)->first();

				if (isset($products_list) && $products_list != '' && $information_data->benefit_period != 0) {
					$res_count = count($products_list);
					for ($i = 0; $i < $res_count; $i++) {
						if ($products_list[$i]['product_benifit_period'] != $information_data->benefit_period) {
							unset($products_list[$i]);
						}

					}
					$products_list = array_values($products_list);
				}

				$user_info = $this->__construct();
				/*echo "<pre>";
					                print_r($information_data);
					                print_r($quote_dtls);
					                print_r($products_list);
					                print_r($products_list_webline);
				*/
				return view('frontend.quote_summary', [
					'information_data' => $information_data,
					'quote_dtls' => $quote_dtls,
					'quote_id' => $quote_id,
					'cover_type' => $quote_dtls['cover_type'],
					'excess_period' => $quote_dtls['excess_period'],
					'benifit_period' => $information_data->benefit_period,
					'benifit_amount' => $quote_dtls['monthly_benifit_amount'],
					'ajax_call_from' => 'add_quote',
					'products_list' => $products_list,
					'products_list_webline' => $products_list_webline,
					'user_info' => $user_info,
				]);
			} else {
				Session::flash('failure', 'Invalid quote');
				return redirect('get-a-quote');
				exit;
			}
		} else {
			Session::flash('failure', 'Invalid quote');
			return redirect('get-a-quote');
			exit;
		}

	}

}
