<?php

namespace App\Http\Controllers;

use App\ProductDetail;
use App\Quote;
use App\Report;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Stripe\Exception\SignatureVerificationException;
use Stripe\StripeClient;
use Stripe\Webhook;
use App\Seo;
use Cache;

/**
 * Class HomeController
 *
 * @package App\Http\Controllers
 */
class HomeController extends Controller
{
	public function index(Request $request)
	{
		/*$seoMeta = Seo::where('uri', $uri)->first();
		$cacheName = str_replace("/", "-", trim($uri));
		$seoMeta = Cache::remember($cacheName, 30, function() use ($uri) {
			return Seo::where('uri', $uri)->first();
		});*/
		
		$uri = $request->getRequestUri();
		$uri = urldecode($uri);
		$uri = $uri . "||";
		$uri = str_replace("//", "/", "/" . $uri);
		$uri = str_replace("/?", "?", $uri);
		$uri = str_replace("?&", "?", $uri);
		$uri = str_replace("&&", "&", $uri);
		$uri = str_replace("/||", "", $uri);
		$uri = str_replace("||", "", $uri);
		$uri = preg_replace('/(?:&|(\?))page=[^&]*(?(1)&|)?/i', "$1", $uri);
		if ($uri == null || $uri == "") $uri = "/";
		
		$seoMeta = Seo::where('uri', $uri)->first();
		if (!$seoMeta && strpos($uri, "/column/detail/") !== false) {
			$idPostArr = str_replace("/column/detail/", "", $uri);
			$idPostArr = explode("/", $idPostArr);
			$idPost = $idPostArr[0];
			$seoMeta = Seo::where('uri', 'like', "/column/detail/" . $idPost . "/%")->first();
		} else if (!$seoMeta && strpos($uri, "/bbs/detail/") !== false) {
			$idPostArr = str_replace("/bbs/detail/", "", $uri);
			$idPostArr = explode("/", $idPostArr);
			$idPost = $idPostArr[0];
			$seoMeta = Seo::where('uri', 'like', "/bbs/detail/" . $idPost . "/%")->first();
		}
		
		if (isset($seoMeta) && $seoMeta->id != null) {
			$data['title'] = $seoMeta->title;
			$data['keywords'] = $seoMeta->keywords;
			$data['description'] = $seoMeta->description;
			$imgSeo = ($seoMeta->image != "" && $seoMeta->image != null) ? $seoMeta->image : 'favicon-16x16.png';
			$data['image'] = url("files/" . $imgSeo);
		} else {
			$data = ['title' => config('settings.site_name'), 'keywords' => '', 'description' => '', 'image' => url('favicon-16x16.png')];
		}
		
		return view('home', $data);
	}
	
	public function note(Request $request)
	{
		$uri = $request->getRequestUri();
		$uri = urldecode($uri);
		$uri = $uri . "||";
		$uri = str_replace("/profile/", "", $uri);
		$uri = str_replace("//", "/", "/" . $uri);
		$uri = str_replace("/?", "?", $uri);
		$uri = str_replace("?&", "?", $uri);
		$uri = str_replace("&&", "&", $uri);
		$uri = str_replace("/||", "", $uri);
		$uri = str_replace("||", "", $uri);
		$uri = preg_replace('/(?:&|(\?))page=[^&]*(?(1)&|)?/i', "$1", $uri);
		if (strpos($uri, "search=1") !== false) $uri = "/fortune-teller?search=1";
		$seoMeta = Seo::where('uri', $uri)->first();
		
		if (isset($seoMeta) && $seoMeta->id != null) {
			$data['title'] = $seoMeta->title;
			$data['keywords'] = $seoMeta->keywords;
			$data['description'] = $seoMeta->description;
			$imgSeo = ($seoMeta->image != "" && $seoMeta->image != null) ? $seoMeta->image : 'no-image.png';
			$data['image'] = url("files/" . $imgSeo);
		} else {
			$data = ['title' => config('settings.site_name'), 'keywords' => '', 'description' => '', 'image' => url('favicon-16x16.png')];
		}
		
		return view('note', $data);
	}
	
	public function stripePaymentWebhook()
	{
		$stripe = new StripeClient('xxxx');
		$endpoint_secret = 'xxxx';
		$payload = @file_get_contents('php://input');
		$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
		$event = null;
		
		try {
			$event = Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
		} catch (\UnexpectedValueException $e) {
			// Invalid payload
			http_response_code(400);
			exit();
			
		} catch (SignatureVerificationException $e) {
			// Invalid signature
			http_response_code(400);
			exit();
		}
		
		http_response_code(200);
	}
	
	public function reportExportPdf($id)
	{
		$report = Report::notDeleted()->where('id', $id)->first();
		if (!isset($report)) abort("404");
		
		$detail = [];
		foreach ($report->detail as $item) {
			$detail[] = [
				'working_zone'        => $item->working_zone,
				'piping'              => $item->piping,
				'temperature_keeping' => $item->temperature_keeping,
				'size'                => $item->size,
				'length'              => $item->length,
				'elbow'               => $item->elbow,
				'note'                => $item->note
			];
		}
		
		if (count($detail) < 26) {
			$addMore = 26 - count($detail);
			for ($i = 0; $i < $addMore; $i++) {
				$detail[] = [
					'working_zone'        => '',
					'piping'              => '',
					'temperature_keeping' => '',
					'size'                => '',
					'length'              => '',
					'elbow'               => '',
					'note'                => ''
				];
			}
		}
		
		$address = $report->address;
		if ($address !== null && $address !== "") {
			$totalLength = count($detail);
			$addressIndex = $totalLength - 3;
			$addressIndexNext = $totalLength - 2;
			$addressIndexNext2 = $totalLength - 1;
			if (isset($detail[$addressIndex]) && ($detail[$addressIndex]['temperature_keeping'] === null || $detail[$addressIndex]['temperature_keeping'] === "")) {
				$detail[$addressIndex]['temperature_keeping'] = $address;
			} elseif (isset($detail[$addressIndexNext]) && ($detail[$addressIndexNext]['temperature_keeping'] === null || $detail[$addressIndexNext]['temperature_keeping'] === "")) {
				$detail[$addressIndexNext]['temperature_keeping'] = $address;
			} elseif (isset($detail[$addressIndexNext2]) && ($detail[$addressIndexNext2]['temperature_keeping'] === null || $detail[$addressIndexNext2]['temperature_keeping'] === "")) {
				$detail[$addressIndexNext2]['temperature_keeping'] = $address;
			} else {
				$detail[] = [
					'working_zone'        => '',
					'piping'              => '',
					'temperature_keeping' => $address,
					'size'                => '',
					'length'              => '',
					'elbow'               => '',
					'note'                => ''
				];
			}
		}
		
		$title = Carbon::parse($report->report_date)->format('Y年m月d日') . ' - ID#' . $report->id;
		$onSiteCost = $report->on_site_cost;
		if ($onSiteCost != null && $onSiteCost != "") {
			$onSiteCost = (float)$onSiteCost;
			if ($onSiteCost > 0) {
				$onSiteCost = number_format($onSiteCost);
			}
		}
		
		$data = [
			'id'                 => $report->id,
			'title'              => $title,
			'report_year'        => Carbon::parse($report->report_date)->format('Y'),
			'report_month'       => Carbon::parse($report->report_date)->format('m'),
			'report_date'        => Carbon::parse($report->report_date)->format('d'),
			'report_full_date'   => $report->report_date,
			'site_name'          => $report->customer->project->site->name,
			'project_name'       => $report->customer->project->name,
			'customer_name'      => $report->customer->name,
			'contact_name'       => $report->charge->name,
			'has_estimated'      => $report->has_estimated,
			'estimated_workload' => $report->estimated_workload,
			'is_finished'        => $report->is_finished,
			'detail'             => $detail,
			'car'                => ($report->car != null && $report->car != "") ? $report->car : '/',
			'primary_member'     => $report->primary_member,
			'second_member'      => $report->second_member,
			'notice'             => $report->notice,
			'request'            => $report->request,
			'on_site_cost'       => $onSiteCost,
		];
		
		return Pdf::loadView('pdf.report', $data)
			->setPaper('A4', 'portrait')
			->stream('77.pdf');
	}
	
	public function quoteExportPdf2($id)
	{
		$quote = Quote::notDeleted()->where('id', $id)->first();
		if (!isset($quote)) abort("404");
		
		$data = [
			'id'                    => $quote->id,
			'code'                  => $quote->code,
			'company'               => $quote->company,
			'customer'              => $quote->customer,
			'gender'                => $quote->gender,
			'estimated_date'        => Carbon::parse($quote->estimated_date)->format('Y年 m月 d日'),
			'estimated_amount'      => number_format($quote->estimated_amount),
			'project_name'          => $quote->project_name,
			'construction_name'     => $quote->construction_name,
			'construction_time'     => $quote->construction_time,
			'quote_expiration_date' => $quote->quote_expiration_date,
			'content'               => ($quote->content != "") ? json_decode($quote->content, true) : null,
			'total_amount'          => number_format($quote->total_amount),
		];
		
		return view('pdf.quote', $data);
	}
	
	public function quoteExportPdf($id)
	{
		$quote = Quote::with('customer')->notDeleted()
			->where('id', $id)
			->where('type', 0)
			->first();
		if (!isset($quote)) abort("404");
		
		$data = [
			'id'                    => $quote->id,
			'code'                  => $quote->code,
			'company'               => $quote->company,
			'customer'              => $quote->customer,
			'gender'                => $quote->gender,
			'estimated_date'        => Carbon::parse($quote->estimated_date)->format('Y年 m月 d日'),
			'estimated_amount'      => number_format($quote->estimated_amount),
			'project_name'          => $quote->project_name,
			'construction_name'     => $quote->construction_name,
			'construction_time'     => $quote->construction_time,
			'quote_expiration_date' => $quote->quote_expiration_date,
			'content'               => ($quote->content != "") ? json_decode($quote->content, true) : null,
			'total_amount'          => number_format($quote->total_amount),
		];
		
		$fileName = '御見積書_No.' . $quote->code . '.pdf';
		
		return Pdf::loadView('pdf.quote_' . $quote->template, $data)
			->setPaper('A4', 'portrait')
			->stream($fileName);
	}
	
	public function invoiceExportPdf($id)
	{
		$invoice = Quote::with('customer')->notDeleted()
			->where('id', $id)
			->where('type', 1)
			->first();
		if (!isset($invoice)) abort("404");
		
		$data = [
			'id'                    => $invoice->id,
			'code'                  => $invoice->code,
			'company'               => $invoice->company,
			'customer'              => $invoice->customer,
			'gender'                => $invoice->gender,
			'estimated_date'        => Carbon::parse($invoice->estimated_date)->format('Y年 m月 d日'),
			'estimated_amount'      => number_format($invoice->estimated_amount),
			'project_name'          => $invoice->project_name,
			'construction_name'     => $invoice->construction_name,
			'construction_time'     => $invoice->construction_time,
			'quote_expiration_date' => $invoice->quote_expiration_date,
			'content'               => ($invoice->content != "") ? json_decode($invoice->content, true) : null,
			'total_amount'          => number_format($invoice->total_amount),
		];
		
		$fileName = '請求書_No.' . $invoice->code . '.pdf';
		
		return Pdf::loadView('pdf.invoice_0', $data)
			->setPaper('A4', 'portrait')
			->stream($fileName);
	}
	
	public function downloadReport($file)
	{
		$filePath = public_path('export/pdf/report/') . $file;
		if ($file == "" || !file_exists($filePath)) abort("404");
		$fileName = '作業報告書_' . $file;
		
		return response()->download($filePath, $fileName, ['Content-Type' => 'application/pdf']);
	}
	
	public function imageToBase64($imgPath)
	{
		$type = pathinfo($imgPath, PATHINFO_EXTENSION);
		$data = \File::get($imgPath);
		
		return ($type == "svg") ? "data:image/svg+xml;base64," . base64_encode($data) : "data:image/" . $type . ";base64," . base64_encode($data);
	}
}
