<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\admin\AdminModel;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
// use Validator;
use App\User;


class AdminController extends Controller

{
	public function dashboard()
	{

		return view('admin_pages.dashboard');
	}

	public function orders()
	{
		$AdminModel 	    = new AdminModel;
		$array_payment_details = 	$AdminModel->selectPaymentDetails('All', null);
		// var_dump($array_payment_details);
		return view('admin_pages.orders')
			->with('array_payment_details', $array_payment_details);
	}

	public function viewOrders($ck)
	{
		$AdminModel 	    = new AdminModel;
		$order_item_array 	= $AdminModel->selectOrderItem('CartKey', $ck);
		$item_goup_array 	= $AdminModel->itemGroup($ck);
		$item_thumbs 		= $AdminModel->selectDisplayItemThumb();
		$array_payment_details 	= 	$AdminModel->selectPaymentDetails('CartKey', $ck);
		$array_shipping_add  = $AdminModel->selectShippingAddress('PaymentDetail_Id', $array_payment_details[0]->Id);


		if (empty($array_shipping_add)) {
			$array_payment_details = array();
		}

		return view('admin_pages.order_details')
			->with('array_payment_details', $array_payment_details)
			->with('img_thumb', $item_thumbs)
			->with('item_goup_array', $item_goup_array)
			->with('order_item_array', $order_item_array)
			->with('array_shipping_add', $array_shipping_add);
	}

	public function createStore()
	{
		$AdminModel 	    = new AdminModel;
		return view('admin_pages.create_store');
	}

	public function printOrder($ck)
	{
		$AdminModel 	    = new AdminModel;
		// $array_shipping_add = null;
		$order_item_array 	= $AdminModel->selectOrderItem('CartKey', $ck);
		$item_goup_array 	= $AdminModel->itemGroup($ck);
		$item_thumbs 		= $AdminModel->selectDisplayItemThumb();
		$array_payment_details 	= 	$AdminModel->selectPaymentDetails('CartKey', $ck);
		$array_shipping_add  = $AdminModel->selectShippingAddress('PaymentDetail_Id', $array_payment_details[0]->Id);
		return view('admin_pages.print_order')
			->with('array_payment_details', $array_payment_details)
			->with('img_thumb', $item_thumbs)
			->with('item_goup_array', $item_goup_array)
			->with('order_item_array', $order_item_array)
			->with('array_shipping_add', $array_shipping_add);
	}

	public function downloadPrintFile_tshirt($dc, $id)
	{
		$AdminModel 	    = new AdminModel;
		$client_design_array 	= $AdminModel->selectClientDesign($dc);
		$order_item_array 	= $AdminModel->selectOrderItem('Id', $id);

		return view('admin_pages.download_pages.tshirt')
			->with('client_design_array', $client_design_array)
			->with('order_item_array', $order_item_array);
	}

	public function downloadPrintFile_jersey($dc, $id)
	{
		$AdminModel 	    = new AdminModel;
		$client_design_array 	= $AdminModel->selectClientDesign($dc);
		$order_item_array 	= $AdminModel->selectOrderItem('Id', $id);
		// var_dump($order_item_array);
		return view('admin_pages.download_pages.jersey')
			->with('client_design_array', $client_design_array)
			->with('order_item_array', $order_item_array);
	}

	public function downloadPrintFile_shorts($dc, $id)
	{
		$AdminModel 	    = new AdminModel;
		$client_design_array 	= $AdminModel->selectClientDesign($dc);
		$order_item_array 	= $AdminModel->selectOrderItem('Id', $id);
		// var_dump($order_item_array);
		return view('admin_pages.download_pages.shorts')
			->with('client_design_array', $client_design_array)
			->with('order_item_array', $order_item_array);
	}

	public function downloadPrintFile_mask($dc, $id)
	{
		$AdminModel 	    = new AdminModel;
		$client_design_array 	= $AdminModel->selectClientDesign($dc);
		$order_item_array 	= $AdminModel->selectOrderItem('Id', $id);
		// var_dump($order_item_array);
		return view('admin_pages.download_pages.mask')
			->with('client_design_array', $client_design_array)
			->with('order_item_array', $order_item_array);
	}




	public function download(Request $request)
	{
		$post 	=	$request->all();
		$svgText = $post['svgText'];
		$filename = $post['filename'];
		header('Content-type: image/svg+xml');
		header('Content-Disposition: attachment; filename="' . $filename . '.svg"');
		echo '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
		print "$svgText";
	}

	public function saveNewStore(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel 	    = new AdminModel;

		$store_name = $post['store_name'];
		$store_url = $post['store_url'];
		$store_currency = $post['store_currency'];

		if ($post['store_status'] == "Public") {
			$store_status = "true";
		} else {
			$store_status = "false";
		}

		if (isset($post['set_store_password'])) {
			$store_password = $post['store_password'];
		} else {
			$store_password = null;
		}

		$check_store_url = array(
			'StoreUrl' => $store_url
		);

		$validator = Validator::make(
			$check_store_url,
			[
				'StoreUrl' 			=> 'unique:teamstores'
			],
			[
				'StoreUrl.unique' => 'The Store URL has already been taken.',
			]
		);


		if ($validator->fails()) {
			$errors = "";

			foreach ($validator->errors()->all() as $error) {
				$errors .= "<li>" . $error . "</li>";
			}

			return response()->json(array(
				'success' => false,
				'clearform'  => false,
				'message' => $errors
			));
		}




		$store_logo_name    = 'logo.' . $request->file('store_logo')->getClientOriginalExtension();
		$store_banner_name = 'banner.' . $request->file('store_banner')->getClientOriginalExtension();


		$data = array(
			'StoreUrl'		=> $store_url,
			'ImageFolder'	=> $store_url,
			'Password'		=> $store_password,
			'HashId' 	 	=> md5($store_url),
			'StoreName' 	=> $store_name,
			'StoreLogo'	    => $store_logo_name,
			'StoreBanner' 	=> $store_banner_name,
			'StoreCurrency' => $store_currency,
			'IsActive'      => $store_status
		);

		$res 	= $AdminModel->insertTeamstore($data);

		if ($res) {

			Storage::disk('uploads')->put('/uploads/images/teamstore/' .   $store_url . '/'  . $store_logo_name, fopen($request->file('store_logo'), 'r+'));
			Storage::disk('uploads')->put('/uploads/images/teamstore/' .   $store_url . '/'  . $store_banner_name, fopen($request->file('store_banner'), 'r+'));

			return response()->json(array(
				'success' => true,
				'clearform'  => true,
				'message' => 'Store is successfully created.'
			));
		} else {
			return response()->json(array(
				'success' => false,
				'clearform'  => true,
				'message' => 'Something went wrong. Please refresh the page and try again.'
			));
		}
	}

	public function storeList()
	{
		$AdminModel 	    = new AdminModel;
		$q = null;
		$sort = null;

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

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

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

			if ($q != "") {
				// keyword and sort
				$teamstore_array 	= $AdminModel->selectTeamstoreSearch($field, $sort_value, $q);
			} else {
				// sort only
				$teamstore_array 	= $AdminModel->selectTeamstoreFilter($field, $sort_value);
			}
		} else {
			// first load
			$teamstore_array 	= $AdminModel->selectTeamstore();
		}

		return view('admin_pages.list_of_stores')
			->with('teamstore_array', $teamstore_array)
			->with('keyword', $q)
			->with('filter', $sort);
	}

	public function viewStore($id)
	{

		$AdminModel 	    = new AdminModel;
		$teamstore_array 	= $AdminModel->selectTeamstoreById($id);
		$store_owners_array 	= $AdminModel->selectStoreOwners($id);

		return view('admin_pages.edit_store')
			->with('teamstore_array', $teamstore_array)
			->with('store_owners_array', $store_owners_array);
	}

	public function updateStore(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel 	    = new AdminModel;

		$store_id   = $post['store_id'];
		$store_name     = $post['store_name'];
		$store_url      = $post['store_url'];
		$orig_store_url = $post['orig_store_url'];
		$store_currency = $post['store_currency'];


		if ($post['store_status'] == "Public") {
			$store_status = "true";
		} else {
			$store_status = "false";
		}

		if (isset($post['set_store_password'])) {
			$store_password = $post['store_password'];
		} else {
			$store_password = null;
		}

		if ($request->file('store_logo') != null) {
			$store_logo_name    = 'logo.' . $request->file('store_logo')->getClientOriginalExtension();
		} else {
			$store_logo_name = $post['orig_store_logo'];
		}

		if ($request->file('store_banner') != null) {
			$store_banner_name = 'banner.' . $request->file('store_banner')->getClientOriginalExtension();
		} else {
			$store_banner_name = $post['orig_store_banner'];
		}


		if ($orig_store_url != $store_url) {

			$check_store_url = array(
				'StoreUrl' => $store_url
			);

			$validator = Validator::make(
				$check_store_url,
				[
					'StoreUrl' 			=> 'unique:teamstores'
				],
				[
					'StoreUrl.unique' => 'The Store URL has already been taken.',
				]
			);


			if ($validator->fails()) {
				$errors = "";

				foreach ($validator->errors()->all() as $error) {
					$errors .= "<li>" . $error . "</li>";
				}

				return response()->json(array(
					'success' => false,
					'clearform'  => false,
					'message' => $errors
				));
			}
		}

		$data = array(
			'StoreUrl'		=> $store_url,
			// 'ImageFolder'	=> $store_url,
			'Password'		=> $store_password,
			'HashId' 	 	=> md5($store_url),
			'StoreName' 	=> $store_name,
			'StoreLogo'	    => $store_logo_name,
			'StoreBanner' 	=> $store_banner_name,
			'StoreCurrency' => $store_currency,
			'IsActive'      => $store_status
		);

		// var_dump($data);


		$res 	= $AdminModel->updateTeamstore($store_id, $data);
		// var_dump($res);
		// if($res){
		if ($request->file('store_logo') != null) {
			Storage::disk('uploads')->put('/uploads/images/teamstore/' .   $orig_store_url . '/'  . $store_logo_name, fopen($request->file('store_logo'), 'r+'));
		}

		if ($request->file('store_banner') != null) {
			Storage::disk('uploads')->put('/uploads/images/teamstore/' .   $orig_store_url . '/'  . $store_banner_name, fopen($request->file('store_banner'), 'r+'));
		}

		return response()->json(array(
			'success' => true,
			'clearform'  => false,
			'message' => 'Store is successfully updated.'
		));

		// }else{
		//     return response()->json(array(
		//         'success' => false, 
		//         'clearform'  => true,
		// 		'message' => 'Something went wrong. Please refresh the page and try again.'
		// 	));
		// }

	}

	public function deleteStore(Request $request)
	{
		$AdminModel 	    = new AdminModel;
		$post 	=	$request->all();
		$teamstore_array 	= $AdminModel->selectTeamstoreById($post['id']);

		if ($teamstore_array[0]->StoreUrl == $post['store_url']) {
			$res 	= $AdminModel->deleteTeamstoreById($post['id']);

			if ($res) {
				return response()->json(array(
					'success' => true,
					'message' => 'This Store is successfully deleted.'
				));
			} else {
				return response()->json(array(
					'success' => false,
					'message' => 'Something went wrong. Please refresh the page and try again.'
				));
			}
		} else {
			return response()->json(array(
				'success' => false,
				'message' => 'Something went wrong. Please refresh the page and try again.'
			));
		}
	}


	public function overlayPattern()
	{
		$AdminModel 	    = new AdminModel;
		$pattern_array 	= $AdminModel->selectPattern();

		return view('admin_pages.overlay_pattern')
			->with('pattern_array', $pattern_array);
	}

	public function viewOverlayPattern($id)
	{

		$AdminModel 	    = new AdminModel;
		$pattern_array 	= $AdminModel->selectPatternWithfield('Id', $id);

		return view('admin_pages.edit_overlay_pattern')
			->with('pattern_array', $pattern_array);
	}

	public function viewReports()
	{
		$AdminModel				= new AdminModel;

		$array_store_orders = $AdminModel->selectStoreOrders();
		// var_dump($array_store_orders);
		return view('admin_pages.reports')
			->with('array_store_orders', $array_store_orders);
	}

	public function addClipart()
	{
		$AdminModel 	    = new AdminModel;
		$clipart_categories_array 	= $AdminModel->selectClipartCategory();

		return view('admin_pages.add_clipart')
			->with('clipart_categories_array', $clipart_categories_array);
	}

	public function saveClipartCategory(Request $request)
	{
		$post 	        =	$request->all();
		$AdminModel 	=   new AdminModel;

		$data =  array(
			'CategoryName'  => $post['category'],
			'IsActive'      => $post['is_active']
		);

		$res 	= $AdminModel->insertClipartCategory($data);
		// var_dump($res);
		if ($res) {
			return response()->json(array(
				'success' => true,
				'addClass' => 'modal-close-reload',
				'message' => 'Clipart Category is successfully added.',
				'last_inserted_id' => $res
			));
		} else {
			return response()->json(array(
				'success' => false,
				'addClass' => '',
				'message' => 'Something went wrong. Please refresh the page and try again.'
			));
		}
	}

	public function saveSVGClipart(Request $request)
	{
		$post 	        =	$request->all();
		$AdminModel 	= new AdminModel;

		$category       = $post['category'];
		$tags           = $post['clipart_tags'];
		$orig_filename  = $request->file('upload_clipart')->getClientOriginalName();

		$lower_filename = str_replace(' ', '-', strtolower($orig_filename));
		$getExt 	    = substr($lower_filename, strrpos($lower_filename, '.'));;
		$clean_filename = preg_replace("/\.[^.\s]{3,4}$/", "", $lower_filename);
		$final_filename = $clean_filename . "-" . uniqid() . $getExt;

		$data = array(
			'CategoryId' =>    $category,
			'OriginalSVGFilename' => $orig_filename,
			'SVGFilename' => $final_filename,
			'Tags' =>       $tags,
			'IsActive' => 1,
		);


		$res = $AdminModel->insertClipart($data);
		Storage::disk('uploads')->put('/uploads/images/cliparts/' . $final_filename, fopen($request->file('upload_clipart'), 'r+'));

		if ($res) {
			return response()->json(array(
				'success' => true,
				'message' => 'Clipart is successfully added.'
			));
		}
	}

	function userList()
	{

		$AdminModel 	    = new AdminModel;
		$result = $AdminModel->userList();

		return response()->json([
			"count" => count($result),
			"results" => $result
		]);
	}

	function updatUserAsStoreOwner(Request $request)
	{
		$AdminModel 	    = new AdminModel;

		$data = array(
			'user_id'		=>  $request->user_id,
			'store_id'	=> $request->store_id
		);

		$res = $AdminModel->makeUserAsStoreOwner($data);

		return response()->json([
			"result" =>  $res
		]);
	}

	public function removeStoreAccess(Request $request)
	{


		$AdminModel 	    = new AdminModel;

		$data = array(
			'user_id'		=>  $request->id,
			'store_id'	    => null
		);

		$res = $AdminModel->model_removeStoreAccess($data);

		return response()->json([
			"result" =>  $res
		]);
	}

	public function saveNewStoreOwner(Request $request)
	{
		$AdminModel 	    = new AdminModel;
		$post 	=	$request->all();

		$validator = Validator::make($post, [
			'username' 				=> 'unique:user_logins',
			'email' 				=> 'unique:user_logins'
		]);


		if ($validator->fails()) {
			$errors = "";
			foreach ($validator->errors()->all() as $error) {
				$errors .= "<li>" . $error . "</li>";
			}

			$message = '
			<div class="alert alert-danger alert-dismissible">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
					<h4><i class="icon fa fa-ban"></i> ERROR:</h4>
					' . $errors .
				'</div>';

			return response()->json(array(
				'success' => false,
				'message' => $message
			));
		}

		User::create([
			'name' => $post['name'],
			'username' => $post['username'],
			'email' => $post['email'],
			'password' => bcrypt($post['password']),
			'role' => 'store_owner',
			'store_id' => $post['store_id'],
		]);

		return response()->json(array(
			'success' => true
		));
	}

	public function viewClipartCategories()
	{
		$AdminModel 	    = new AdminModel;
		$clipart_categories_array 	= $AdminModel->ClipartCategory();
		return view('admin_pages.clipart_categories')
			->with('clipart_categories_array', $clipart_categories_array);
	}

	public function deleteClipartCategory(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel 	    = new AdminModel;

		$res 	= $AdminModel->deleteClipartCategory($post['id']);

		if ($res) {
			return response()->json(array(
				'success' => true,
				'message' => "Clipart Category is successfully deleted."
			));
		}
	}

	public function saveClipartCatOrdering(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel 	    = new AdminModel;

		$arrayClipartCat = $post['clip_cat_id'];
		$order = 1;

		foreach ($arrayClipartCat as $item) {
			$i = $AdminModel->updateClipartCatOrdering($order, $item);
			$order++;
		}

		return response()->json(array(
			'success' => true,
			'message' => "Clipart Category ordering is succcessfully updated!"
		));
	}

	public function updateClipartCategory(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel 	    = new AdminModel;

		$id = $post['id'];
		$category = $post['category'];
		$is_active = $post['is_active'];

		$data = array(
			'CategoryName' =>  $category,
			'IsActive' => $is_active
		);

		$res 	= $AdminModel->updateClipartCategory($id, $data);

		if ($res) {
			return response()->json(array(
				'success' => true,
				'message' => "Clipart Category ordering is succcessfully updated!"
			));
		} else {
			return response()->json(array(
				'success' => false,
				'message' => "Something went wrong. Please refresh the page and try again."
			));
		}
	}

	public function viewClipart()
	{

		$clipart_category = request()->get('clipart_category');

		$AdminModel 	            = new AdminModel;
		$clipart_array 	= $AdminModel->selectCliparts($clipart_category);
		$clipart_categories_array 	= $AdminModel->selectClipartCategory();

		return view('admin_pages.cliparts')
			->with('clipart_array', $clipart_array)
			->with('clipart_categories_array', $clipart_categories_array)
			->with('selected_clipart_category', $clipart_category);
	}

	public function visualizerAdd()
	{
		$AdminModel 	            = new AdminModel;
		$sports_array 	= $AdminModel->selectSports();
		$pattern_array 	= $AdminModel->selectPattern();

		return view('admin_pages.add_visualizer')
			->with('sports_array', $sports_array)
			->with('pattern_array', $pattern_array);
	}


	public function selectSportsCategory(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel   = new AdminModel;
		$sports_category_array 	= $AdminModel->selectSportsCategory($post['id']);

		return response()->json(array(
			'success' =>    true,
			'data' =>        $sports_category_array
		));
	}


	public function getOverlayPattern()
	{
		$AdminModel 	            = new AdminModel;
		$pattern_array 	= $AdminModel->selectPattern();
		return response()->json(array(
			'success' =>    true,
			'data'      =>  $pattern_array
		));
	}

	public function saveNewVisualizer(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel   = new AdminModel;
		$tmp_arr_visualizer_pattern = array();
		$template_thumbnail_path = "/uploads/images/templates/thumbnail/";
		$template_path = "/uploads/images/uniform-templates/";

		foreach ($post['visualizer_pattern'] as $item_visualizer) {
			$arr_visualizer_pattern = explode("##", $item_visualizer);
			array_push($tmp_arr_visualizer_pattern, $arr_visualizer_pattern['0']);
		}

		$orig_visualizer_thumbnail_filename  = $request->file('visualizer_thumbnail')->getClientOriginalName();

		$new_visualizer_thumbnail_filename = $this->generateFileName($orig_visualizer_thumbnail_filename);
		Storage::disk('uploads')->put($template_thumbnail_path . $new_visualizer_thumbnail_filename, fopen($request->file('visualizer_thumbnail'), 'r+'));

		$final_arr_visualizer_pattern = implode(",", $tmp_arr_visualizer_pattern);

		$data = array(
			'SportsId'      => $post['sportName'],
			'Category'      => $post['sport_category'],
			'Thumbnail'     => $template_thumbnail_path . $new_visualizer_thumbnail_filename,
			'TemplateName'  => $post['visualizer_name'],
			'Trim'          => $post['numberOfTrims'],
			'PatternId'     => $final_arr_visualizer_pattern,
			'WithGradient'  => ($post['visualizer_format'] == "png") ? 'no' : null,
			'TemplateFormat' => $post['visualizer_format'],
			'IsActive'      => "TRUE",
			'Tags'      => $post['visualizer_tags'],
		);


		$res_saveNewVisualizer   = $AdminModel->saveNewVisualizer($data);

		$templateCode = "TEMP-" . str_pad($res_saveNewVisualizer['lastId'], 5, '0', STR_PAD_LEFT);
		$data_to_update = array(
			'TemplateCode'      => $templateCode,
			'HashTemplateCode'  => md5($templateCode)
		);

		$res_updateVisualizer   = $AdminModel->updateVisualizer($res_saveNewVisualizer['lastId'], $data_to_update);

		$data_def_main_color = array(
			'TemplateCode'      => $templateCode,
			'RGBColor'          => $post['main_body_def_color'],
			'DisplayName'       => $post['main_body_label']
		);

		$res_saveVisualizerDefaultBodyColor   = $AdminModel->saveVisualizerDefaultBodyColor($data_def_main_color);

		if ($post['numberOfTrims'] != 0) {
			for ($i = 0; $i < $post['numberOfTrims']; $i++) {
				$t = $i + 1;
				$data_def_trim_color = array(
					'TrimNumber'      => $t,
					'TemplateCode'    => $templateCode,
					'RGBColor'        => $post['trim_def_color'][$i],
					'DisplayName'     => $post['trim_label'][$i]
				);
				$AdminModel->saveVisualizerDefaultTrimColor($data_def_trim_color);
			}
		}

		// front saving 
		if (isset($post['front_visualizer'])) {
			$orig_front_visualize_filename  = $request->file('front_visualizer')->getClientOriginalName();

			$new_front_visualize_filename = $this->generateFileName($orig_front_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_front_visualize_filename, fopen($request->file('front_visualizer'), 'r+'));

			$data_front_visualizer = array(
				'TemplateCode'      => $templateCode,
				'HashTemplateCode'  => md5($templateCode),
				'Type'              => $post['front_visualizer_type'],
				'Side'              => "Front",
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_front_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->saveVisualizerPath($data_front_visualizer);
			// var_dump($data_front_visualizer);

		}

		// back saving
		if (isset($post['back_visualizer'])) {
			$orig_front_visualize_filename  = $request->file('back_visualizer')->getClientOriginalName();

			$new_back_visualize_filename = $this->generateFileName($orig_front_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_back_visualize_filename, fopen($request->file('back_visualizer'), 'r+'));

			$data_back_visualizer = array(
				'TemplateCode'      => $templateCode,
				'HashTemplateCode'  => md5($templateCode),
				'Type'              => $post['back_visualizer_type'],
				'Side'              => "Back",
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_back_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->saveVisualizerPath($data_back_visualizer);
		}

		// right saving
		if (isset($post['right_visualizer'])) {
			$orig_right_visualize_filename  = $request->file('right_visualizer')->getClientOriginalName();

			$new_right_visualize_filename = $this->generateFileName($orig_right_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_right_visualize_filename, fopen($request->file('right_visualizer'), 'r+'));

			$data_right_visualizer = array(
				'TemplateCode'      => $templateCode,
				'HashTemplateCode'  => md5($templateCode),
				'Type'              => $post['right_visualizer_type'],
				'Side'              => "Right",
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_right_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->saveVisualizerPath($data_right_visualizer);
		}

		// left saving 
		if (isset($post['left_visualizer'])) {
			$orig_left_visualize_filename  = $request->file('left_visualizer')->getClientOriginalName();

			$new_left_visualize_filename = $this->generateFileName($orig_left_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_left_visualize_filename, fopen($request->file('left_visualizer'), 'r+'));

			$data_left_visualizer = array(
				'TemplateCode'      => $templateCode,
				'HashTemplateCode'  => md5($templateCode),
				'Type'              => $post['left_visualizer_type'],
				'Side'              => "Left",
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_left_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->saveVisualizerPath($data_left_visualizer);
		}

		return response()->json(array(
			'success' =>  true,
			'message' => "Visualizer is successfully added."
		));
	}


	public function generateFileName($filename)
	{

		$lower_filename = str_replace(' ', '-', strtolower($filename));
		$getExt 	    = substr($lower_filename, strrpos($lower_filename, '.'));;
		$clean_filename = preg_replace("/\.[^.\s]{3,4}$/", "", $lower_filename);
		$final_filename = date('Ymd') . "-" . time() . '-' . $clean_filename . "-" . $getExt;

		return $final_filename;
	}

	public function visualizer()
	{
		$AdminModel 	            = new AdminModel;
		$sports_array 	= $AdminModel->selectSports();
		$pattern_array 	= $AdminModel->selectPattern();

		$sport_name = request()->get('sport_name'); // Sprots Id
		$sport_category = request()->get('sport_category');

		if (isset($sport_name) && isset($sport_category)) {
			$visualizer_array =  $AdminModel->selectVisualizer($sport_name, $sport_category);
		} else {
			$visualizer_array = array();
		}

		return view('admin_pages.visualizer')
			->with('sports_array', $sports_array)
			->with('visualizer_array', $visualizer_array);
	}

	function showStoreOrderDetails(Request $request)
	{

		$post 					=	$request->all();
		// var_dump($post['pid']);
		$AdminModel				= new AdminModel;
		$array_payment_details 	= $AdminModel->selectPaymentDetails('CartKey', $post['ck']);
		$array_shipping_add 	= $AdminModel->selectShippingAddress('PaymentDetail_Id', $array_payment_details[0]->Id);

		$array_thumbnail_display = $AdminModel->selectDisplayItemThumbById($post['pid']);
		$array_item = $AdminModel->selectOrder('Id', $post['id']);
		$handle_order_detail_body = view('admin_pages.order-details-body')
			->with('array_payment_details', $array_payment_details)
			->with('array_shipping_add', $array_shipping_add)
			->with('array_thumbnail_display', $array_thumbnail_display)
			->with('array_item', $array_item)
			->render();


		return response()->json(array(
			'success' => true,
			'payment_details_response' => $handle_order_detail_body,
			'thumb' => $array_thumbnail_display,
			'item' => $array_item
		));
	}

	function viewVisualizer($id)
	{
		$AdminModel 	            = new AdminModel;
		$sports_array 	= $AdminModel->selectSports();
		$pattern_array 	= $AdminModel->selectPattern();
		$template_array 	= $AdminModel->editVisualizer($id);
		$sports_category_array 	= $AdminModel->selectSportsCategory($template_array[0]->SportsId);
		$template_pattern_array = explode(",", $template_array[0]->PatternId);
		$template_path_array 	= $AdminModel->selectTemplatePath($template_array[0]->TemplateCode);
		$default_body_color_array 	= $AdminModel->selectDefaultBodyColor($template_array[0]->TemplateCode);
		$default_trim_color_array 	= $AdminModel->selectDefaultTrimColor($template_array[0]->TemplateCode);

		return view('admin_pages.edit_visualizer')
			->with('sports_array', $sports_array)
			->with('pattern_array', $pattern_array)
			->with('template_array', $template_array)
			->with('sports_category_array', $sports_category_array)
			->with('template_path_array', $template_path_array)
			->with('default_body_color_array', $default_body_color_array)
			->with('default_trim_color_array', $default_trim_color_array)
			->with('template_pattern_array', $template_pattern_array);
	}

	function deleteVisualizer(Request $request)
	{
		$post 	        = $request->all();
		$AdminModel     = new AdminModel;

		$template_array 	= $AdminModel->editVisualizer($post['id']);

		$res_deleteVisualizer   	= $AdminModel->deleteVisualizer($post['id']);
		$res_deleteDefaultBodyColor = $AdminModel->deleteDefaultBodyColor($template_array[0]->TemplateCode);
		$res_deleteTemplatePath	    = $AdminModel->deleteTemplatePath($template_array[0]->TemplateCode);
		$res_deleteDefaultTrimColor	= $AdminModel->deleteDefaultTrimColor($template_array[0]->TemplateCode);
		$res_deletePrintPatternList	= $AdminModel->deletePrintPatternList($template_array[0]->TemplateCode);

		return response()->json(array(
			'success' =>    true,
			'message' =>        "Visualizer is successfully deleted."
		));
	}

	public function updateVisualizer(Request $request)
	{
		$post 	=	$request->all();
		$AdminModel   = new AdminModel;
		$tmp_arr_visualizer_pattern = array();
		$template_thumbnail_path = "templates/thumbnail/";
		$template_path = "uniform-templates/";
		$visualizer_id =  $post['visualizer_id'];
		$templateCode = "TEMP-" . str_pad($visualizer_id, 5, '0', STR_PAD_LEFT);

		foreach ($post['visualizer_pattern'] as $item_visualizer) {
			$arr_visualizer_pattern = explode("##", $item_visualizer);
			array_push($tmp_arr_visualizer_pattern, $arr_visualizer_pattern['0']);
		}

		if (isset($post['visualizer_thumbnail'])) {
			$orig_visualizer_thumbnail_filename  = $request->file('visualizer_thumbnail')->getClientOriginalName();

			$new_visualizer_thumbnail_filename = $this->generateFileName($orig_visualizer_thumbnail_filename);
			Storage::disk('uploads')->put($template_thumbnail_path . $new_visualizer_thumbnail_filename, fopen($request->file('visualizer_thumbnail'), 'r+'));
			$template_thumbnail = $template_thumbnail_path . $new_visualizer_thumbnail_filename;
		} else {
			$template_thumbnail = $post['current_visualizer_thumbnail'];
		}


		$final_arr_visualizer_pattern = implode(",", $tmp_arr_visualizer_pattern);

		$data = array(
			'SportsId'      => $post['sportName'],
			'Category'      => $post['sport_category'],
			'Thumbnail'     => $template_thumbnail,
			'TemplateName'  => $post['visualizer_name'],
			'Trim'          => $post['numberOfTrims'],
			'PatternId'     => $final_arr_visualizer_pattern,
			'WithGradient'  => ($post['visualizer_format'] == "png") ? 'no' : null,
			'TemplateFormat' => $post['visualizer_format'],
			'IsActive'      => $post['is_active'],
			'Tags'          => $post['visualizer_tags'],
		);

		$res_updateVisualizer   = $AdminModel->updateVisualizer($visualizer_id, $data);


		$data_def_main_color = array(
			'RGBColor'          => $post['main_body_def_color'],
			'DisplayName'       => $post['main_body_label']
		);

		$res_updateDefaultBodyColor = $AdminModel->updateDefaultBodyColor($templateCode, $data_def_main_color);

		$res_deleteDefaultTrimColor	= $AdminModel->deleteDefaultTrimColor($templateCode);

		if ($post['numberOfTrims'] != 0) {
			for ($i = 0; $i < $post['numberOfTrims']; $i++) {
				$t = $i + 1;
				$data_def_trim_color = array(
					'TrimNumber'      => $t,
					'TemplateCode'    => $templateCode,
					'RGBColor'        => $post['trim_def_color'][$i],
					'DisplayName'     => $post['trim_label'][$i]
				);
				$AdminModel->saveVisualizerDefaultTrimColor($data_def_trim_color);
			}
		}

		// // front saving 
		if (isset($post['front_visualizer'])) {
			$orig_front_visualize_filename  = $request->file('front_visualizer')->getClientOriginalName();

			$new_front_visualize_filename = $this->generateFileName($orig_front_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_front_visualize_filename, fopen($request->file('front_visualizer'), 'r+'));

			$data_front_visualizer = array(
				'Type'              => $post['front_visualizer_type'],
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_front_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->updateVisualizerPath($post['front_visualizer_id'], $data_front_visualizer);
		} else {

			$data_front_visualizer = array(
				'Type'              => $post['front_visualizer_type'],
				'TemplateFormat'    => $post['visualizer_format']
			);

			$AdminModel->updateVisualizerPath($post['front_visualizer_id'], $data_front_visualizer);
		}

		// back saving
		if (isset($post['back_visualizer'])) {
			$orig_front_visualize_filename  = $request->file('back_visualizer')->getClientOriginalName();

			$new_back_visualize_filename = $this->generateFileName($orig_front_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_back_visualize_filename, fopen($request->file('back_visualizer'), 'r+'));

			$data_back_visualizer = array(
				'Type'              => $post['back_visualizer_type'],
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_back_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->updateVisualizerPath($post['back_visualizer_id'], $data_back_visualizer);
		} else {

			$data_back_visualizer = array(
				'Type'              => $post['back_visualizer_type'],
				'TemplateFormat'    => $post['visualizer_format']
			);

			$AdminModel->updateVisualizerPath($post['back_visualizer_id'], $data_back_visualizer);
		}

		// right saving
		if (isset($post['right_visualizer'])) {
			$orig_right_visualize_filename  = $request->file('right_visualizer')->getClientOriginalName();

			$new_right_visualize_filename = $this->generateFileName($orig_right_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_right_visualize_filename, fopen($request->file('right_visualizer'), 'r+'));

			$data_right_visualizer = array(
				'Type'              => $post['right_visualizer_type'],
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_right_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->updateVisualizerPath($post['right_visualizer_id'], $data_right_visualizer);
		} else {

			$data_right_visualizer = array(
				'Type'              => $post['right_visualizer_type'],
				'TemplateFormat'    => $post['visualizer_format']
			);

			$AdminModel->updateVisualizerPath($post['right_visualizer_id'], $data_right_visualizer);
		}

		// left saving 
		if (isset($post['left_visualizer'])) {
			$orig_left_visualize_filename  = $request->file('left_visualizer')->getClientOriginalName();

			$new_left_visualize_filename = $this->generateFileName($orig_left_visualize_filename);
			Storage::disk('uploads')->put($template_path . $templateCode . '/DISPLAY/' . $new_left_visualize_filename, fopen($request->file('left_visualizer'), 'r+'));

			$data_left_visualizer = array(
				'Type'              => $post['left_visualizer_type'],
				'Path'              => $template_path . $templateCode . '/DISPLAY/' . $new_left_visualize_filename,
				'TemplateFormat'    => $post['visualizer_format'],
				'IsActive'          => "TRUE"
			);

			$AdminModel->updateVisualizerPath($post['left_visualizer_id'], $data_left_visualizer);
		} else {
			$data_left_visualizer = array(
				'Type'              => $post['left_visualizer_type'],
				'TemplateFormat'    => $post['visualizer_format']
			);

			$AdminModel->updateVisualizerPath($post['left_visualizer_id'], $data_left_visualizer);
		}

		return response()->json(array(
			'success' =>  true,
			'message' => "Visualizer is successfully updated."
		));
	}


	public function viewCommission()
	{
		$AdminModel     = new AdminModel;
		$array_commission  = $AdminModel->selectCommission();
		return view('admin_pages.commission')
			->with("array_commission", $array_commission);
	}

	public function deleteClipart(Request $request)
	{
		$post 	        = $request->all();
		$AdminModel     = new AdminModel;

		$delete_clipart_array 	= $AdminModel->deleteClipart($post['id']);

		return response()->json(array(
			'success' =>    true,
			'message' =>        "Clipart is successfully deleted."
		));
	}


	public function printFiles()
	{
		$AdminModel     = new AdminModel;
		$selectGroupPrintFiles = $AdminModel->selectGroupPrintFiles();

		return view('admin_pages.print_files')
			->with('selectPrintFiles', $selectGroupPrintFiles);
	}

	public function uploadPrintFile()
	{
		$AdminModel     = new AdminModel;
		$vilualizer_array = $AdminModel->selectVisualizerPrint();

		return view('admin_pages.upload_print_file')
			->with('vilualizer_array', $vilualizer_array);
	}

	public function uploadPrintFileSave(Request $request)
	{
		$post 	        = $request->all();
		$AdminModel     = new AdminModel;

		$template_path = "uniform-templates/" . $post['print_file_for'] . "/" .  strtoupper($post['print_file_type']) . "/SIZES/";

		for ($i = 0; $i < count($post['uploadPrintFiles']); $i++) {

			$rawName = $request->file('uploadPrintFiles')[$i]->getClientOriginalName();
			Storage::disk('uploads')->put($template_path . $rawName, fopen($request->file('uploadPrintFiles')[$i], 'r+'));

			$data = array(
				'TemplateCode'   => $post['print_file_for'],
				'Path'           => $template_path . $rawName,
				'Type'           => strtoupper($post['print_file_type']),
				'Size'           => pathinfo($rawName, PATHINFO_FILENAME)
			);
			// var_dump($data);
			$AdminModel->insertPrintFiles($data);
		}

		return response()->json(array(
			'success' =>    true,
			'message' =>     "Print Files(s) is successfully uploaded."
		));
	}

	public function printFilesDetails($tempcode)
	{
		$AdminModel     = new AdminModel;
		$selectPrintFiles = $AdminModel->selectPrintFiles($tempcode);

		if (empty($selectPrintFiles)) {
			return redirect()->away('/admin/print-files');
		}

		return view('admin_pages.view-print-file')
			->with('selectPrintFiles', $selectPrintFiles);
	}

	public function printFilesDelete(Request $request)
	{
		$post 	        = $request->all();
		$AdminModel     = new AdminModel;

		$deletePrintFiles = $AdminModel->deletePrintFiles($post['id']);

		return response()->json(array(
			'success' =>    true,
			'message' =>     "Print File is successfully deleted."
		));
	}

	public function taxIndex()
	{
		$AdminModel     = new AdminModel;
		$selectTax = $AdminModel->selectTax();
		return view('admin_pages.tax_index')->with("taxLists", $selectTax);
	}

	public function updateHibernate(Request $request){
		$post 	        = $request->all();
		$AdminModel     = new AdminModel;

		$data = array(
			'IsHibernated' => ($post['IsActive'] == 'true') ? 1 : 0
		);

		$res 	= $AdminModel->updateTeamstore($post['data'][0]['value'], $data);

		return response()->json(array(
			'success' => true,
			'message' => "successfully updated."
		));
	}
}
