<?php

namespace App\Http\Controllers\teamstore;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
// use Auth;
use Illuminate\Support\Facades\Auth;
use App\Models\teamstore\TeamStoreModel;
use App\Models\user\UserModel;
// use Mail;
use Illuminate\Support\Facades\Mail;
use Analytics;
use App\Models\TemplatesModel;
use App\Traits\CaptchaTrait;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Carbon\Carbon;

class TeamStoreController extends Controller
{

	use CaptchaTrait;

	public function index(Request $request, $teamStoreURL)
	{
		// var_dump($teamStoreURL);
		$m 		= new TeamStoreModel;
		$UserModel 	= new UserModel;

		$store_array 	= $m->selectTeamStore('StoreUrl', $teamStoreURL);

		if(count($store_array) <= 0) {
			return view('merchbay.not_found')
			->with('message', "Store not found");
		}


		// $product_array 	= $m->selectTeamStoreProducts('TeamStoreId', $store_array[0]->Id);

		$q 		= $request->input('q');
		$sort 	= $request->input('s');

		if (isset($q) && isset($sort)) {

			if ($sort == "latest") {
				$field = "Id";
				$sort_value = "DESC";
			} elseif ($sort == "al-desc") {
				$field = "ProductName";
				$sort_value = "DESC";
			} elseif ($sort == "oldest") {
				$field = "Id";
				$sort_value = "ASC";
			} else {
				$field = "ProductName";
				$sort_value = "ASC";
			}

			if ($q != "") {
				// keyword and sort
				$product_array 	= $m->searchTeamstoreProducts('TeamStoreId', $store_array[0]->Id, $field, $sort_value, $q);
			} else {
				// sort only
				$product_array 	= $m->filterTeamstoreProducts('TeamStoreId', $store_array[0]->Id, $field, $sort_value);
			}
		} else {
			$field = "Ordering";
			$sort_value = "ASC";
			$sort = "";
			$product_array 	= $m->filterTeamstoreProducts('TeamStoreId', $store_array[0]->Id, $field, $sort_value);
		}



		$user_role = '';

		if (Auth::check()) {
			$user_role = Auth::user()->role;
			$store_id = Auth::user()->store_id;
		} else {
			$user_role = null;
			$store_id = null;
		}


		if ($store_array[0]->Password != null) {
			if ($request->session()->get('teamstore_data_array') == null) {
				if ($store_id !=  $store_array[0]->Id) {
					return redirect('/');
				}
			} else {

				if ($user_role != "store_owner") {
					if ($request->session()->get('teamstore_data_array')[0]->StoreUrl != $store_array[0]->StoreUrl) {
						return redirect()->back();
					}
				}
			}
		}


		$thumbnails = [];
		foreach ($product_array as $p => $pr_arr) {

			$thumbnails_array 			= 	$m->getProductThumbnails($pr_arr->Id);
			$displayThumbnails = "product-image-placeholder.png";


			if (!empty($thumbnails_array)) {
				foreach ($thumbnails_array as $t => $thumb) {

					if ($thumb->ImageClass == 'custom') {
						$displayThumbnails = $thumb->Image;
						break;
					}

					if ($thumb->ImageClass == 'active') {
						$displayThumbnails = $thumb->Image;
						break;
					}
				}

				$thumbnails[] = array(
					'folder' 	=>	$store_array[0]->ImageFolder,
					'product_id' =>  $pr_arr->Id,
					'thumb'	     =>  $displayThumbnails

				);
			} else {
				$thumbnails[] = array(
					'folder' 	=>	$store_array[0]->ImageFolder,
					'product_id' =>  $pr_arr->Id,
					'thumb'	     =>  "product-image-placeholder.png"
				);
			}
		}
		$getAnnouncement 	= $UserModel->getAnnouncement($store_array[0]->Id);

		if (count($getAnnouncement) > 0) {
			$data = $getAnnouncement[0];
		} else {
			$data =  (object) array(
				'Id' => 0,
				'StoreId' => "",
				'Announcement' => "",
				'IsActive' => 0,
				'DateCreated' => ""
			);
		}
		// var_dump($thumbnails);
		return view('teamstore-sublayouts.index')
			->with('store_array', $store_array)
			->with('product_array', $product_array)
			->with('announcement', $data)
			->with('keyword', $q)
			->with('filter', $sort)
			->with('thumbnails', $thumbnails);
	}

	public function storelist(Request $request)
	{
		// $analyticsData = Analytics::getMostVisitedPages(14, 50);

		// foreach($analyticsData as $key => $val){
		// 	if (strpos($val['url'], 'teamstore') !== false) {
		// 		$teamstore[] = $val['url'];
		// 	}
		// }

		// foreach($teamstore as $t){
		// 	$sad = explode('/', $t);

		// 	if(count($sad) == 4){
		// 		$arr_teamstore[] = explode('?', $sad['3'])['0'];

		// 	}
		// }

		// var_dump(array_unique($arr_teamstore));

		$m 		= new TeamStoreModel;
		$q 		= $request->input('q');
		$sort 	= $request->input('s');

		if (isset($q) && isset($sort)) {

			if ($sort == "latest") {
				$field = "Id";
				$sort_value = "DESC";
			} elseif ($sort == "al-desc") {
				$field = "StoreName";
				$sort_value = "DESC";
			} elseif ($sort == "oldest") {
				$field = "Id";
				$sort_value = "ASC";
			} else {
				$field = "StoreName";
				$sort_value = "ASC";
			}

			if ($q != "") {
				// keyword and sort
				$stores_array 	= $m->selectTeamstoreSearch($field, $sort_value, $q);
			} else {
				// sort only
				$stores_array 	= $m->selectTeamstoreFilter($field, $sort_value);
			}
		} else {
			$field = "StoreName";
			$sort_value = "ASC";
			$sort = "al-asc";
			$stores_array 	= $m->selectTeamstoreFilter($field, $sort_value);
		}

		$getCarousel = $m->getCarousel();
		// var_dump($getCarousel);

		$featured_products 	 = $m->selectFeaturedProducts();
		return view('merchbay.index')
			->with('stores_array', $stores_array)
			->with('keyword', $q)
			->with('filter', $sort)
			->with('carousel_images', $getCarousel)
			->with('featured_products', $featured_products);
	}

	public function checkTeamStorePassword(Request $request)
	{
		$m 				= 	new TeamStoreModel;
		$post 			=	$request->all();

		$store_array 	= $m->checkStorePassword($post['store_id'], $post['password']);

		if ($store_array) {
			$request->session()->put('teamstore_data_array', $store_array);
			return redirect('store/' . $store_array[0]->StoreUrl);
		} else {
			Session::flash('errors', 'Invalid Password');
			echo '<script>
        			alert("Invalid Password");
							window.history.back();
        		</script>';
			// return redirect('cart');

			// return redirect('/');
		}
	}

	private $teams_array;

	public function productDetails($teamStoreURL, $productURL)
	{
		$m 		= new TeamStoreModel;
		$teams_array = array();
		$store_array 	= $m->selectTeamStore('StoreUrl', $teamStoreURL);
		$product_array 	= $m->selectTeamStoreProducts('ProductURL', $productURL);

		if(count($product_array) <= 0) {
			return view('merchbay.not_found')
			->with('message', "Store product not found");
		}

		$thumbnails_array 	= $m->getThumbnails($product_array[0]->Id);
		$teams_array 	= $m->getTeams($product_array[0]->Id);
		$selectRoster 	= $m->selectRoster($product_array[0]->Id);
		// $sizes_array 	= $m->getSizes();

		if (empty($thumbnails_array)) {

			$data = (object)  array(
				'Image' => 'product-image-placeholder.png',
				'ImageClass' => 'active'
			);


			$thumbnails_array[] = $data;
		}


		$x = explode(",", $product_array[0]->AvailableSizes);
		foreach ($x as $s) {
			$h[] 	= $m->getSizesByBracket($s);
		}

		foreach ($h as $d) {
			foreach ($d as $g) {
				$sizes_array[] = $g;
			}
		}

		if ($product_array[0]->ProductAvailableQty != null) {
			$soldQty 	= $m->getSoldQty($product_array[0]->Id);
			$availableQty = $product_array[0]->ProductAvailableQty - $soldQty[0]->SoldQty;
		} else {
			// echo 'no qty';
			$availableQty = null;
		}
		// $product_array[0]->ProductAvailableQty
		// var_dump($store_array[0]->Id);
		$store_products = $m->selectFeaturedProducts($store_array[0]->Id);

		return view('teamstore-sublayouts.product-details')
			->with('store_array', $store_array)
			->with('product_array', $product_array)
			->with('thumbnails_array', $thumbnails_array)
			->with('teams_array', $teams_array)
			->with('sizes_array', $sizes_array)
			->with('available_qty', $availableQty)
			->with('store_products', $store_products)
			->with('roster', $selectRoster);
	}

	public function login(Request $request)
	{
		return view('teamstore-sublayouts.login');
	}

	public function clearSession(Request $request)
	{
		$request->session()->forget('teamstore_data_array');
		return redirect("{{ url('/') }}");
	}

	public function addNewRow(Request $request)
	{
		$post 	=	$request->all();
		$TeamStoreModel 		= new TeamStoreModel;

		$item 	= $TeamStoreModel->selectTeamStoreProductByIdHash($post['p_id']);
		$x = explode(",", $item[0]->AvailableSizes);

		foreach ($x as $s) {
			$h[] 	= $TeamStoreModel->getSizesByBracket($s);
		}

		foreach ($h as $d) {
			foreach ($d as $g) {
				$sizes_array[] = $g;
			}
		}

		if ($item[0]->ProductAvailableQty != null) {
			$soldQty 	= $TeamStoreModel->getSoldQty($item[0]->Id);
			$availableQty = $item[0]->ProductAvailableQty - $soldQty[0]->SoldQty;
		} else {
			// echo 'no qty';
			$availableQty = null;
		}

		$selectRoster 	= $TeamStoreModel->selectRoster($item[0]->Id);

		$handle_form = view('teamstore-sublayouts.forms.' .  $item[0]->ProductForm)
			->with('sizes_array', $sizes_array)
			->with('availableQty', $availableQty)
			->with('roster', $selectRoster)
			->render();

		return $handle_form;
	}

	public function addToCart(Request $request)
	{
		$post 	=	$request->all();
		$m 		= new TeamStoreModel;
		$hash_product_id =  $post['p_id'];

		if ($request->session()->has('cartkey')) {
			$cartKey = $request->session()->get('cartkey');
		} else {
			$request->session()->put('cartkey', sha1(time() . str_random(6)));
			$cartKey = $cartKey = $request->session()->get('cartkey');
		}

		$product_array 	= $m->selectTeamStoreProductByIdHash($hash_product_id);
		$product_id 		= $product_array[0]->Id;
		$TeamStoreId 	= $product_array[0]->TeamStoreId;
		$ProductPrice 	= $product_array[0]->ProductPrice;
		$ProductURL 	= $product_array[0]->ProductURL;
		$product_form 	= $product_array[0]->ProductForm;
		$design_code 	= $product_array[0]->DesignCode;
		$product_name 	= $product_array[0]->ProductName;
		$shipping_cost_id 	= $product_array[0]->ShippingCostId;

		$teamstore_array 	= $m->selectTeamStore('Id', $TeamStoreId);

		$store_url 		=  $teamstore_array[0]->StoreUrl;
		$store_id 		=  $teamstore_array[0]->Id;

		if ($product_form == "jersey-and-shorts-form") {
			$order_names =  $post['order_names'];
			$order_number =  $post['order_number'];
			$order_jersey_size =  $post['order_jersey_size'];
			$order_shorts_size =  $post['order_shorts_size'];

			foreach ($order_names as $key => $val) {

				if ($order_jersey_size[$key] == "none" || $order_shorts_size[$key] == "none") {
					$final_price = $ProductPrice / 2;
				} else {
					$final_price = $ProductPrice;
				}

				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $order_names[$key],
					'Number'     	=> $order_number[$key],
					'JerseySize'    => $order_jersey_size[$key],
					'ShortsSize'   	=> $order_shorts_size[$key],
					'Price'			=> $final_price,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "tshirt-form") {

			$items[] = array(
				'ProductId'		=> $product_id,
				'StoreURL'		=> $store_url,
				'StoreId'		=> $store_id,
				'FormUsed'		=> $product_form,
				'CartKey' 	 	=> $cartKey,
				'DesignCode'	=> $design_code,
				'ProductURL' 	=> $ProductURL,
				'ProductName' 	=> $product_name,
				'Size' 		 	=> $post['uniformSize'],
				'Price'			=> $ProductPrice,
				'Quantity'		=> $post['quantity'],
				'ShippingCostId' => $shipping_cost_id
			);
		} elseif ($product_form == "quantity-form") {

			$items[] = array(
				'ProductId'		=> $product_id,
				'StoreURL'		=> $store_url,
				'StoreId'		=> $store_id,
				'FormUsed'		=> $product_form,
				'CartKey' 	 	=> $cartKey,
				'DesignCode'	=> $design_code,
				'ProductURL' 	=> $ProductURL,
				'ProductName' 	=> $product_name,
				'Price'			=> $ProductPrice,
				'Quantity'		=> $post['quantity'],
				'ShippingCostId' => $shipping_cost_id
			);
		} elseif ($product_form == "name-number-form") {

			$order_names =  $post['order_names'];
			$order_number =  $post['order_number'];

			foreach ($order_names as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $order_names[$key],
					'Number'     	=> $order_number[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "name-number-size-form" || $product_form == "roster-name-number-size-form") {

			$order_names =  $post['order_names'];
			$order_number =  $post['order_number'];
			$order_size =  $post['order_size'];

			foreach ($order_names as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $order_names[$key],
					'Size' 		 	=> $order_size[$key],
					'Number'     	=> $order_number[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "number-size-form") {

			// $order_names =  $post['order_names'];
			$order_number =  $post['order_number'];
			$order_size =  $post['order_size'];

			foreach ($order_size as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $product_name,
					'Size' 		 	=> $order_size[$key],
					'Number'     	=> $order_number[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "number-form") {

			$order_number =  $post['order_number'];

			foreach ($order_number as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Number'     	=> $order_number[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "name-name2-size-form") {

			$order_names =  $post['order_names'];
			$order_names2 =  $post['order_names2'];
			$order_size =  $post['order_size'];

			foreach ($order_names as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $order_names[$key],
					'Name2'     	=> $order_names2[$key],
					'Size' 		 	=> $order_size[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "name-size-form") {

			$order_names =  $post['order_names'];
			$order_size =  $post['order_size'];

			foreach ($order_names as $key => $val) {
				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Name' 		 	=> $order_names[$key],
					'Size'     		=> $order_size[$key],
					'Price'			=> $ProductPrice,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		} elseif ($product_form == "jersey-and-shorts-quantity-form") {

			$order_shorts_size =  $post['order_shorts_size'];
			$order_jersey_size =  $post['order_jersey_size'];
			$quantity = $post['quantity'];

			foreach ($order_jersey_size as $key => $val) {
				if ($order_jersey_size[$key] != "none" || $order_shorts_size[$key] != "none") {

					if ($order_jersey_size[$key] == "none" || $order_shorts_size[$key] == "none") {
						$final_price = $ProductPrice / 2;
					} else {
						$final_price = $ProductPrice;
					}

					$items[] = array(
						'ProductId'		=> $product_id,
						'StoreURL'		=> $store_url,
						'StoreId'		=> $store_id,
						'FormUsed'		=> $product_form,
						'CartKey' 	 	=> $cartKey,
						'DesignCode'	=> $design_code,
						'ProductURL' 	=> $ProductURL,
						'ProductName' 	=> $product_name,
						'JerseySize'    => $order_jersey_size[$key],
						'ShortsSize'   	=> $order_shorts_size[$key],
						'Price'			=> $final_price,
						'Quantity'		=> $quantity[$key],
						'ShippingCostId' => $shipping_cost_id
					);
				}
			}
		} elseif ($product_form == "number-jersey-shorts-form") {

			$order_number =  $post['order_number'];
			$order_jersey_size =  $post['order_jersey_size'];
			$order_shorts_size =  $post['order_shorts_size'];

			foreach ($order_number as $key => $val) {

				if ($order_jersey_size[$key] == "none" || $order_shorts_size[$key] == "none") {
					$final_price = $ProductPrice / 2;
				} else {
					$final_price = $ProductPrice;
				}

				$items[] = array(
					'ProductId'		=> $product_id,
					'StoreURL'		=> $store_url,
					'StoreId'		=> $store_id,
					'FormUsed'		=> $product_form,
					'CartKey' 	 	=> $cartKey,
					'DesignCode'	=> $design_code,
					'ProductURL' 	=> $ProductURL,
					'ProductName' 	=> $product_name,
					'Number'     	=> $order_number[$key],
					'JerseySize'    => $order_jersey_size[$key],
					'ShortsSize'   	=> $order_shorts_size[$key],
					'Price'			=> $final_price,
					'Quantity'		=> 1,
					'ShippingCostId' => $shipping_cost_id
				);
			}
		}

		$i 	= 	$m->insertToCart($items);

		if ($i['i']) {
			return response()->json(array(
				'success' => true
			));
		}


		return response()->json(array(
			'success' => false,
			'message' => "Something went wrong. Please refresh the page."
		));
	}

	public function cart(Request $request)
	{

		$m		 		= new TeamStoreModel;
		$UserModel				= new UserModel;
		$array_address_book = null;

		if (!Auth::guest()) {
			$userId = Auth::user()->id;
			$array_address_book 	= 	$UserModel->selectAddresBook('UserId', $userId);
			if (count($array_address_book) <= 0) {
				$array_address_book = null;
			}
		}

		$cartKey 		= $request->session()->get('cartkey');
		$items 	 		= $m->myCart($cartKey);
		// var_dump($items);
		$getSubtotal 	= $m->getSubtotal($cartKey);
		$items_group 	= $m->myCartGroup($cartKey);
		//var_dump($items_group);
		$grouped_item 	= $m->selectTeamStoreGroupByCartKey($cartKey);
		if ($grouped_item) {
			$defId = $grouped_item[0]->StoreId;
		} else {
			$defId = 0;
		}

		$item_thumbs 	= $m->selectDisplayCartThumb();
		$store_array 	= $m->selectTeamStore('Id', $defId);


		if ($items) {
			$voucherIds = array();
			foreach ($items as $item) {
				if ($item->VoucherId != null) {
					$voucherIds[] = $item->VoucherId;
				}
			}
			$vouchers 	= $m->selectVoucherWhereIn($voucherIds);
		}

		// var_dump($vouchers);

		$totalValue = 0;
		if (!empty($vouchers)) {
			foreach ($vouchers as $voucher) {
				$totalValue = $totalValue + $voucher->VoucherValue;
				if ($voucher->VoucherType == "Percentage") {
					$voucherData = array(
						'totalValue' => $totalValue,
						'type' => 'Percentage'
					);
				} else {
					$voucherData = array(
						'totalValue' => $totalValue,
						'type' => 'Flat'
					);
				}
			}

			if ($voucherData['type'] == "Percentage") {
				$getPercentageValue = $voucherData['totalValue'] / 100;

				// var_dump($getPercentageValue);
				// var_dump($getSubtotal[0]->Subtotal);
				// var_dump($getSubtotal[0]->Subtotal * $getPercentageValue);

				$getDiscountValue = ($getSubtotal[0]->Subtotal * $getPercentageValue);
				$finalSubTotal = $getSubtotal[0]->Subtotal - $getDiscountValue;
			} else {
				//Flat voucher computation here..
				$finalSubTotal = $getSubtotal[0]->Subtotal - $voucherData['totalValue'];
				// var_dump($voucherData['totalValue']);
			}
		} else {
			$finalSubTotal =  $getSubtotal[0]->Subtotal;
		}

		if ($cartKey != null) {
			$shippingFee =  app(\App\Http\Controllers\paypal\PaypalController::class)->getShippingFee($cartKey, $store_array);
			$tax = app(\App\Http\Controllers\paypal\PaypalController::class)->getTax($cartKey);
		} else {
			$shippingFee = 0;
			$tax = [];
		}

		// var_dump($finalSubTotal);

		return view('merchbay.cart')
			->with('item_group', $items_group)
			->with('row', $items)
			->with('img_thumb', $item_thumbs)
			->with('getSubtotal', $finalSubTotal)
			->with('store_array', $store_array)
			->with('store_array', $store_array)
			->with('shipping_fee', $shippingFee)
			->with('tax', $tax)
			->with('address_book', 	$array_address_book);
	}

	public function addVoucher(Request $request)
	{
		$cartKey 		= $request->session()->get('cartkey');

		if ($cartKey == "") {
			return false;
		}

		$TeamStoreModel		= new TeamStoreModel;
		$post 	=	$request->all();

		$grouped_item 	= $TeamStoreModel->selectTeamStoreGroupByCartKey($cartKey);
		$store_id = $grouped_item[0]->StoreId;
		$vocher = $post['voucher'];
		$store_array 	= $TeamStoreModel->selectTeamStore('Id', $grouped_item[0]->StoreId);
		$getSubtotal 	= $TeamStoreModel->getSubtotal($cartKey);

		if ($cartKey != null) {
			$shippingFee =  app(\App\Http\Controllers\paypal\PaypalController::class)->getShippingFee($cartKey);
			$tax = app(\App\Http\Controllers\paypal\PaypalController::class)->getTax($cartKey);
		} else {
			$shippingFee = 0;
			$tax = [];
		}

		$data = array(
			'store_id' => $store_id,
			'voucher' => $vocher
		);

		$getVoucher 	= $TeamStoreModel->selectVoucher($data);
		$now = Carbon::now();

		if ($getVoucher) {
			$items 	 		= $TeamStoreModel->myCart($cartKey);

			// check if if voucher is already in used;
			foreach ($items  as $item) {

				if ($item->VoucherId) {
					return response()->json(array(
						'success' => false,
						'message' => 'You can only apply one voucher per order.'
					));
				}

				if ($getVoucher[0]->Id == $item->VoucherId) {
					return response()->json(array(
						'success' => false,
						'message' => 'This voucher is already in used.'
					));
				}

				if ($getVoucher[0]->Status == 'Inactive') {
					return response()->json(array(
						'success' => false,
						'message' => 'This voucher is inactive.'
					));
				}

				if ($getVoucher[0]->VoucherExpiryDate < $now) {
					return response()->json(array(
						'success' => false,
						'message' => 'This voucher has expired.'
					));
				}

				if ($getVoucher[0]->VoucherType === "Flat") {

					if (Auth::guest()) {
						return response()->json(array(
							'success' => false,
							'message' => 'Log-in first to use this voucher.',
						));
					}

					$userId 		= Auth::user()->id;
					$isUsed = $TeamStoreModel->checkVoucher($userId, $getVoucher[0]->Id);

					if (count($isUsed) >= 1) {
						return response()->json(array(
							'success' => false,
							'message' => 'You already used this voucher.',
						));
					}

					if ($getSubtotal[0]->Subtotal <= $getVoucher[0]->VoucherValue) {
						return response()->json(array(
							'success' => false,
							'message' => 'Please add another item to redeem this voucher.',
						));
					}
				}

				if ($getVoucher[0]->VoucherType === "Shipping" && $getVoucher[0]->UserId != null) {

					if (Auth::guest()) {
						return response()->json(array(
							'success' => false,
							'message' => 'Log-in first to use this voucher.',
						));
					}

					$userId 		= Auth::user()->id;
					// $isUsed = $TeamStoreModel->checkVoucher($userId, $getVoucher[0]->Id);

					if ($getVoucher[0]->UserId != $userId) {
						return response()->json(array(
							'success' => false,
							'message' => 'Invalid voucher.',
						));
					}

					// if ($getSubtotal[0]->Subtotal <= $getVoucher[0]->VoucherValue) {
					// 	return response()->json(array(
					// 		'success' => false,
					// 		'message' => 'Please add another item to redeem this voucher.',
					// 	));
					// }
				}
			}

			// insert vocuher to cart_tmp
			$voucherData = array(
				'VoucherId'		=> $getVoucher[0]->Id,
				'StoreURL'		=> $store_array[0]->StoreUrl,
				'StoreId'		=> $store_array[0]->Id,
				'CartKey' 	 	=> $cartKey,
				'ProductName' 	=> $getVoucher[0]->VoucherCode,
				'Price'			=> '00.00',
				'Quantity'		=> 1
			);

			$i = $TeamStoreModel->insertToCart($voucherData);
			$lastId = $i['lastId'];
			$removeItemURL = url('removeitem') . '/' . $lastId;

			//get all voucher used.
			$updated_items 	 		= $TeamStoreModel->myCart($cartKey);
			foreach ($updated_items as $item) {
				if ($item->VoucherId != null) {
					$voucherIds[] = $item->VoucherId;
				}
			}

			$vouchers 	= $TeamStoreModel->selectVoucherWhereIn($voucherIds);

			$totalValue = 0;
			if (!empty($vouchers)) {
				foreach ($vouchers as $voucher) {
					$totalValue = $totalValue + $voucher->VoucherValue;
					if ($voucher->VoucherType == "Percentage") {
						$voucherData = array(
							'totalValue' => $totalValue,
							'type' => 'Percentage'
						);
					} else if ($voucher->VoucherType == "Flat") {
						$voucherData = array(
							'totalValue' => $totalValue,
							'type' => 'Flat'
						);
					} else {
						$voucherData = array(
							'totalValue' => $totalValue,
							'type' => 'Shipping'
						);
						$shippingFee = 0;
					}
				}

				// voucher computation
				if ($voucherData['type'] == "Percentage") {
					$getPercentageValue = $voucherData['totalValue'] / 100;
					$getDiscountValue = ($getSubtotal[0]->Subtotal * $getPercentageValue);
					$finalSubTotal = $getSubtotal[0]->Subtotal - $getDiscountValue;
				} else if ($voucherData['type'] == "Flat") {
					$finalSubTotal =  $getSubtotal[0]->Subtotal - $voucherData['totalValue'];
				} else {
					$finalSubTotal =  $getSubtotal[0]->Subtotal;
				}
			} else {
				$finalSubTotal =  $getSubtotal[0]->Subtotal;
			}

			if ($getVoucher[0]->VoucherType == "Percentage") {
				$offData = $getVoucher[0]->VoucherValue . '%' . ' OFF';
			} else if ($voucherData['type'] == "Flat") {
				$offData = $getVoucher[0]->VoucherValue . ' ' . $store_array[0]->StoreCurrency . ' OFF';
			} else if ($voucherData['type'] == "Shipping") {
				$offData = "";
			}



			$message = '<div class="btn-group mb-2">
							<button type="button" class="btn btn-black btn-sm dropdown-toggle"  data-bs-toggle="dropdown">' . $getVoucher[0]->VoucherCode . ' ' . $offData . '</button>
							<ul class="dropdown-menu">
								<li><a class="dropdown-item" href="' . $removeItemURL . '">Remove</a></li>
							</ul>
						</div>';

			// return success
			return response()->json(array(
				'success' => true,
				'message' => $message,
				'shippingFee' => number_format($shippingFee, 2),
				'total' =>  number_format($finalSubTotal + $shippingFee + $tax["tax"], 2),
				'subtotal' =>  number_format($finalSubTotal, 2),
				'tax' => $tax["tax"],
				'remaining_shippingfee' => number_format(99 - $finalSubTotal, 2)
			));
		} else {

			return response()->json(array(
				'success' => false,
				'message' => "Sorry, the voucher code is invalid. Please try again."
			));
		}
	}

	public function checkout(Request $request)
	{
		$m						= new TeamStoreModel;
		$cartKey 				= $request->session()->get('cartkey');

		$usermodel 				= new UserModel;
		$userId 				= Auth::user()->id;

		$array_address_book		= 	$usermodel->selectAddresBook('UserId', $userId);

		// var_dump($array_address_book);

		$items 	 		= $m->myCart($cartKey);

		$getSubtotal 	= $m->getSubtotal($cartKey);

		return view('sublayouts.checkout')
			->with('row', $items)
			->with('getSubtotal', $getSubtotal)
			->with('array_address_book', $array_address_book);
	}

	public function mail()
	{
		// $user = User::find(1)->toArray();

		// var_dump($user);

		// Mail::send('emails.mailExample', $user, function($message) use ($user) {
		// 	$message->to($user->email);
		// 	$message->subject('E-Mail Example');
		// });


		// dd('Mail Send Successfully');
		Mail::raw('Text to e-mail', function ($message) {
			$message->from('us@example.com', 'Laravel');

			$message->to('frank.begornia@yahoo.com')->subject('sample email');
		});
	}

	public function contact()
	{
		return view('contact');
	}

	public function selectTemplates()
	{
		$m 		= new TemplatesModel;
		$data 	 = $m->selectAllTemplate();
		return view('merchbay.templates')
			->with('row', $data);
	}

	public function contactUsSend(Request $request)
	{
		$post 	=	$request->all();

		$post['captcha'] = $this->captchaCheck();

		$validator = Validator::make(
			$post,
			[
				'emailAddress' 				=> 'required',
				'fullname' 				=> 'required',
				'message' => 'required',
				'g-recaptcha-response'  => 'required',
				'captcha'               => 'required|min:1'
			],
			[
				'g-recaptcha-response.required' => 'Captcha is required',
				'captcha.min'           		=> 'Wrong captcha, please try again.'
			]
		);


		if ($validator->fails()) {
			$errors = "";
			foreach ($validator->errors()->all() as $error) {
				$errors .= "<li>" . $error . "</li>";
			}
			$message = '
				<div class="alert alert-danger alert-dismissible fade show" role="alert">
					<strong>Error!</strong>' . $errors .
				'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
				</div>';
			Session::flash('contactUserError', 	$message);
			return Redirect::back();
		}

		$data = array(
			'name' => $post['fullname'],
			'emailAddress' => $post['emailAddress'],
			'msg' => $post['message'],
			'receiver'   => 'angelo@merchbay.com',
			'email_cc' => ['webmaster@merchbay.com', 'orders@minijerzeys.com'],
			'subject' => 'Merchbay - Contact Us Page',
		);

		Mail::send('emails.contact_us', $data, function ($msg) use ($data) {
			$msg->from('support@merchbay.com', 'Merchbay Contact Us Page');
			$msg->bcc($data['email_cc'], 'Merchbay Contact Us Page');
			$msg->to($data['receiver'])->subject($data['subject']);
		});

		$contactUsUrl =  url('/contact-us');
		echo '<script>
        			alert("Your message is successfully sent.");
							window.location = "' . $contactUsUrl . '" 
        		</script>';
	}
}
