<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Controllers\FileController;
use App\Http\Controllers\HelperController;
use App\Http\Controllers\RAF\RAFController;
use App\Http\Requests\Backend\RAFWebHookMessageRequest;
use App\Information;
use App\Jobs\RAF\DocumentStatusCheckJob;
use App\LogInformation;
use App\MailTracker;
use App\Models\RAF\RAFLoanDocuments;
use App\Models\RAF\RAFLoan;
use App\Models\RAF\RAFWebHookMessage;
use Carbon\Carbon;
use DB;
use File;
use Illuminate\Http\Request;
use Storage;
use URL;

class DocVersionController extends Controller {
	function __construct() {
		$this->middleware('auth');
		$this->fileuploader = new FileController();
		$this->helper = new HelperController();
	}

	public function details($lead_id) {
		/*
			        $log_details = LogInformation::with('information.RAFCustomerInfo.raf_loan',
			                                'information.RAFCustomerInfo.raf_webhook_messages',
			                                'raf_docuemnts')
			                                ->where('application_id',$lead_id)
			                                ->orderBy('created_at','DESC')
			                                ->get();
			        dd($log_details->first()->information->RAFCustomerInfo->raf_webhook_messages);
		*/

		// Get all Log details
		$log_details = LogInformation::with('information.RAFCustomerInfo.raf_loan',
			'raf_docuemnts')
			->where('application_id', $lead_id)
			->orderBy('created_at', 'DESC')
			->get();

		if (@count($log_details) == 0) {
			$log_id = $this->helper->insertLogInfo($lead_id);
			$log_details = LogInformation::with('information.RAFCustomerInfo.raf_loan',
				'raf_docuemnts')
				->where('application_id', $lead_id)
				->orderBy('created_at', 'DESC')
				->get();
		}

		// Get all mail tracker details
		$mailtracker =
		MailTracker::where('mt_lead_id', $lead_id)->get();

		$information = Information::with('RAFCustomerInfo.raf_docuemnts')->find($lead_id);

		//Breadcrumb Titles
		$breadcrumb = [
			'title' => 'Document Versions',
			'subTitle' => 'Preview of completed lead',
			'home' => 'Leads',
			'homeLink' => '/account/leads?status=completed',
			'subHome' => 'Document Versions',
			'subHomeLink' => URL::to('account/leads?status=completed'),
			'subChildHome' => '',
			'menu' => 'completed-leads',
			'menuColor' => '#fff',
			'MenuClass' => 'active open',
			'SubMenuClass' => 'active',
		];
		$status = "";
		return view('admin.leads.version_doc_viewer', compact('breadcrumb', 'mailtracker', 'information', 'status', 'log_details'));
	}

	public function details_update($lead_id) {
		/*
			        $log_details = LogInformation::with('information.RAFCustomerInfo.raf_loan',
			                                'information.RAFCustomerInfo.raf_webhook_messages',
			                                'raf_docuemnts')
			                                ->where('application_id',$lead_id)
			                                ->orderBy('created_at','DESC')
			                                ->get();
			        dd($log_details->first()->information->RAFCustomerInfo->raf_webhook_messages);
		*/

		// Get all Log details
		/*$log_details = LogInformation::with('information.RAFCustomerInfo.raf_loan',
				'raf_docuemnts')
				->where('application_id', $lead_id)
				->orderBy('created_at', 'DESC')
				->get();*/


		$log_details_info=LogInformation::leftjoin('raf_customer_info','raf_customer_info.i_id','=','log_information.application_id')
					->leftjoin('raf_loan','raf_loan.CustomerId','=','raf_customer_info.id')
					->select('log_information.*','raf_loan.id as loanid','raf_customer_info.id as customerid')
					->where('log_information.application_id',$lead_id)
					->where('raf_loan.is_active',1)
					->orderBy('log_information.created_at', 'DESC')
					->get();
		
		if (@count($log_details_info) == 0) {
		$log_id = $this->helper->insertLogInfo($lead_id);
		$log_details_info=LogInformation::leftjoin('raf_customer_info','raf_customer_info.i_id','=','log_information.application_id')
					->leftjoin('raf_loan','raf_loan.CustomerId','=','raf_customer_info.id')
					->select('log_information.*','raf_loan.id as loanid','raf_customer_info.id as customerid')
					->where('log_information.application_id',$lead_id)
					->orderBy('log_information.created_at', 'DESC')
					->get();
		}

//dd($log_details_info);
		foreach($log_details_info as $log)
		{
			$data['policy_number_full']=$log->policy_number_full;
			$data['action']=$log->action;
			$data['status']=$log->status;
			$data['created_at']=$log->created_at;
			$data['reason']=$log->reason;
			$data['fname']=$log->fname;
			$data['is_bundled']=$log->is_bundled;
			$data['id']=$log->id;
			$data['customerid']=$log->customerid;
			$data['loanid']=$log->active_loan_id;
			$data['schedule_pdf']=$log->schedule_pdf;
			$data['customer_status']=$log->customer_status;

			$information['information']=$data;

			$documents=RAFLoanDocuments::where('log_info_id',$log->id)
			->select('s3_url','IsGenerated','Alias','id')
			->orderBy('CreatedDate')
			->get();
			$documents_array=[];
			foreach($documents as $document)
			{
				$doc['Alias']=$document->Alias;
				$doc['s3_url']=$document->s3_url;
				$doc['IsGenerated']=$document->IsGenerated;
				$doc['id']=$document->id;
				$documents_array[]=$doc;
			}

			$information['raf_documents']=$documents_array;
			
			$log_details[]=$information;
		}
			//dd($log_details);


		

		// Get all mail tracker details
		$mailtracker =
		MailTracker::where('mt_lead_id', $lead_id)->get();

	//	$information = Information::with('RAFCustomerInfo.raf_docuemnts')->find($lead_id);

		//Breadcrumb Titles
		$breadcrumb = [
			'title' => 'Document Versions',
			'subTitle' => 'Preview of completed lead',
			'home' => 'Leads',
			'homeLink' => '/account/leads?status=completed',
			'subHome' => 'Document Versions',
			'subHomeLink' => URL::to('account/leads?status=completed'),
			'subChildHome' => '',
			'menu' => 'completed-leads',
			'menuColor' => '#fff',
			'MenuClass' => 'active open',
			'SubMenuClass' => 'active',
		];
		$status = "";
		return view('admin.leads.version_doc_viewer_update', compact('breadcrumb', 'mailtracker', 'status', 'log_details'));
	}

	public function downloadRafVersion($raf_document_id) {
		$raf_doc = RAFLoanDocuments::where('id', $raf_document_id)->first();
		if (!empty($raf_doc)) {
			return $this->helper->download($raf_doc->s3_url);
		}
		\Flash::error('Invalid request');
		return redirect()->back();
	}


	public function downloadRafBundlePolicy($log_id) {
		
		$doc = LogInformation::where('id', $log_id)->first();
		if (!empty($doc)) {
			return $this->helper->download($doc->bundle_policy_documents);
		}
		\Flash::error('Invalid request');
		return redirect()->back();
		
		
	}

	public function downloadRafBundleDD($log_id) {
		
		$doc = LogInformation::where('id', $log_id)->first();
		if (!empty($doc)) {
			return $this->helper->download($doc->bundle_direct_debit_documents);
		}
		\Flash::error('Invalid request');
		return redirect()->back();
		
		
	}

	public function downloadRafBundleTerms($log_id) {
		
		$doc = LogInformation::where('id', $log_id)->first();
		if (!empty($doc)) {
			return $this->helper->download($doc->bundle_terms_and_conditions_documents);
		}
		\Flash::error('Invalid request');
		return redirect()->back();
		
		
	}


	public function getLoanTransactions(Request $request) {
		$loan_id = $request->loan_id;

		//echo $loan_id;
		//exit;

		if($loan_id=="")
		
		{
			$loan_id=RAFLoan::where('CustomerId',$request->customer_id)->first();
			$loan_id=$loan_id->id;
		}
		$transactions = RAFController::getPaymentTransaction($loan_id);

		//ksort($transactions['response']['Transactions']);

		//dd($transactions['response']['Transactions']);

		foreach($transactions['response']['Transactions'] as $transaction)
		{
			$payment_transactions[$transaction['PaymentArrivalDate']]['payment_date']=str_limit($transaction['PaymentArrivalDate'], $limit = 10, $end = '');
			$payment_transactions[$transaction['PaymentArrivalDate']]['status']=$transaction['Status'];
			$payment_transactions[$transaction['PaymentArrivalDate']]['total']=$transaction['Total'];
		}
		ksort($payment_transactions);
		//dd($payment_transactions);
		$res_string = view('admin.leads.partials.raf-loan-payment-transactions', compact('transactions','payment_transactions'))->render();
		return $res_string;
	}


	public static function getLoanPrincipalAmount($customer_id) {
		//$loan_id = $request->loan_id;

		//echo $loan_id;
		//exit;

		
		$loan_id=RAFLoan::where('CustomerId',$customer_id)->orderBy('primary_id','DESC')->first();
		$loan_id=$loan_id->id;
		
		$transactions = RAFController::getPaymentTransaction($loan_id);

		//ksort($transactions['response']['Transactions']);

		//dd($transactions['response']['Transactions']);

		

		$transactions = $transactions['response'];

		$loan_data['TotalPrincipal']=$transactions['TotalPrincipal'];
		$loan_data['RegularPaymentAmount']=$transactions['RegularPaymentAmount'];
		
		return $loan_data;
	}


	public static function getLoanPrincipalAmountForResend($customer_id) {
		//$loan_id = $request->loan_id;

		//echo $loan_id;
		//exit;

		
		$loan_id=RAFLoan::where('CustomerId',$customer_id)->where('is_active','0')->orderBy('primary_id','DESC')->first();
		$loan_id=$loan_id->id;
		
		$transactions = RAFController::getPaymentTransaction($loan_id);

		//ksort($transactions['response']['Transactions']);

		//dd($transactions['response']['Transactions']);

		

		$transactions = $transactions['response'];

		$loan_data['TotalPrincipal']=$transactions['TotalPrincipal'];
		$loan_data['RegularPaymentAmount']=$transactions['RegularPaymentAmount'];
		
		return $loan_data;
	}

	
	public static function getLoanPrincipalAmountOld($customer_id) {
		//$loan_id = $request->loan_id;

		//echo $loan_id;
		//exit;

		
		$loan_id=RAFLoan::where('CustomerId',$customer_id)->first();
		$loan_id=$loan_id->id;
		
		$transactions = RAFController::getPaymentTransaction($loan_id);

		//ksort($transactions['response']['Transactions']);

		//dd($transactions['response']['Transactions']);

		

		$transactions = $transactions['response'];

		$loan_data['TotalPrincipal']=$transactions['TotalPrincipal'];
		$loan_data['RegularPaymentAmount']=$transactions['RegularPaymentAmount'];
		
		return $loan_data;
	}

	public function getWebHookMessages(RAFWebHookMessageRequest $request) {
		//Breadcrumb Titles
		$breadcrumb = [
			'title' => 'RAF Webhook Messages',
			'subTitle' => 'Preview of webhook messages',
			'home' => 'Leads',
			'homeLink' => '/account/leads?status=completed',
			'subHome' => 'Document Versions',
			'subHomeLink' => URL::to('account/leads?status=completed'),
			'subChildHome' => '',
			'menu' => 'completed-leads',
			'menuColor' => '#fff',
			'MenuClass' => 'active open',
			'SubMenuClass' => 'active',
		];
		$status = "";

		$raf_web_hook_messages = RAFWebHookMessage::where('customerid', $request->raf_cust_id)->orderBy('created_at', 'DESC')->get();

		return view('admin.leads.raf-webhooks', compact('breadcrumb', 'raf_web_hook_messages'));
	}

	public function getVv() {
		$documents_data = RAFLoanDocuments::all();

		foreach ($documents_data as $document) {
			//dd($document);
			$doc_exists = RAFLoanDocuments::where('id', $document['id'])->first();
			//  dd($doc_exists);
			if (is_null($doc_exists)) {

				dispatch(new DocumentStatusCheckJob(
					$document->id,
					"d4ee5277-7a00-ea11-80f8-005056b97be2"
				));

				echo "Disapctached" . "<br/>";
			}
		}
	}

	public function getDd() {

		$document_id = "b486ddcc-d8fa-e911-80f8-005056b97be2";

		$log_info_id = RAFLoanDocuments::where('id', $document_id)->first()->log_info_id;
		$raf_docs = RAFLoanDocuments::where('log_info_id', $log_info_id)->get();

		$raf_printes_docs = RAFLoanDocuments::where('log_info_id', $log_info_id)
			->whereNotNull('s3_url')->get();

		if ((@count($raf_docs) > 0) && (@count($raf_printes_docs) == @count($raf_docs))) {
			$lead_log_info = LogInformation::with('raf_docuemnts')->find($log_info_id);
			$raf_docs = $lead_log_info->raf_docuemnts;

			if (!empty($lead_log_info->schedule_pdf)) {
				// echo "<br/>".$count++;
				$this->s3ToLocal($lead_log_info->schedule_pdf);
				$pdf->addPDF(public_path($lead_log_info->schedule_pdf), 'all');
			}

			foreach ($raf_docs as $key => $raf_doc) {
				// echo "<br/>".$count++;
				$this->s3ToLocal($raf_doc->s3_url);
				$pdf->addPDF(public_path($raf_doc->s3_url), 'all');
			}

			$bundle_doc_file_name = "bundle_doc_file_name.pdf";
			$path_info_directory_name = pathinfo($raf_docs->first()->s3_url)['dirname'];
			// dd($path_info_directory_name);
			$bundle_doc_file_name = $path_info_directory_name . $bundle_doc_file_name;
			$pdf->merge('file', public_path($bundle_doc_file_name), 'P');
			dd("done");
		}
	}

	public function s3ToLocal($s3_path_file, $path = null) {
		// sleep(2);
		$inputStream = Storage::disk('s3')->getDriver()->readStream($s3_path_file);
		if (!empty($path)) {
			$destination = $path;
		} else {
			$destination = $s3_path_file;
		}
		echo $s3_path_file . "--" . $destination . "<br/>";
		return Storage::disk('app_public')->getDriver()->put($destination, $inputStream);
	}

	public function getCd() {
		try {
			$raf_started_date = Carbon::parse(config('raf.raf_started_date'));

			$log_details = LogInformation::where('is_bundled', '!=', 1)
			// ->where('created_at', '>=', $raf_started_date)
				->where('application_id', '=', 76551)
				->chunk(50, function ($lds) {
					foreach ($lds as $ld) {
						// echo $ld->id."<br/>";
						$this->getBundleJob($ld);
					}
				});
		} catch (\Exception $e) {
			dd($e);
		}

	}

	public function getBundleJob($logInfo) {
		if ($logInfo->action == "EDIT") {
			if ($logInfo->product_id == 17 || $logInfo->product_id == 27) {
				$file_path = $this->fileuploader->createGenerateScheduleBAIFileIfnotExists($logInfo->id);
			} else {
				$file_path = $this->fileuploader->createGenerateScheduleFileIfnotExists($logInfo->id);
			}
		} elseif ($logInfo->action == "MTA") {
			$file_path = $this->fileuploader->createMtaFileIfnotExists($logInfo->id);
		} elseif ($logInfo->action == "RENEW") {
			$file_path = $this->fileuploader->createRenewFileIfnotExists($logInfo->id);
		} elseif ($logInfo->action == "CANCEL") {
			$file_path = $this->fileuploader->createCancelFileIfnotExists($logInfo->id);
		} else {
			if ($logInfo->product_id == 17 || $logInfo->product_id == 27) {
				$file_path = $this->fileuploader->createGenerateScheduleBAIFileIfnotExists($logInfo->id);
			} else {
				$file_path = $this->fileuploader->createGenerateScheduleFileIfnotExists($logInfo->id);
			}
		}

		$logInfo = LogInformation::find($logInfo->id);

		$raf_docs = RAFLoanDocuments::where('log_info_id', $logInfo->id)->get();

		$raf_printes_docs = RAFLoanDocuments::where('log_info_id', $logInfo->id)
			->whereNotNull('s3_url')->get();

		$file_command = "";
		if ((@count($raf_docs) > 0) && (@count($raf_printes_docs) == @count($raf_docs))) {
			echo $logInfo->id . "?<br>";

			if (($logInfo->action == "") || is_null($logInfo->action)) {
				// approved
				echo "approved<br>";
				$this->savePolicyScheduleDocumentsBundle($logInfo);
				$logInfo = LogInformation::find($logInfo->id);
				echo "eod approved<br>";
			} elseif ($logInfo->action == "RENEW") {
				// renew
				echo "renew<br>";
				$this->saveRenewPolicyScheduleDocuemnt($logInfo);
				$logInfo = LogInformation::find($logInfo->id);
				echo "eod renew<br>";
			}
			echo "Before saveRafDirectDebitDocumentsBundle<br>";
			$this->saveRafDirectDebitDocumentsBundle($logInfo, $raf_printes_docs);
			echo "saveRafDirectDebitDocumentsBundle<br>";
			$logInfo = LogInformation::find($logInfo->id);
			$this->saveTermsAndConditionDocumentsBundle($logInfo);
			echo "saveTermsAndConditionDocumentsBundle<br>";
			$logInfo = LogInformation::find($logInfo->id);
			$logInfo->is_bundled = 1;
			$logInfo->save();
			echo "Done<br>";
		}
	}

	public function saveRenewPolicyScheduleDocuemnt($logInfo) {
		$policy_directory = pathinfo($logInfo->renew_pdf)['dirname'];
		$path_info_directory_name = public_path($policy_directory);
		$this->s3ToLocal($logInfo->renew_pdf);
		$this->s3ToLocal(config('raf.faq_document'), $policy_directory . DIRECTORY_SEPARATOR . config('raf.faq_document_file_name'));

		$faq = $path_info_directory_name . DIRECTORY_SEPARATOR . config('raf.faq_document_file_name');
		$file_command = "";
		$file_command = $file_command . " " . public_path($logInfo->renew_pdf) . " " . $faq;

		$bundle_doc_file_name_only = "Policy_Schedule.pdf";

		$bundle_doc_file_name = $path_info_directory_name . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;

		$file_command = "pdftk " . $file_command . " cat output " . $bundle_doc_file_name;
		// dd($file_command);
		exec($file_command);

		$logInfo->bundle_policy_documents = $policy_directory . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;
		$logInfo->save();

		Storage::disk('s3')->put($logInfo->bundle_policy_documents, file_get_contents($logInfo->bundle_policy_documents), 'public');
		File::deleteDirectory($policy_directory);
	}

	public function saveRafDirectDebitDocumentsBundle($logInfo, $raf_printes_docs) {
		$file_command = "";
		foreach ($raf_printes_docs as $key => $raf_doc) {
			$this->s3ToLocal($raf_doc->s3_url);
			$file_command = $file_command . " " . public_path($raf_doc->s3_url);
		}

		if (!empty($file_command)) {
			$bundle_doc_file_name_only = "Direct_Debit_Documents.pdf";

			$path_info_directory_name = pathinfo($raf_printes_docs->first()->s3_url)['dirname'];

			// dd($path_info_directory_name);
			$bundle_doc_file_name = public_path($path_info_directory_name . "/" . $bundle_doc_file_name_only);

			$file_command = "pdftk " . $file_command . " cat output " . $bundle_doc_file_name;

			// dd($file_command);
			echo exec($file_command);
			// exec("chmod -R 777 ".$path_info_directory_name);

			$logInfo->bundle_direct_debit_documents = $path_info_directory_name . "/" . $bundle_doc_file_name_only;
			$logInfo->save();

			Storage::disk('s3')->put($logInfo->bundle_direct_debit_documents, file_get_contents($logInfo->bundle_direct_debit_documents), 'public');
			File::deleteDirectory($path_info_directory_name);
		}
	}

	public function savePolicyScheduleDocumentsBundle($logInfo) {
		$policy_directory = pathinfo($logInfo->schedule_pdf)['dirname'];
		$path_info_directory_name = public_path($policy_directory);
		$this->s3ToLocal($logInfo->schedule_pdf);
		$this->s3ToLocal(config('raf.faq_document'), $policy_directory . DIRECTORY_SEPARATOR . config('raf.faq_document_file_name'));

		$faq = $path_info_directory_name . DIRECTORY_SEPARATOR . config('raf.faq_document_file_name');
		$file_command = "";
		$file_command = $file_command . " " . public_path($logInfo->schedule_pdf) . " " . $faq;

		$bundle_doc_file_name_only = "policy_schedule_bundle.pdf";

		$bundle_doc_file_name = $path_info_directory_name . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;

		$file_command = "pdftk " . $file_command . " cat output " . $bundle_doc_file_name;
		echo $file_command . "<br/>";
		exec($file_command);

		// exec("chmod -R 777 ".$path_info_directory_name);

		$logInfo->bundle_policy_documents = $policy_directory . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;
		$logInfo->save();

		Storage::disk('s3')->put($logInfo->bundle_policy_documents, file_get_contents($logInfo->bundle_policy_documents), 'public');
		File::deleteDirectory($policy_directory);
	}

	public function saveTermsAndConditionDocumentsBundle($lgInfo) {

		$logInfo = DB::table('log_information')
			->where('log_information.id', $lgInfo->id)
			->join('products', 'log_information.product_id', '=', 'products.id')
			->first();

		if (!empty($logInfo->schedule_pdf)) {
			$policy_directory = pathinfo($logInfo->schedule_pdf)['dirname'];
		} elseif (!empty($logInfo->renew_pdf)) {
			$policy_directory = pathinfo($logInfo->renew_pdf)['dirname'];
		} elseif (!empty($logInfo->cancel_pdf)) {
			$policy_directory = pathinfo($logInfo->cancel_pdf)['dirname'];
		} elseif (!empty($logInfo->mta_pdf)) {
			$policy_directory = pathinfo($logInfo->mta_pdf)['dirname'];
		}

		$path_info_directory_name = public_path($policy_directory);
		$tob = $path_info_directory_name . DIRECTORY_SEPARATOR . config('raf.tob_document_file_name');

		$this->s3ToLocal(config('raf.tob_document'), $policy_directory . DIRECTORY_SEPARATOR . config('raf.tob_document_file_name'));

		$ip_ipid_file = 'static_policy_documents' . DIRECTORY_SEPARATOR . $logInfo->keyfacts_doc;
		$ipid_file = $path_info_directory_name . DIRECTORY_SEPARATOR . $logInfo->keyfacts_doc;
		$this->s3ToLocal($ip_ipid_file, $policy_directory . DIRECTORY_SEPARATOR . $logInfo->keyfacts_doc);

		$ip_policy_document_file = 'static_policy_documents' . DIRECTORY_SEPARATOR . $logInfo->policy_wordings_doc;
		$policy_document_file = $path_info_directory_name . DIRECTORY_SEPARATOR . $logInfo->policy_wordings_doc;

		$this->s3ToLocal($ip_policy_document_file, $policy_directory . DIRECTORY_SEPARATOR . $logInfo->policy_wordings_doc);

		$bundle_doc_file_name_only = "Terms_And_Conditions.pdf";

		$bundle_doc_file_name = $path_info_directory_name . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;

		$file_command = "pdftk ";
		$file_command = $file_command . " " . $tob . " " . $ipid_file . " " . $policy_document_file . " cat output " . $bundle_doc_file_name;

		exec($file_command);

		// exec("chmod -R 777 ".$path_info_directory_name);
		$logInfo = LogInformation::find($lgInfo->id);

		$logInfo->bundle_terms_and_conditions_documents = $policy_directory . DIRECTORY_SEPARATOR . $bundle_doc_file_name_only;
		$logInfo->save();

		Storage::disk('s3')->put($logInfo->bundle_terms_and_conditions_documents, file_get_contents($logInfo->bundle_terms_and_conditions_documents), 'public');
		File::deleteDirectory($policy_directory);
	}

	public function getAa() {
		$s3_path_file = "policy_documents/BIG90_06005A3209MMS/raf/Direct_Debit_Documents.pdf";

		dd(Storage::disk('s3')->put($s3_path_file, file_get_contents($s3_path_file), 'public'));
	}

};