<?php

namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Action\Common;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;


use App\Traits\ReferenceData;
use App\Services\ApiJwt;

class commonController extends Controller
{
	//use ReferenceData;
	use ReferenceData {
		getReferenceData as protected refData;
		getReferenceDataBM as protected refDataBM;
		getReferenceDataFilter as protected refDataFilter;
	}

	public $appType = 'SM';
	public function __construct(Request $request)
	{
		if ($request->has('debug') && $request->input('debug') == true) {
			$this->debug = true;
		}
		$this->appType = 'SM';
		if ($request->has('appType') && $request->input('appType') == true) {
			$this->appType = $request->input('appType');
		} elseif ($request->has('filters')) {
			$filter = $request->input('filters');
			if (!empty($filter['app_type'])) {
				$this->appType = 'CM';
			}
		} elseif ($request->has('app_type') && $request->input('app_type') == true) {
			$this->appType = $request->input('app_type');
		}
	}

	public function delSMAccount(Request $request)
	{
		if ($request->has("accessToken") && $request->has("resourceType") && $request->has("appType")) {
			$accessToken = $request->input('accessToken');
			$resourceType = $request->input('resourceType');
			$appType = $request->input('appType');

			if ($resourceType != 'app') {
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Insufficient parameters.")));
			}

			$auth = new authentication();
			$user_id = $auth->authToken($accessToken, $appType);
			if ($user_id) {
				if (!empty($user_id) && is_numeric($user_id) && $user_id != '' && $user_id != 0) {

					include_once('/home/steelmin/public_html/hf.php');
					insert_commment_for_deleted_ids($user_id, $accessToken, $appType, $resourceType);
					$del_res  = shift_delete_memids($user_id);
					if ('Data Deleted' == $del_res)
						return new JsonResponse(array("status" => array("code" => 1001, "message" => "Your account with SteelMint has been deleted successfully.")));
					else
						return new JsonResponse(array("status" => array("code" => 2100, "message" => "An error occurred while deleting the account.")));
				} else
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "User Id blank.")));
			} else {
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Access token is invalid or has expired")));
			}
		} else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => "Insufficient parameters.")));
		}
	}

	public function appMenuData(Request $request)
	{
		$data = [
			[
				"id" => "1",
				"level" => 1,
				"name" => "My portfolio",
				"url" => ""
			],
			[
				"id" => "2",
				"level" => 1,
				"name" => "Prices",
				"url" => "",
				"subItems" => [
					[
						"level" => 2,
						"name" => "Ferrous Metals",
						"url" => "",
						"subItems" => [
							[
								"level" => 3,
								"name" => "Iron Ore",
								"url" => "",
								"subItems" => [
									[
										"id" => "433",
										"level" => 4,
										"name" => "Fines/Lumps",
										"url" => "",
										"root" => "Prices",
										"parent" => "Iron Ore",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "434",
										"level" => 4,
										"name" => "Pellets",
										"url" => "",
										"root" => "Prices",
										"parent" => "Iron Ore",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "877",
										"level" => 4,
										"name" => "Concentrates",
										"url" => "",
										"root" => "Prices",
										"parent" => "Iron Ore",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "1703",
										"level" => 4,
										"name" => "Iron ore Vessel Freight",
										"url" => "",
										"root" => "Prices",
										"parent" => "Iron Ore",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Coal",
								"url" => "",
								"subItems" => [
									[
										"id" => "417",
										"level" => 4,
										"name" => "Non Coking",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "415",
										"level" => 4,
										"name" => "Coking",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "416",
										"level" => 4,
										"name" => "Met Coke",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "1814",
										"level" => 4,
										"name" => "Coal Vessel Freight",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Scrap & Metallics",
								"url" => "",
								"subItems" => [
									[
										"id" => "443",
										"level" => 4,
										"name" => "Sponge Iron",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "441",
										"level" => 4,
										"name" => "Pig Iron",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "439",
										"level" => 4,
										"name" => "Melting Scrap",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "442",
										"level" => 4,
										"name" => "Rerolling scrap",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "440",
										"level" => 4,
										"name" => "Mill Scale",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Steel",
								"url" => "",
								"subItems" => [
									[
										"id" => "471",
										"level" => 4,
										"name" => "Billet/Bloom/Ingot",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "466",
										"level" => 4,
										"name" => "Rebar",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "468",
										"level" => 4,
										"name" => "Structure",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "469",
										"level" => 4,
										"name" => "Wire Rod",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "457",
										"level" => 4,
										"name" => "HRC",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "456",
										"level" => 4,
										"name" => "HR Plate",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "914",
										"level" => 4,
										"name" => "HR Strip (Patra)",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "463",
										"level" => 4,
										"name" => "Pipes",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "449",
										"level" => 4,
										"name" => "CRC",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "454",
										"level" => 4,
										"name" => "GP",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "460",
										"level" => 4,
										"name" => "PPGI",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "878",
										"level" => 4,
										"name" => "Galvalume",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "940",
										"level" => 4,
										"name" => "India Steel Composite Index",
										"url" => "",
										"root" => "Prices",
										"parent" => "Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Ferro Alloy",
								"url" => "",
								"subItems" => [
									[
										"id" => "426",
										"level" => 4,
										"name" => "Manganese Ore",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "419",
										"level" => 4,
										"name" => "Chrome Ore",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "427",
										"level" => 4,
										"name" => "Silico Manganese",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "422",
										"level" => 4,
										"name" => "Ferro Manganese",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "421",
										"level" => 4,
										"name" => "Ferro Chrome",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "424",
										"level" => 4,
										"name" => "Ferro Silicon",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "1301",
										"level" => 4,
										"name" => "Noble Ferro Alloys",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ferro Alloy",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Stainless Steel",
								"url" => "",
								"subItems" => [
									[
										"id" => "981",
										"level" => 4,
										"name" => "Stainless Steel",
										"url" => "",
										"root" => "Prices",
										"parent" => "Stainless Steel",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Ship Breaking",
								"url" => "",
								"subItems" => [
									[
										"id" => "445",
										"level" => 4,
										"name" => "Ship Breaking",
										"url" => "",
										"root" => "Prices",
										"parent" => "Ship Breaking",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Graphite Electrode",
								"url" => "",
								"subItems" => [
									[
										"id" => "431",
										"level" => 4,
										"name" => "Graphite Electrode",
										"url" => "",
										"root" => "Prices",
										"parent" => "Graphite Electrode",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
						]
					],
					[
						"level" => 2,
						"name" => "Non Ferrous",
						"url" => "",
						"subItems" => [
							[
								"level" => 3,
								"name" => "Non Ferrous",
								"url" => "",
								"subItems" => [
									[
										"id" => "973",
										"level" => 4,
										"name" => "Aluminium",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "996",
										"level" => 4,
										"name" => "Copper",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "997",
										"level" => 4,
										"name" => "Zinc",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "998",
										"level" => 4,
										"name" => "Lead",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "1000",
										"level" => 4,
										"name" => "Nickel",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									],
									[
										"id" => "1001",
										"level" => 4,
										"name" => "Tin",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "non-ferrous",
										"filterType" => "commodity"
									]
								]
							]
						]
					],
					[
						"level" => 2,
						"name" => "Coal & Energy",
						"url" => "",
						"subItems" => [
							[
								"level" => 3,
								"name" => "Coal",
								"url" => "",
								"subItems" => [
									[
										"id" => "417",
										"level" => 4,
										"name" => "Non Coking",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "coal",
										"filterType" => "commodity"
									],
									[
										"id" => "415",
										"level" => 4,
										"name" => "Coking",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "coal",
										"filterType" => "commodity"
									],
									[
										"id" => "416",
										"level" => 4,
										"name" => "Met Coke",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "coal",
										"filterType" => "commodity"
									],
									[
										"id" => "737",
										"level" => 4,
										"name" => "Pet Coke",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "coal",
										"filterType" => "commodity"
									],
									[
										"id" => "1251",
										"level" => 4,
										"name" => "India Coal Index",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "coal",
										"filterType" => "commodity"
									],
									[
										"id" => "1814",
										"level" => 4,
										"name" => "Coal Vessel Freight",
										"url" => "",
										"root" => "Prices",
										"parent" => "Coal",
										"market_id" => "ferrous",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Graphite Electrode",
								"url" => "",
								"subItems" => [
									[
										"id" => "431",
										"level" => 4,
										"name" => "Graphite Electrode",
										"url" => "",
										"root" => "Prices",
										"parent" => "Graphite Electrode",
										"market_id" => "coal",
										"filterType" => "commodity"
									]
								]
							]
						]
					],
					[
						"level" => 2,
						"name" => "Scrap Recycling",
						"url" => "",
						"subItems" => [
							[
								"level" => 3,
								"name" => "Scrap & Metallics",
								"url" => "",
								"subItems" => [
									[
										"id" => "439",
										"level" => 4,
										"name" => "Melting Scrap",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									],
									[
										"id" => "442",
										"level" => 4,
										"name" => "Rerolling Scrap",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									],
									[
										"id" => "440",
										"level" => 4,
										"name" => "Mill Scale",
										"url" => "",
										"root" => "Prices",
										"parent" => "Scrap & Metallics",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Non Ferrous",
								"url" => "",
								"subItems" => [
									[
										"id" => "439",
										"level" => 4,
										"name" => "Aluminium",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									],
									[
										"id" => "996",
										"level" => 4,
										"name" => "Copper",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									],
									[
										"id" => "997",
										"level" => 4,
										"name" => "Zinc",
										"url" => "",
										"root" => "Prices",
										"parent" => "Non Ferrous",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									]
								]
							],
							[
								"level" => 3,
								"name" => "Stainless Steel",
								"url" => "",
								"subItems" => [
									[
										"id" => "981",
										"level" => 4,
										"name" => "Stainless Steel",
										"url" => "",
										"root" => "Prices",
										"parent" => "Stainless Steel",
										"market_id" => "scrap-recycling",
										"filterType" => "commodity"
									]
								]
							]
						]
					],
					[
						"level" => 2,
						"name" => "Agriculture",
						"url" => "",
						"subItems" => [
							[
								"level" => 3,
								"name" => "Grains",
								"url" => "",
								"subItems" => [
									[
										"id" => "2093",
										"level" => 4,
										"name" => "Rice",
										"url" => "",
										"root" => "Prices",
										"parent" => "Grains",
										"market_id" => "agriculture",
										"filterType" => "commodity"
									],
								]
							]
						]
					]
				]
			],
			[
				"id" => "5",
				"level" => 1,
				"name" => "Insights",
				"url" => ""
			],
			[
				"id" => "6",
				"level" => 1,
				"name" => "Tenders",
				"url" => ""
			],
			[
				"id" => "7",
				"level" => 1,
				"name" => "Events",
				"url" => ""
			],
			[
				"id" => "12",
				"level" => 1,
				"name" => "Statistics",
				"url" => ""
			],
			[
				"id" => "8",
				"level" => 1,
				"name" => "Reports",
				"url" => ""
			],
			[
				"id" => "9",
				"level" => 1,
				"name" => "Profile settings",
				"url" => ""
			],
			[
				"id" => "10",
				"level" => 1,
				"name" => "Subscription",
				"url" => ""
			],
			[
				"id" => "11",
				"level" => 1,
				"name" => "Help",
				"url" => ""
			]
		];

		// Output the JSON data
		return json_encode($data);
	}

	public function rmCreds(Request $request)
	{
		//DB::enableQueryLog();
		$id = DB::table('rm_save_settings')->insertGetId(["rm_name" => $request->rmname, "rm_user" => $request->ruid, "date_added" => date("Y-m-d")]);
		//dd(DB::getQueryLog());
		return json_encode(["actv_id" => $id]);
	}

	public function quickdata(Request $request)
	{
		try {
			$user_id = 0;
			$_ct_suffix = '';
			$_services = "'MA', 'MA_PO', 'W'";
			if ('CM' == $this->appType) {
				$_ct_suffix = '_cm';
				$_services = "'C'";
			}
			if ($request->has("accessToken")) {
				$accessToken = $request->input('accessToken');
				$auth = new authentication();
				$user_id = $auth->authToken($accessToken, $this->appType);
				if ($user_id) {

					//api call to generate the qr code 
					$url = "https://www.steelmint.com/api/public/v2019/events/QR/gen?memId=$user_id&eventID=";
					$res = $this->getCURL($url);

					$common = new Common();

					$user = new User($user_id, $this->appType);
					$isAccessible = $user->isAccessible($resourceType); //
					if ($isAccessible == -1) {
						$activePackageName =  session('userService');

						if ($activePackageName == "Price Only") {
							if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("ios_do_not_change_price_only_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_do_not_change_price_only_post" . $_ct_suffix . ".json");
							} else {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("android_do_not_change_price_only_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_do_not_change_price_only_post" . $_ct_suffix . ".json");
							}
							$p_array = json_decode($result, true);
							///$c = $this->getBookmarked($user_id,$p_array);
							$c = $common->getBookmarked($user_id, $p_array);
							$result = json_encode($c);
							return $result;
						} else {
							if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("ios_do_not_change_professional_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_do_not_change_professional_post" . $_ct_suffix . ".json");
							} else {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("android_do_not_change_professional_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_do_not_change_professional_post" . $_ct_suffix . ".json");
							}
							$p_array = json_decode($result, true);
							///$c = $this->getBookmarked($user_id,$p_array);
							$c = $common->getBookmarked($user_id, $p_array);
							$result = json_encode($c);
							return $result;
						}
					} else {

						if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
							if ($user_id == 116707) {
								include_once "/home/steelmin/public_html/redisFn.php";
								$result = getKeyValueFromRedis("ios_pre" . $_ct_suffix . ".json");
							} else
								$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_pre" . $_ct_suffix . ".json");
						} else {
							if ($user_id == 116707) {
								include_once "/home/steelmin/public_html/redisFn.php";
								$result = getKeyValueFromRedis("android_pre" . $_ct_suffix . ".json");
							} else
								$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_pre" . $_ct_suffix . ".json");
						}
						return $result;
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Access token or memId is invalid or has expired")));
				}
			} else {

				if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
					if ($user_id == 116707) {
						include_once "/home/steelmin/public_html/redisFn.php";
						$result = getKeyValueFromRedis("ios_pre" . $_ct_suffix . ".json");
					} else
						$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_pre" . $_ct_suffix . ".json");
				} else {
					if ($user_id == 116707) {
						include_once "/home/steelmin/public_html/redisFn.php";
						$result = getKeyValueFromRedis("android_pre" . $_ct_suffix . ".json");
					} else
						$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_pre" . $_ct_suffix . ".json");
				}

				return $result;
			}
		} catch (\Exception $e) {
			return $e->getMessage();
		}
	}

	public function quickdata01102021(Request $request)
	{
		try {
			$user_id = 0;
			$_ct_suffix = '';
			$_services = "'MA', 'MA_PO', 'W'";
			if ('CM' == $this->appType) {
				$_ct_suffix = '_cm';
				$_services = "'C'";
			}
			if ($request->has("accessToken")) {
				$accessToken = $request->input('accessToken');
				$auth = new authentication();
				$user_id = $auth->authToken($accessToken, $this->appType);
				if ($user_id) {
					$common = new Common();

					$active_count = DB::table("tbl_updated_reg_logs")->select("active_products")->where('status', "Active")->whereIn("services", [$_services])->where("memid", $user_id)->count();

					if ($active_count > 0) {
						$res = DB::table("tbl_updated_reg_logs")->select("active_products")->where('status', "Active")->whereIn("services", [$_services])->where("memid", $user_id)->get();

						$res = DB::table("tbl_packages")->select("packageName")->where("id", $res[0]["active_products"])->get();
						if ($res[0]["packageName"] == "Price Only") {
							if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("ios_do_not_change_price_only_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_do_not_change_price_only_post" . $_ct_suffix . ".json");
							} else {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("android_do_not_change_price_only_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_do_not_change_price_only_post" . $_ct_suffix . ".json");
							}
							$p_array = json_decode($result, true);
							///$c = $this->getBookmarked($user_id,$p_array);
							$c = $common->getBookmarked($user_id, $p_array);
							$result = json_encode($c);
							return $result;
						} else {
							if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("ios_do_not_change_professional_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_do_not_change_professional_post" . $_ct_suffix . ".json");
							} else {
								if ($user_id == 116707) {
									include_once "/home/steelmin/public_html/redisFn.php";
									$result = getKeyValueFromRedis("android_do_not_change_professional_post" . $_ct_suffix . ".json");
								} else
									$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_do_not_change_professional_post" . $_ct_suffix . ".json");
							}
							$p_array = json_decode($result, true);
							///$c = $this->getBookmarked($user_id,$p_array);
							$c = $common->getBookmarked($user_id, $p_array);
							$result = json_encode($c);
							return $result;
						}
					} else {

						if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
							if ($user_id == 116707) {
								include_once "/home/steelmin/public_html/redisFn.php";
								$result = getKeyValueFromRedis("ios_pre" . $_ct_suffix . ".json");
							} else
								$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_pre" . $_ct_suffix . ".json");
						} else {
							if ($user_id == 116707) {
								include_once "/home/steelmin/public_html/redisFn.php";
								$result = getKeyValueFromRedis("android_pre" . $_ct_suffix . ".json");
							} else
								$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_pre" . $_ct_suffix . ".json");
						}
						return $result;
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Access token or memId is invalid or has expired")));
				}
			} else {

				if ($request->has("deviceType") && $request->get("deviceType") == "ios") {
					if ($user_id == 116707) {
						include_once "/home/steelmin/public_html/redisFn.php";
						$result = getKeyValueFromRedis("ios_pre" . $_ct_suffix . ".json");
					} else
						$result = file_get_contents("/home/steelmin/public_html/v2019/Json/ios_pre" . $_ct_suffix . ".json");
				} else {
					if ($user_id == 116707) {
						include_once "/home/steelmin/public_html/redisFn.php";
						$result = getKeyValueFromRedis("android_pre" . $_ct_suffix . ".json");
					} else
						$result = file_get_contents("/home/steelmin/public_html/v2019/Json/android_pre" . $_ct_suffix . ".json");
				}

				return $result;
			}
		} catch (\Exception $e) {
			return $e->getMessage();
		}
	}

	///function getBookmarked moved to Action\Common.php

	public function getDetailsFromURL(Request $request)
	{
		if ($request->has('accessToken')) {
			$accessToken = $request->input('accessToken');
		} else
			$accessToken = '';

		if ($request->has('f_url')) {
			$f_url = $request->input('f_url');
			if (strpos($f_url, "/insights/") !== false) {
				$ex = explode("-", $f_url);
				$itemID = $ex[count($ex) - 1];
				$url = "https://www.steelmint.com/api/public/v2019/insights/details?deviceType=android&itemID=$itemID&resourceType=app";
				if ($accessToken != '')
					$url .= "&accessToken=$accessToken";
				$res = $this->getCURL($url);
				$res = json_decode($res, true);

				$result = $res['data'][0];
				$section = 'insights';
			} elseif (strpos($f_url, "/price/") !== false) {
				$ex = explode("-", $f_url);
				$itemID = $ex[count($ex) - 1];
				$url = "https://www.steelmint.com/api/public/v2019/prices/details";
				$params = array(
					"currencyName" => $ex[count($ex) - 1],
					"itemID" => $ex[count($ex) - 3],
					"priceType" => $ex[count($ex) - 2]
				);
				if ($accessToken != '')
					$params['accessToken'] = $accessToken;
				$res = $this->postCURL($url, $params);
				$res = json_decode($res, true);
				$result = $res['data'][0];
				$section = 'prices';
			} elseif (strpos($f_url, "/intel/") !== false) {
				$ex = explode("-", $f_url);

				$url = "https://www.steelmint.com/api/public/v2019/intel";
				$params = array(
					"filters" =>  array("post_id" => $ex[count($ex) - 1]),
					"resourceType" => "app",
					"deviceType" => "android"
				);
				if ($accessToken != '')
					$params['accessToken'] = $accessToken;

				/* echo "<pre>";
				print_r($params); */

				$res = $this->postCURL($url, $params);
				$res = json_decode($res, true);

				$result = $res['data'][0];
				$section = 'intel';
			}
			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "section" => $section, "data" => $result));
		} else {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "URL not passed")));
		}
	}

	public  function getCURL($url, $params = '')
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		if ($params != '') {
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
			curl_setopt(
				$ch,
				CURLOPT_HTTPHEADER,
				array(
					'Content-Type: application/json',
					'Content-Length: ' . strlen($params)
				)
			);
		}
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}

	public  function postCURL($url, $params)
	{
		$fields_string = http_build_query($params);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

		$output = curl_exec($ch);
		$information = curl_getinfo($ch);

		return $output;
	}

	public function storePushNotifiDtls(Request $request)
	{
		if ($request->has('accessToken')) {
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} else
			$user_id = 0;
		if ($request->has('fcmToken'))
			$fcmToken = strtolower($request->input('fcmToken'));

		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($request->has('deviceInfo'))
			$deviceInfo = strtolower($request->input('deviceInfo'));

		if ($request->has('payLoadData'))
			$payLoadData = strtolower($request->input('payLoadData'));


		DB::table('tbl_push_notifi_details')->insert([
			'memid' => $user_id,
			'fcmToken' => $fcmToken,
			'deviceType' => $deviceType,
			'resourceType' => $resourceType,
			'deviceInfo' => $deviceInfo,
			'f_datetime' => date("Y-m-d H:i:s"),
			'payLoadData' => htmlspecialchars($payLoadData, ENT_QUOTES)
		]);

		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success")));
	}

	public function getArray(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if ($request->has('app_type'))
			$app_type = strtolower($request->input('app_type'));
		else
			$app_type = "SM";
		$place = '';
		$itemType = '';
		$section = '';
		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($request->has('place'))
			$place = strtolower($request->input('place'));

		if ($request->has('itemType'))
			$itemType = strtolower($request->input('itemType'));

		if ($request->has('section'))
			$section = strtolower($request->input('section'));

		//START: form key for redis using above parameters
		$redisKeyName = '';
		if ($resourceType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $resourceType;
			else
				$redisKeyName .= "_" . $resourceType;
		}

		if ($deviceType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $deviceType;
			else
				$redisKeyName .= "_" . $deviceType;
		}

		if ($app_type !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $app_type;
			else
				$redisKeyName .= "_" . $app_type;
		}


		if ($place !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $place;
			else
				$redisKeyName .= "_" . $place;
		}

		if ($itemType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $itemType;
			else
				$redisKeyName .= "_" . $itemType;
		}

		if ($section !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $section;
			else
				$redisKeyName .= "_" . $section;
		}
		//END: form key for redis using above parameters

		//check if the above key exists in redis DB
		//if yes, then return the same
		//include_once "/home/steelmin/public_html/redisFn.php";
		/* if(isKeyExistsInRedis($redisKeyName)){
		    return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> json_decode(getKeyValueFromRedis($redisKeyName), true)));
		} */

		if ($resourceType == 'web' && $section == 'event') {
			$resultset = $this->refData($resourceType, $itemType, $section = 'event', $place = "WEB_EVENTS_LANDING_LISTING_CMBBOX", $otherCondition = '', '', $app_type);
			$result = $resultset['WEB_EVENTS_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && $section == 'tender') {
			$resultset = $this->refData($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_TENDER_LISTING_FILTER'];
		} elseif ($resourceType == 'web' && $section == 'insight') {
			$resultset = $this->refData($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_INSIGHT_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && $section == 'price') {
			$resultset = $this->refData($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_PRICE_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && ($place != '' || $itemType != ''))
			$result = $this->refDataFilter($resourceType, $itemType, $section, $place);
		else
			$result = $this->refData($resourceType, '', '', '', '', $deviceType, $app_type);

		//set $redisKeyName in redis with $result for one day
		//after every 24 hours it will expire
		//setInRedis($redisKeyName, json_encode($result), 86400);

		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function getPriceSectionWiseFilters(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if (!$request->has('price_section_type')) {
			return new JsonResponse(array("code" => 2001, "message" => "invalid section type"));
		}

		$price_section_type = strtolower($request->input('price_section_type'));
		$market = strtolower($request->input('market'));

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($this->appType == 'CM') //if coalmint, show all coal related records only
			$where_condition = " WHERE continue_or_discontinue <> 0 AND commodityID = 401 AND category<>'INDEX' and sub_category NOT IN('') and price_section_type like '%$price_section_type%'";
		elseif ($this->appType == 'NFS') //if non fessous, show all non ferrous related records only
			$where_condition = " WHERE showOnlyInSteelmint=1 and continue_or_discontinue=1 and category ='Non Ferrous' and sub_category NOT IN('') and price_section_type like '%$price_section_type%'";
		elseif ($market != '') {
			$where_condition = " WHERE continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('')  ";
			$where_condition .= " and FIND_IN_SET('$market', f_market) ";
			//added for market wise
			if ($price_section_type == 'spot_prices' || $price_section_type == 'indices_prices')
				$where_condition .= " and (price_section_type like '%spot_prices%' OR price_section_type like '%indices_prices%')";
			else
				$where_condition .= " and price_section_type like '%$price_section_type%'";
		} elseif ($resourceType == 'web')
			$where_condition = " WHERE category <> 'Non Ferrous' and showOnlyInSteelmint=1 and continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') and price_section_type like '%$price_section_type%' ";
		else
			$where_condition = " WHERE showOnlyInSteelmint=1 and continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') and price_section_type like '%$price_section_type%' ";
		///add this condition when anamika work will start for non Ferrous and category <> 'Non Ferrous'  when NFS is+


		$sqlQry = "(
		SELECT id 
		FROM `tbl_dom_master` 
		$where_condition
		 )	
		";
		$sqlQry .= " union all (";
		$sqlQry .= "
		SELECT id
		FROM `tbl_exim_master` 
		$where_condition 
		";

		$sqlQry .= ") union all (";
		$sqlQry .= "
		SELECT id
		FROM `tbl_global_dom_master` 
		$where_condition
		)";
		//echo $sqlQry . "<hr>";
		include_once('/home/steelmin/public_html/hf.php');
		$relIDs = qryToCommaSepString($sqlQry);

		$result = array();
		if ($relIDs == '')
			$relIDs = 0;
		if ($this->appType == 'CM')
			$where_condition = " WHERE r.relation_id in ($relIDs) and continue_or_discontinue<>0 AND category<>'INDEX' and product NOT IN('') and commodityID > 0 and regionID > 0  ";
		elseif ($this->appType == 'NFS') //if non fessous, show all non ferrous related records only
			$where_condition = " WHERE r.relation_id in ($relIDs) and continue_or_discontinue=1 AND category<>'INDEX' and product NOT IN('') and showOnlyInSteelmint=1 and commodityID > 0 and regionID > 0 ";
		elseif ($market != '')
			$where_condition = " WHERE r.relation_id in ($relIDs) and continue_or_discontinue=1 AND category<>'INDEX' and product NOT IN('') and commodityID > 0 and regionID > 0  ";
		else
			$where_condition = " WHERE r.relation_id in ($relIDs) and continue_or_discontinue=1 AND category<>'INDEX' and product NOT IN('') and showOnlyInSteelmint=1 and commodityID > 0 and regionID > 0  ";

		$sqlQry = "";
		/*$sqlQry .= "
		SELECT r.commodityID ,
			   case 
				when r.commodityID=413 then r.subSubCommodityID
				else r.subCommodityID
			   end as subCommodityID,
			   regionID,
			   r.countryID as subRegionID,
			   r.f_cnf_fob,
			    r1.itemName as commodityName,
			   case 
				when r.commodityID=413 then r21.itemName
				else r2.itemName
			   end as subCommodityName,
			   r3.itemName as regionName,
			   r4.itemName as subRegionName
		FROM `tbl_price_static` as r
		left join `tbl_region_commodity_master` as r1 ON r1.ID=r.commodityID
		left join `tbl_region_commodity_master` as r2 ON r2.ID=r.subCommodityID
		left join `tbl_region_commodity_master` as r21 ON r21.ID=r.subSubCommodityID
		left join `tbl_region_commodity_master` as r3 ON r3.ID=r.regionID
		left join `tbl_region_commodity_master` as r4 ON r4.ID=r.countryID
		$where_condition
		
		";*/

		//added condition to show subCommodity in first level for non ferrous (15feb2022)
		if ($this->appType == 'NFS') {
			$sqlQry .= "
		SELECT case 
				when r.commodityID=972 then r.subCommodityID
				else r.commodityID
			   end as commodityID,				
			   case 
				when r.commodityID=413 then r.subSubCommodityID
				else r.subCommodityID
			   end as subCommodityID,
			   regionID,
			   r.countryID as subRegionID,
			   r.f_cnf_fob,
			   case 
				when r.commodityID=972 then  r2.itemName
				else r1.itemName
			   end as commodityName,
			   case 
				when r.commodityID=413 then r21.itemName
				else r2.itemName
			   end as subCommodityName,
			   r3.itemName as regionName,
			   r4.itemName as subRegionName
		FROM `tbl_price_static` as r
		left join `tbl_region_commodity_master` as r1 ON r1.ID=r.commodityID
		left join `tbl_region_commodity_master` as r2 ON r2.ID=r.subCommodityID
		left join `tbl_region_commodity_master` as r21 ON r21.ID=r.subSubCommodityID
		left join `tbl_region_commodity_master` as r3 ON r3.ID=r.regionID
		left join `tbl_region_commodity_master` as r4 ON r4.ID=r.countryID
		$where_condition
		";
		} else {
			$sqlQry .= "
			SELECT r.commodityID ,
				case 
					when r.commodityID=413 then r.subSubCommodityID
					else r.subCommodityID
				end as subCommodityID,
				regionID,
				r.countryID as subRegionID,
				r.f_cnf_fob,
					r1.itemName as commodityName,
				case 
					when r.commodityID=413 then r21.itemName
					else r2.itemName
				end as subCommodityName,
				r3.itemName as regionName,
				r4.itemName as subRegionName
			FROM `tbl_price_static` as r
			left join `tbl_region_commodity_master` as r1 ON r1.ID=r.commodityID
			left join `tbl_region_commodity_master` as r2 ON r2.ID=r.subCommodityID
			left join `tbl_region_commodity_master` as r21 ON r21.ID=r.subSubCommodityID
			left join `tbl_region_commodity_master` as r3 ON r3.ID=r.regionID
			left join `tbl_region_commodity_master` as r4 ON r4.ID=r.countryID
			$where_condition";
		}
		$sqlQryC = $sqlQry . " group by subCommodityID, subSubCommodityID, countryID 
					order by r1.parentID, r1.f_order_by, r2.parentID, r2.f_order_by, r21.f_order_by, r.f_order_by, r3.f_order_by, r4.f_order_by, subCommodityName"; //
		//echo $sqlQryC . "<hr>";
		$resultData = DB::select($sqlQryC);
		$commodityID = 0;
		$m = 0;
		foreach ($resultData as $data):
			if ($commodityID != $data['commodityID']) {
				$m++;
				$commodityID = $data['commodityID'];
				$result['commodity'][$m - 1] = array(
					"id" => $data['commodityID'],
					"name" => $data['commodityName'],
					"isSelectable" => 'n'
				);

				$c = 0;
				$subCommodityID = '';
			}
			///echo '<prE>', $m, '-',$c, '-',$commodityID, '-',$data['subCommodityID'], '-','</pre>'; 
			if ($subCommodityID != $data['subCommodityID']) {
				$c++;
				$subCommodityID = $data['subCommodityID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1] = array(
					"id" => $data['subCommodityID'],
					"name" => $data['subCommodityName'],
					"isSelectable" => 'y'
				);

				$regionID = 0;
				$r = 0;
			}

			if ($regionID != $data['regionID']) {
				$r++;
				$regionID = $data['regionID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1] = array(
					"id" => $data['regionID'],
					"name" => $data['regionName'],
					"isSelectable" => 'y'
				);

				$subRegionID = 0;
				$sr = 0;
			}


			if ($subRegionID != $data['regionID']) {
				$sr++;
				$subRegionID = $data['subRegionID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
					"id" => $data['subRegionID'],
					"name" => $data['subRegionName'],
					"isSelectable" => 'y'
				);
			}
		endforeach;

		///


		$sqlQryR = $sqlQry . " group by regionID, countryID, subCommodityID, subSubCommodityID 
				  order by r3.parentID, r3.f_order_by, r4.parentID, r4.f_order_by, r1.f_order_by, regionID, countryID, r2.f_order_by ";
		///if($request->input('memid')==56350)
		///	echo '<pre>'.$sqlQryR;
		$resultData = DB::select($sqlQryR);
		$regionID = 0;
		$m = 0;
		foreach ($resultData as $data):
			if ($regionID != $data['regionID']) {
				$m++;
				$regionID = $data['regionID'];
				$result['region'][$m - 1] = array(
					"id" => $data['regionID'],
					"name" => $data['regionName'],
					"isSelectable" => 'n'
				);

				$c = 0;
				$subRegionID = '';
			}
			///echo '<prE>', $m, '-',$c, '-',$commodityID, '-',$data['subCommodityID'], '-','</pre>'; 
			if ($subRegionID != $data['subRegionID']) {
				$c++;
				$subRegionID = $data['subRegionID'];
				$result['region'][$m - 1]['sub_region'][$c - 1] = array(
					"id" => $data['subRegionID'],
					"name" => $data['subRegionName'],
					"isSelectable" => 'y'
				);

				$commodityID = 0;
				$r = 0;
			}

			if ($commodityID != $data['commodityID']) {
				$r++;
				$commodityID = $data['commodityID'];
				$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1] = array(
					"id" => $data['commodityID'],
					"name" => $data['commodityName'],
					"isSelectable" => 'y'
				);

				$subCommodityID = 0;
				$sr = 0;
			}


			if ($subCommodityID != $data['subCommodityID']) {
				$sr++;
				$subCommodityID = $data['subCommodityID'];
				$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
					"id" => $data['subCommodityID'],
					"name" => $data['subCommodityName'],
					"isSelectable" => 'y'
				);
			}
		endforeach;
		/*$res1=[];
		foreach($result['region'] as $kname=>$arr_name){
			foreach($sub_region as $ksection=>$filters){
				foreach($arr_section as $itemType=>$arr_itemType){
					foreach($sub_filters as $itemType=>$arr){
						$res1 = array_values($arr);
					}
				}
			}
		}*/
		$result['dataType'] = array(
			array("name" => "Imp", "value" => "cnf"),
			array("name" => "Exp", "value" => "fob"),
			array("name" => "Dom", "value" => "f")
		);
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function getPackageDetails(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		//if(!$request->has('packageID')){
		if (!$request->has('itemID')) {
			return new JsonResponse(array("code" => 2001, "message" => "invalid package"));
		}

		//$packageID = $request->input('packageID');
		$packageID = $request->input('itemID');
		if ($request->has('memid')) {
			$memid = $request->input('memid');
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		} elseif ($request->has('accessToken')) {
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		}

		$common = new Common();
		$result = $common->getPackagesDetail($packageID, $memid);

		//return A::calc($v);
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function index()
	{
		$result = array();
		$result = $this->referenceDataArr;
		//$a = $this->getReferenceData();
		$dbresult = DB::table('tbl_companytype')
			->select('id', 'short_comptype as name')
			->get();
		foreach ($dbresult as $cType) {
			$result['companyType'][$cType["id"]] = $cType["name"];
		}
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function alerts(Request $request)
	{
		$result = array();

		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			$source = $request->input('source'); //Tender/Prices

			$itemId = $request->input('itemId');
			$mediumList = $request->input('mediumList'); //["email"  , "sms" ]
			$xDaysBefore = $request->input('xDaysBefore');
			$action = $request->input('action');
			$accessToken = $request->input('accessToken');
		}
		$code = 1001;
		$message = "Alert Set Successfully";
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}

	public function removeBookmark(Request $request)
	{
		$result = array();
		$accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			$source = $request->input('source'); //price/insights/tender

			$itemId = $request->input('itemId');
			$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch ($section) {
				case "bookmark":
					switch ($source) {
						case "price":
							break;
						case "insights":
							break;
						case "tender":
							break;
					}
					break;
				case "compare":
					switch ($source) {
						case "price":
							break;
						case "insights":
							break;
						case "tender":
							break;
					}
					break;
				case "portfolio":
					switch ($source) {
						case "price":
							break;
						case "insights":
							break;
						case "tender":
							break;
					}
					break;
				case "alerts":
					switch ($source) {
						case "price":
							break;
						case "insights":
							break;
						case "tender":
							break;
					}
					break;
			}

			$code = 1001;
			$message = "Successfully Saved";
		} else {
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}
	//Add bookmark -
	public function getEventsWebRowSet(Request $request)
	{
		$result = array();
		$accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			$source = $request->input('source'); //price/insights/tender

			$itemIds = $request->input('itemIds');
			///$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch ($source) {
				case "price":
					break;
				case "insights":
					break;
				case "tender":
					break;
			}

			$code = 1001;
			$message = "Successfully Bookmarked";
		} else {
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}
	//Show more/less Like this - insight
	public function showSimilar(Request $request)
	{
		$result = array();
		$accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			$source = $request->input('source'); //price/insights/tender

			$itemIds = $request->input('itemIds');
			$type = $request->input('type'); //more/less
			switch ($source) {
				case "insights":
					break;
				case "tender":
					break;
			}

			$code = 1001;
			$message = "Successfully Saved";
		} else {
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}


	public function portfolioAddItem(Request $request)
	{
		$result = array();
		//$accessToken = $request->input('accessToken');
		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if ($resourceType == 'web' && $request->has('memid') && !empty($request->input('memid'))) {
			$memid = $request->input('memid');
			if ($request->has("rid") && $request->input("rid") != null) {
				DB::table("rm_saved_sections")->insert(['section' => "portfolio", 'rm_setting_id' => $request->input("rid"), 'updated_at' => $GLOBALS['currDate'] . " " . $GLOBALS['currTime']]);
			} else {
				$id = DB::table('rm_save_settings')->insertGetId(["rm_name" => "front-user", "rm_user" => $memid, "date_added" => $GLOBALS['currDate']]);
				DB::table("rm_saved_sections")->insert(['section' => "portfolio", 'rm_setting_id' => $id, 'updated_at' => $GLOBALS['currDate'] . " " . $GLOBALS['currTime']]);
			}
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		} elseif ($resourceType == 'app' && $request->has('accessToken') && !empty($request->input('accessToken'))) {
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		}

		if (!$user_id) {
			$code = 2001;
			$message = "Invalid  User";
		} else {

			$section = $request->input('section'); //price/insights/tender

			///$itemID = $request->input('itemID');
			///$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch ($section) {
				case "price":
				case "prices":
					$rows_input = $request->input('itemID');
					//print_r($rows_input);
					// if($request->has('accessToken'))
					// $rows = json_decode(stripcslashes($rows_input), true);
					// else
					$rows = $rows_input;

					foreach ($rows as $_row) {
						$row_id = $_row['rowID'];
						$prices_col = $_row['pricesCol'];
						$flag = $_row['flag'];
						if ($flag == 0) {
							DB::table('tbl_user_portfolio')
								->where('type', '=', 'prices')
								->where('user_id', '=', $user_id)
								->where('prices_col', '=', $prices_col)
								->where('appType', '=', $this->appType)
								->where('row_id', '=', $row_id)
								->delete();
							$message = "Successfully removed from Portfolio";
						} else {
							DB::table('tbl_user_portfolio')
								->where('type', '=', 'prices')
								->where('user_id', '=', $user_id)
								->where('prices_col', '=', $prices_col)
								->where('appType', '=', $this->appType)
								->where('row_id', '=', $row_id)
								->delete();

							$ipAddress = $_SERVER['REMOTE_ADDR'];
							if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
								$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
							}
							DB::table('tbl_user_portfolio')->insert([
								'ip' => $ipAddress,
								'user_id' => $user_id,
								'type' => 'prices',
								'prices_col' => $prices_col,
								'appType' => $this->appType,
								'row_id' => $row_id,
								'created_on' => $GLOBALS['currDateTime']
							]);

							$message = "Successfully added to Portfolio";
						}
					}
					break;
				case "insights":
				case "tender":
					/* $category = !empty($request->input('category'))?$request->input('category'):'';
					$country = !empty($request->input('country'))?$request->input('country'):'';
					$lead_type = !empty($request->input('lead_type'))?$request->input('lead_type'):'';
					
					DB::table('tbl_user_portfolio')
						->where('type', '=', $type)
						->where('user_id', '=', $user_id)
						->where('appType', '=', $appType )
						->delete();
					
					$ipAddress = $_SERVER['REMOTE_ADDR'];	
					DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
					'user_id' => $user_id,
					'type' => $type,
					'category' => $category,
					'country' => $country,
					'row_id' => 0,
					'lead_type' => $lead_type,
					'appType' => $appType,
					'created_on' => $GLOBALS['currDateTime']]); */
					break;
				case "forex":
				case "historical":
					$rows_input = $request->input('itemID');
					$rows = $rows_input;

					foreach ($rows as $_row) {
						$row_id = $_row['rowID'];
						$prices_col = $_row['pricesCol'];
						$flag = $_row['flag'];
						if ($flag == 0) {
							DB::table('tbl_user_portfolio')
								->where('type', '=', $section)
								->where('user_id', '=', $user_id)
								->where('prices_col', '=', $prices_col)
								->where('appType', '=', $this->appType)
								->where('row_id', '=', $row_id)
								->delete();
							$message = "Successfully removed from Portfolio";
						} else {
							DB::table('tbl_user_portfolio')
								->where('type', '=', $section)
								->where('user_id', '=', $user_id)
								->where('prices_col', '=', $prices_col)
								->where('appType', '=', $this->appType)
								->where('row_id', '=', $row_id)
								->delete();

							$ipAddress = $_SERVER['REMOTE_ADDR'];
							if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
								$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
							}
							DB::table('tbl_user_portfolio')->insert([
								'ip' => $ipAddress,
								'user_id' => $user_id,
								'type' => $section,
								'prices_col' => $prices_col,
								'appType' => $this->appType,
								'row_id' => $row_id,
								'created_on' => $GLOBALS['currDateTime']
							]);

							$message = "Successfully added to Portfolio";
						}
					}
					break;
				default:
					break;
			}

			$code = 1001;
			//	$message = "Successfully Saved";
			if ($resourceType == 'web' && $request->has('memid') && !empty($request->input('memid'))) {
				calculate_coc($request->input('memid'));
			}
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}

	public function addPreferences(Request $request)
	{
		//$resourceType = "web";
		$user_id = 0;



		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if (!$request->has('section')) {
			return new JsonResponse(array("code" => 2001, "message" => "invalid section!"));
		}
		$section = $request->input('section'); //"Tender/Insight/Intel/all",

		$commodityID = array();
		if ($request->has('commodityID')) {
			$commodityID = $request->input('commodityID');
		}

		$regionID = array();
		if ($request->has('regionID')) {
			$regionID = $request->input('regionID');
		}



		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);

			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		} elseif ($request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}
		if ($user_id) {
			///$itemIds = $request->input('itemIds');		
			//$channel = $request->input('channel'); //["whatsapp", "fb"]
			switch ($section) {
				case "price":
					break;
				case "insights":
					break;
				case "intel_insight":
				case "tender":

					DB::table('tbl_user_portfolio')
						->where('type', '=', $section)
						->where('user_id', '=', $user_id)
						->where('appType', '=', $this->appType)
						->delete();

					$ipAddress = $_SERVER['REMOTE_ADDR'];
					if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
						//$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
					}
					DB::table('tbl_user_portfolio')->insert([
						'ip' => $ipAddress,
						'user_id' => $user_id,
						'type' =>  $section,
						'commodityId' => implode(',', $commodityID),
						'regionId' => implode(',', $regionID),
						'row_id' => 0,
						///'lead_type' => $lead_type,
						'appType' => $this->appType,
						'created_on' => $GLOBALS['currDateTime']
					]);


					//new code to updated sendy list
					//file_get_contents("https://www.steelmint.com/registrationAJAX.php?resetAfterSetChannels=1&m=1&mid=$user_id");

					/*if( $resourceType == 'web' ){
						$listids = implode(',',$commodityID).','.implode(',',$regionID);
						$listids = trim($listids, ",");
						file_get_contents("https://www.steelmint.com/registrationAJAX.php?memid=$user_id&listids=$listids&subUnsubMembers=1");
					}*/
					/* if($request->has('show_manage_pref_screen') && $request->input('show_manage_pref_screen')=='yes'){
						
						DB::table($_ENV['USER_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->where('is_first_time_user', '=', 1 )
						->update( [ 'is_first_time_user' => 0 ]);
					} */
					break;
				case "both":
					///for intel_insight
					DB::table('tbl_user_portfolio')
						->where('type', '=', 'intel_insight')
						->where('user_id', '=', $user_id)
						->where('appType', '=', $this->appType)
						->delete();

					$ipAddress = $_SERVER['REMOTE_ADDR'];
					if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
						$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
					}
					DB::table('tbl_user_portfolio')->insert([
						'ip' => $ipAddress,
						'user_id' => $user_id,
						'type' =>  'intel_insight',
						'commodityId' => implode(',', $commodityID),
						'regionId' => implode(',', $regionID),
						'row_id' => 0,
						///'lead_type' => $lead_type,
						'appType' => $this->appType,
						'created_on' => $GLOBALS['currDateTime']
					]);
					//new code to updated sendy list
					file_get_contents("https://www.steelmint.com/registrationAJAX.php?resetAfterSetChannels=1&m=1&mid=$user_id");
					/*if( $resourceType == 'web' ){
						$listids = implode(',',$commodityID).','.implode(',',$regionID);
						file_get_contents("https://www.steelmint.com/registrationAJAX.php?memid=$user_id&listids=$listids&subUnsubMembers=1");
					}*/
					if ($request->has('show_manage_pref_screen') && $request->input('show_manage_pref_screen') == 'yes') {

						DB::table($_ENV['USER_TABLE'])
							->where($_ENV['USER_ID'], '=', $user_id)
							->where('is_first_time_user', '=', 1)
							->update(['is_first_time_user' => 0]);
					}

					///for tender
					DB::table('tbl_user_portfolio')
						->where('type', '=', 'tender')
						->where('user_id', '=', $user_id)
						->where('appType', '=', $this->appType)
						->delete();

					$ipAddress = $_SERVER['REMOTE_ADDR'];
					if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
						$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
					}
					DB::table('tbl_user_portfolio')->insert([
						'ip' => $ipAddress,
						'user_id' => $user_id,
						'type' =>  'tender',
						'commodityId' => implode(',', $commodityID),
						'regionId' => implode(',', $regionID),
						'row_id' => 0,
						///'lead_type' => $lead_type,
						'appType' => $this->appType,
						'created_on' => $GLOBALS['currDateTime']
					]);

					break;
			}
			if ($request->has('memid') && $request->input('memid') != '') {
				calculate_coc($request->input('memid'));
			}
			$code = 1001;
			$message = "Successfully Saved";
		} else {
			//return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
			$code = 2100;
			$message = "Unauthorized action";
		}
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function getPreferences(Request $request)
	{
		$resourceType = "app";
		$user_id = 0;

		$result = (object)array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if (!$request->has('section')) {
			return new JsonResponse(array("code" => 2001, "message" => "invalid section!"));
		}
		$section = $request->input('section'); //"Tender/Insight/Intel/all",

		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		} elseif ($request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}
		if ($user_id) {

			$dbresult = DB::table('tbl_user_portfolio')
				->select('commodityID', 'regionID', 'type')
				->where('type', '=',  $section)
				->where('user_id', '=', $user_id)
				->where('appType', '=', $this->appType)
				->orderBy('id', 'desc')
				->first();






			if ($dbresult && count($dbresult) > 0) {
				//$result[$dbresult['type']] = array(
				$commodityId = explode(',', $dbresult['commodityID']);
				$regionId = explode(',', $dbresult['regionID']);
				$commodityIDArr = array();
				$regionIDArr = array();
				foreach ($commodityId as $id) {
					$commodityIDArr[] = (int)$id;
				}
				foreach ($regionId as $id) {
					$regionIDArr[] = (int)$id;
				}

				$result = array(
					"commodityID" => $commodityIDArr,
					"regionID" => $regionIDArr,
				);
			}

			$code = 1001;
			$message = "Success";

			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
		} else {
			return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}
	}

	public function download(Request $request)
	{
		$resourceType = "app";
		$user_id = 0;

		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section = '';
		if ($request->has('section'))
			$section = strtolower($request->input('section'));

		if ($request->has('company'))
			$company = strtolower($request->input('company'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}

		switch ($section) {
			case "price":
				break;
			case "report": //for special report
				if ($request->has('itemID') && $request->input('itemID') != '') {
					$itemID = $request->input('itemID');
					$fDate = $request->has('fDate') ? $request->input('fDate') : $GLOBALS['currDate'];

					$user = new User($user_id, $this->appType);
					$isAccessible = $user->isAccessible($resourceType, $section = 'Report_s', $itemID);
					if ($isAccessible == -1) {
						$dbresult2 = DB::table('tbl_steelreport')
							->select('file')
							->where('id', $itemID)
							->first();
						$filePath = BASEURL . "reports/" . $dbresult2['file'];
						$result['path'] = $filePath;

						$code = 1001;
						$message = "Success";
					} else {
						return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
					}
				}
				break;
			case "tender":
				if ($request->has('itemID') && $request->input('itemID') != '') {
					$itemID = $request->input('itemID');

					$user = new User($user_id, $this->appType);
					$isAccessible = $user->isAccessible($resourceType, $section = 'tenders');
					if ($isAccessible == -1) {
						//$result['path'] = "https://www.steelmint.com/reports/Iron_Ore_Insight_28_02_2019.pdf";
						$dbresult2 = DB::table('tbl_tenders')
							->select('file')
							->where('id', $itemID)
							->first();
						$filePath = BASEURL . "images/tenders/" . $row['pdf_path'];
						$result['path'] = $filePath;

						$code = 1001;
						$message = "Success";
					} else {
						return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
					}
				}
				break;
			case "invoice":
				if ($request->has('invNo') && $request->input('invNo') != '') {
					$inv_no = $request->input('invNo');

					if ($user_id) {
						if ($company == 'events' || $company == 'event') {
							$result['path'] = "https://www.steelmint.com/invoices/multiform/preview.php?inv_no=" . $inv_no;
						} else {
							$result['path'] = "https://www.steelmint.com/invoices/preview.php?inv_no=" . $inv_no;
						}
					}

					$code = 1001;
					$message = "Success";
				} else {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "Invalid invoice")));
				}
				break;
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function alertsListing(Request $request)
	{
		$result = array();
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			$source = $request->input('source'); //price/insights/tender

			switch ($source) {
				case "tenders":
				case "tender":
					$result['tender'] = array(
						array(
							'itemId' => 10,
							'title' => "Iron Ore Tenders",
							//'medium'=>array('sms','push','wa')
						),
						array(
							'itemId' => 1,
							'title' => "Billet Tenders",
							//'medium'=>array('sms','push','email')
						)
					);
					break;
				case "prices":
					$result['prices'] = array(
						array(
							'itemId' => 1003,
							'title' => "Iron Ore prices",
							//'medium'=>array('sms','push','wa')
						),
						array(
							'itemId' => 22,
							'title' => "Billet prices",
							//'medium'=>array('sms','push','email')
						)
					);
					break;
			}

			$code = 1001;
			$message = "Success";
		} else {
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getFAQ()
	{
		$result = array();

		if ('CM' == $this->appType)
			include_once "/home/steelmin/public_html/api_bm/storage/v2019/CMfaqs.php";
		else
			include_once "/home/steelmin/public_html/api_bm/storage/v2019/faqs.php";

		$code = 1001;
		$message = "Successfully Saved";

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function webNotificationDetails(Request $request)
	{
		$user_id = 0;
		$result = array();

		if ($request->has('memid') && $request->input('memid') != '') { //visitor
			$user_id = $request->input('memid');
		}
		//echo "uid:" . $user_id;
		if ($user_id) {
			if ($request->has('pageValue')) {
				$pageValue = $request->input('pageValue');
			} else
				$pageValue = 1;

			$offset = ($pageValue - 1) * 15;
			//DB::enableQueryLog();
			$dbresult = DB::table('tbl_notification_list')
				->select('*')
				->orderBy('id', 'desc')
				->whereRaw("FIND_IN_SET('$user_id',sent_to_memids)")
				->skip($offset)
				->take(15)
				->get();
			//dd(DB::getQueryLog());

			if (count($dbresult) > 0) {
				foreach ($dbresult as $logs) {
					$item1 = array();
					$priceType = '';
					if ($logs['category'] == 'Price') {
						list($itemID, $priceType) = explode(',', $logs['f_url']);
						if ($this->appType == 'CM') {
							$dbresult2 = DB::table('tbl_price_static')
								->select('price', 'change')
								->where('relation_id', '=', $itemID)
								->where('f_cnf_fob', '=', $priceType)
								->where('commodityID', '=', 401)
								->first();
						} else {
							$dbresult2 = DB::table('tbl_price_static')
								->select('price', 'change')
								->where('relation_id', '=', $itemID)
								->where('f_cnf_fob', '=', $priceType)
								->first();
						}
						if (!empty($dbresult2)) {
							include_once('/home/steelmin/public_html/hf.php');
							$item1 = getPriceAndCurrency($dbresult2['price'], $dbresult2['change']);
						}
					} else {
						$itemID = $logs['f_url'];
					}
					$log_href = str_replace("https://www.steelmint.com/price/detail/", config('constants.siteUrl') . "prices/detail/", $logs['href']);
					$log_href = str_replace("https://www.coalmint.com/price/detail/", config('constants.siteUrl') . "prices/detail/", $log_href);
					$log_href = str_replace("https://www.steelmint.com/insights/", config('constants.siteUrl') . "insights/detail/", $log_href);
					$item = array(
						'notificationTitle' => htmlentities($logs['notification_title'], ENT_QUOTES),
						'notificationDescription' => htmlentities($logs['description'], ENT_QUOTES),
						'priceType' => $priceType,
						'category' => $logs['category'],
						'sent_at' => $logs['sent_at'],
						'href' => $log_href,
						'itemID' => intval($itemID),
						'icon' => url('/') . "/uploads/notification/" . strtolower($logs['category']) . "_1.png"
					);

					$result[] = array_merge($item, $item1);
				}
			}

			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
		}
	}


	public function notificationDetails(Request $request)
	{
		$result = array();
		$resourceType = "app";
		$user_id = 0;
		$gcm_id = 0;

		/*//added by mohan on <29-11-2021> for the purpose of update gcm divice concept*/
		$gcm_device_table = $this->appType == "CM" ? "gcm_device_cm" : "gcm_device";
		//appType = SM/CM
		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));


		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($request->has('deviceID') && $request->input('deviceID') != '') { //visitor

			$deviceID = $request->input('deviceID');
			$fcmToken = $request->input('fcmToken');
			//DB::enableQueryLog();
			$sel_admob = DB::table($gcm_device_table)
				->select('id')
				->where("device", "=", $request->input('deviceType'))
				->where("device_id", "=", $fcmToken)
				->where("physical_id", "=", $deviceID)
				->where("appType", "=", $this->appType)
				->orderBy('id', 'desc')
				->first();
			//dd(DB::getQueryLog());	
			if (count($sel_admob) > 0)
				$gcm_id = $sel_admob['id']; ///use this
		} elseif ($request->has('memid') && $request->input('memid') != '') { //visitor
			$user_id = $request->input('memid');
		}

		if ($user_id) {
			$sel_admob = DB::table($gcm_device_table)
				->select('id')
				//->where("device" , "=" , $request->input('deviceType'))
				->where("user_id", "=", $user_id)
				//->where("appType" , "=" , $this->appType )
				->orderBy('id', 'desc')
				->first();

			if (count($sel_admob) > 0)
				$gcm_id = $sel_admob['id']; ///use this
		}
		//echo "<br>gcm_id : ".$gcm_id;
		$notifications_ids = 0;
		if ($gcm_id) { ///name SEPARATOR '-'
			//DB::enableQueryLog(); 
			$notifications = DB::table('tbl_sent_notifications')
				->select(DB::raw("GROUP_CONCAT(f_notification_list_id) as `ids`"))
				->where("f_gcm_tbl_id", "=", $gcm_id)
				//->where("read_status" , "=" , 0 )
				->orderBy('id', 'desc')
				->first();
			//dd(DB::getQueryLog());	

			if (count($notifications) > 0)
				$notifications_ids = $notifications['ids']; ///use this
		} else {
			return new JsonResponse(array("status" => array("code" => 1011, "message" => "Unauthorized action, device not registered")));
			//return new JsonResponse(array("code" => 1011, "message" => "Unauthorized action, device not registered."));
		}
		///echo "<br>notifications_ids : ".$notifications_ids;
		$days_ago = date('Y-m-d', strtotime('-3 days', strtotime(date("Y-m-d"))));

		$notification_title_like = 'SteelMint';
		if ($this->appType == 'CM') {
			$notification_title_like = 'CoalMint';
		}

		$dbresult = DB::table('tbl_notification_list')
			->select('*')
			->orderBy('sent_at', 'desc')
			->whereIn('id', explode(',', $notifications_ids))
			->where('sent_at', '>=', $days_ago)
			->where('notification_title', 'like', '%' . $notification_title_like . '%')
			//->limit(30)
			->get();

		if (count($dbresult) > 0) {
			foreach ($dbresult as $logs) {
				$priceType = '';
				$price2 = '';
				$change2 = '';
				$currencyConvertor = 1;
				$item1 = array();
				if ($logs['category'] == 'Price') {

					list($itemID, $priceType) = explode(',', $logs['f_url']);
					$dbresult2 = DB::table('tbl_price_static')
						->select('price', 'change')
						->where('relation_id', '=', $itemID)
						->where('f_cnf_fob', '=', $priceType)
						->first();
					if (!empty($dbresult2)) {
						include_once('/home/steelmin/public_html/hf.php');
						$item1 = getPriceAndCurrency($dbresult2['price'], $dbresult2['change']);
					}
				} else
					$itemID = $logs['f_url'];

				$item = array(
					'notificationTitle' =>   html_entity_decode($logs['notification_title'], ENT_QUOTES),
					'notificationDescription' => html_entity_decode($logs['description'], ENT_QUOTES),
					'priceType' => $priceType,
					'category' => $logs['category'],
					'sent_at' => $logs['sent_at'],
					'itemID' => intval($itemID),
					'timeline' => $logs['timeline'],
					'promotion_url' => $logs['f_url'],
					'icon' => url('/') . "/uploads/notification/" . strtolower($logs['category']) . "_1.png"
				);

				$result[] = array_merge($item, $item1);
			}
		}
		/* array (
				  'id' => '24080',
				  'notification_title' => 'SteelMint | Intel',
				  'description' => 'Ex-Mines Orissa India, falls down $100',
				  'category' => 'intel',
				  'category_id' => '',
				  'sent_at' => '2019-09-05 16:11:01',
				  'type' => 'T',
				  'sent_to_groups' => 'auto',
				  'f_url' => '12507',
				  'share_url' => 'https://www.steelmint.com/intel/intel-12507',
				) */
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function showPackageDetails(Request $request)
	{
		$resourceType = "app";
		$user_id = 0;

		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section = '';
		if ($request->has('section'))
			$section = strtolower($request->input('section'));
		else
			return new JsonResponse(array("status" => array("code" => 2014, "message" => "section type missing.")));

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}

		//$accessType='pre';//for visitor///
		$activePackegesIDs = array();
		if ($user_id) {
			$user = new User($user_id, $this->appType);
			$activePackeges = $user->accessiblePackagesToMemid($user_id);

			$activePackegesIDs = $activePackeges['IDs'];
			///print_r($activePackegesIDs);	
		}

		$currencyName = '';
		if ($request->has('currencyName'))
			$currencyName = strtolower($request->input('currencyName'));

		$packageID = array();
		if ($request->has('packageID'))
			$packageID = $request->input('packageID');
		if ($request->has('itemID'))
			$packageID = $request->input('itemID');
		$renderAt = '';
		if ($request->has('renderAt'))
			$renderAt = $request->input('renderAt');
		//include_once "/home/steelmin/public_html/api/storage/v2019/package_details.php";
		$result = \ApiQuery::getPackagesRows($user_id, $packageID, $section, 'Active', $resourceType, $activePackegesIDs, $this->appType, $currencyName, $deviceType, $renderAt);
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function pricesBookmarkedCommodities(Request $request)
	{
		if ($request->has('memid')) {
			$result = \ApiQuery::getBookrMarkedCommoditiesOfPrices($request->input('memid'));

			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
		} else {
			$code = 2002;
			$message = "Memid is missing";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
	}
	public function insightsBookmarkedCommodities(Request $request)
	{
		if ($request->has('memid')) {
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				$code = 2002;
				$message = "Improper input values!";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}


			$result = \ApiQuery::getBookrMarkedCommoditiesOfInsights($memid);

			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
		} else {
			$code = 2002;
			$message = "Memid is missing";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
	}

	public function getloginSuggestedPackage(Request $request)
	{
		$place = strtolower($request->input('place'));
		$result = array(

			"suggestedPackage" => array(
				"packageId" => "2",
				"packageName" => "Standard",
				"whatYouGet" => array("Prices", "Tenders", "Newsletters"),
				"period" => array(
					array(
						"name" => "1 year",
						"isDisabled" => "Y",
						"amountPerMonth" => 4999.0,
						"billed_text" => "Billed Anually",
						"currencyConvertor" => array(
							"USD" => array(
								"symbol" => "$",
								"code" => 'USD',
								"amount" => 110.00
							),
							"INR" => array(
								"symbol" => "₹",
								"code" => 'INR',
								"amount" => 6999.00
							)
						)
					)
				),
				"isActivePackage" => "Y",
				"minimumMagazineYear" => "2019"
			)
		);
		$code = 1001;
		$message = "success";
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getLoginDetails(Request $request)
	{
		$result = array();
		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'web') {
			if ($request->has('OTP') && $request->input('OTP') != '') {
				$remeberme = strtolower($request->input('remeberme'));
				$password = $request->input('password');
				$email = $request->input('email');
				$remember = $request->has('remember') ? $request->input('remember') : '';

				$auth = new authentication();

				if ($request->has('newOTP') && $request->input('newOTP') != '') {
					$userName = $request->input('userName');
					//$userName = $request->input('userName');
					$refreshToken = $auth->generateRefreshTokenV2022ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id = 'web', $resourceType, $this->appType);
				} elseif ($request->has('OTP') && $request->input('OTP') != '') {
					$userName = $request->input('userName');
					//$userName = $request->input('userName');
					$refreshToken = $auth->generateRefreshTokenV2019ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id = 'web', $resourceType, $this->appType);
				} else {
					$password = $request->input('password');
					$userName = $request->input('userName');
					if (empty($userName))
						$userName = $request->input('email');
					/* if ($request->has('DEBUG')){
						
								ECHO $refreshToken = $auth->generateRefreshTokenV2019V1($resourceType, $userName, $password, $request->all(), $remember);
								PRINT_R($_COOKIE);
							}ELSE */
					$refreshToken = $auth->generateRefreshTokenV2019($resourceType, $userName, $password, $request->all(), $remember);
					//PRINT_R($refreshToken);

				}

				if ($refreshToken) {
					$user_id = $refreshToken['uid'];
					$user = new User($user_id, $this->appType);
					$maxCount =	$user->isAccessible($resourceType, $section = 'prices', $itemID = '', $itemDate = '', $reportID = 0, $market = 'login');
					$sectionsIncludes =  session('sectionsIncludes');
					$marketsIncludes =  session('marketsIncludes');

					if (is_array($refreshToken)) {
						$refreshToken["sections_includes"] = $sectionsIncludes;
						$refreshToken["markets_includes"] = strtolower($marketsIncludes);
					}
				}

				if ($refreshToken == false && $request->has('OTP')) {
					$code = 2002;
					$message = "Unauthorized action. please enter correct OTP";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				} elseif ($refreshToken == "USER_NOT_EXIST") {
					$code = 2001;
					$message = "Unauthorized action. User doesn't Exist!";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				} elseif ($refreshToken == false) {
					$code = 2001;
					$message = "Unauthorized action. please enter correct username and password";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}

				if ($refreshToken == "NV") {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action. Email/User not verified")));
					//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));

				} elseif ($refreshToken == 'falseIPBL') {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "You are not authrised to access out side office")));
				}
				/* elseif ($refreshToken == 'falseAccess' )
						{
							return new JsonResponse(array("status"=>array("code" => 2013, "message" => "User already loggedIn from some other device"))) ;
							
						}elseif ($refreshToken == 'trueAL' )
						{
							return new JsonResponse(array("status"=>array("code" => 2013, "message" => "You are already loggedIn"))) ;
							
						} */ elseif ($refreshToken) {
					$code = 1001;
					$message = "success";

					/* 	//uncomment it when u want to apply the concept of multi login			
							if( $user_id  != 116707 ){
								$isMultipleLogin = DB::table('tbl_loggedin_users')
									->select('id')
									->where('mem_id', '=', $user_id )
									->where('status', '=', 'on' )
									->first();				
								
								if($isMultipleLogin['id'])
									return new JsonResponse(array("status"=>array("code" => 2013, "message" => "You are already loggedIn somewhere."))) ;
							}	 */

					$result = DB::table($_ENV['USER_TABLE'])
						->select('is_first_time_user', 'activity_meter')
						->where($_ENV['USER_ID'], '=', $user_id)
						->first();
					$show_manage_pref_screen = 'no';
					if ($result['is_first_time_user']) {
						$show_manage_pref_screen = 'yes';

						DB::table($_ENV['USER_TABLE'])
							->where($_ENV['USER_ID'], '=', $user_id)
							->where('is_first_time_user', '=', 0)
							->update(['activity_meter' => $result['activity_meter'] + $_val]);
					} else {
						DB::table($_ENV['USER_TABLE'])
							->where($_ENV['USER_ID'], '=', $user_id)
							->update(['activity_meter' => $result['activity_meter'] + $_val]);
					}
					$refreshToken['show_manage_pref_screen'] = $show_manage_pref_screen;

					//delete a row from tb1_online_member for teh memid as we want to start his last activity record afresh 
					//if( $user_id == 116707 ){
					DB::table('tbl_loggedin_users')
						->where('mem_id', '=', $user_id)
						->delete();
					DB::table('tb1_online_member')
						->where('mem_id', '=', $user_id)
						->delete();

					$loggin_try = array();
					$loggin_try["mem_id"] = $user_id;
					$loggin_try["log_time"] = $GLOBALS['currDateTime'];
					if ($request->has('toknix') && $request->input('toknix') != '')
						$loggin_try["ip_address"] = $request->input('toknix');
					else {
						include_once('/home/steelmin/public_html/hf.php');
						$loggin_try["ip_address"] = getIpAddress();
					}
					if ($request->has('sender'))
						$loggin_try["device"] = $request->input('sender') . "||" . $GLOBALS['currDateTime'];
					$loggin_try["status"] = "on";
					$loggin_try["remember_me"] = "N";
					//print_r($loggin_try);
					//DB::enableQueryLog(); 
					DB::table('tbl_loggedin_users')
						->insert($loggin_try);

					//}
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $refreshToken));
				}
			}
			if ($request->has('_t')) {
				$fields_chk = array("secret" => "6LfOZzcaAAAAAB2leEMYxHALlWG4MYW0iGgpQbKz", "response" => $request->_t);
				$fields_string = http_build_query($fields_chk);
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
				$output = curl_exec($ch);
				$res_flg = json_decode($output, true);

				if ($res_flg["success"] == true && !empty($res_flg["success"])) {
					$remeberme = strtolower($request->input('remeberme'));
					$password = $request->input('password');
					$email = $request->input('email');
					$remember = $request->has('remember') ? $request->input('remember') : '';

					$auth = new authentication();
					if ($request->has('newOTP') && $request->input('newOTP') != '') {
						$userName = $request->input('userName');
						$refreshToken = $auth->generateRefreshTokenV2022ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id = 'web', $request->all(), $remember, $this->appType);
					} elseif ($request->has('OTP') && $request->input('OTP') != '') {
						$userName = $request->input('userName');
						$refreshToken = $auth->generateRefreshTokenV2019ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id = 'web', $request->all(), $remember, $this->appType);
					} else {
						$password = $request->input('password');
						$userName = $request->input('userName');
						if (empty($userName))
							$userName = $request->input('email');

						//check if IP, phone number/email are blacklisted or not. if yes then return teh user from here
						//     $logs = DB::table('tbl_blacklisted_ips')
						//             ->select("id")
						// ->where('f_ip' , '=' , $_SERVER['REMOTE_ADDR'])
						// ->orWhere('f_username' , '=' , $userName)
						// ->get();

						//                                if( count($logs) > 0 ){
						//code commenetd by tarun on 6-mar-2024 as we migrated to bigmint today    
						// $code = 2001;
						// $message = "Username/IP (".$_SERVER['REMOTE_ADDR'].") has been blocked due to multiple incorrect logins. Please send an email to info@steelmint.com for further assistance.";
						// return new JsonResponse(array("status"=>array("code" => $code, "message" =>$message )));
						//                                }
						//IP, phone number/email are NOT blacklisted								


						$refreshToken = $auth->generateRefreshTokenV2019($resourceType, $userName, $password, $request->all(), $remember, $this->appType);
					}

					if ($refreshToken) {
						$user_id = $refreshToken['uid'];
						$user = new User($user_id, $this->appType);
						$maxCount =	$user->isAccessible($resourceType, $section = 'prices', $itemID = '', $itemDate = '', $reportID = 0, $market = 'login');
						$sectionsIncludes =  session('sectionsIncludes');
						$marketsIncludes =  session('marketsIncludes');

						if ($request->input('debug') == 'Y')
							echo '<pre>=>', $maxCount, ', ', print_r(session()->all()), '</pre>';

						if (is_array($refreshToken)) {
							$refreshToken["sections_includes"] = $sectionsIncludes;
							$refreshToken["markets_includes"] = strtolower($marketsIncludes);
						}
					}

					$isLoginInvalid = 0;

					if ($refreshToken == false && $request->has('OTP')) {
						$code = 2002;
						$message = "Unauthorized action. please enter correct OTP";
						$isLoginInvalid = 1;
						//return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
					} elseif ($refreshToken == "USER_NOT_EXIST") {
						$code = 2001;
						$message = "Unauthorized action. User doesn't Exist!";
						$isLoginInvalid = 1;
						//return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
					} elseif ($refreshToken == false) {
						$code = 2001;
						$message = "Unauthorized action. please enter correct username and password";
						$isLoginInvalid = 1;
						//return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
					}

					if ($refreshToken == "NV") {
						$code = 2001;
						$message = "Unauthorized action. Email/User not verified";
						$isLoginInvalid = 1;
						//							return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action. Email/User not verified"))) ;
						//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));

					} elseif ($refreshToken == 'falseIPBL') {
						$code = 2001;
						$message = "You are not authrised to access out side office";
						$isLoginInvalid = 1;
						//							return new JsonResponse(array("status"=>array("code" => 2100, "message" => "You are not authrised to access out side office"))) ;
					}
					/* elseif ($refreshToken == 'falseAccess' )
						{
							return new JsonResponse(array("status"=>array("code" => 2013, "message" => "User already loggedIn from some other device"))) ;
							
						}elseif ($refreshToken == 'trueAL' )
						{
							return new JsonResponse(array("status"=>array("code" => 2013, "message" => "You are already loggedIn"))) ;
						} */

					//elseif($refreshToken){ //commented by tarun on 21-7-2022 to add teh code of marking username, IP in blacklist if 3 attemps of unsuccessful logins happens
					if ($isLoginInvalid == 1) {
						//mark an entry in the table tbl_login_attempts for unsuccesful login 
						$ipAddress = $_SERVER['REMOTE_ADDR'];
						$dat = array(
							"f_username" => $userName,
							"f_status" => 'F',
							"f_source" => $resourceType . ' loginWithPassword',
							"f_ip" => $ipAddress,
							"f_password" => $password,
							"f_reason" => $message,
							"f_useragent" => $request->header('User-Agent')


						);
						DB::table('tbl_login_attempts')->insert($dat);

						//blacklist the IP if its the 3rd attempt of invalid OTP

						//         	$logs = DB::table('tbl_login_attempts')
						// 					->select("f_status")
						// 					->where('f_ip' , '=' , $ipAddress)
						// 					->where('f_username' , '=' , $userName)
						// 					->where('f_source' , '=' , $resourceType . ' loginWithPassword')
						// 					->where('f_datetime', 'like', '%' . date("Y-m-d") . '%')
						// 					->orderBy('id' , 'DESC')
						// 					->limit(5)
						// 					->get();
						// 			$cnt = 0;		
						//             foreach($logs as $r){
						// 				if($r['f_status']=='F'){    					
						// 				    $cnt += 1;		
						// 				}
						//             }	
						//echo "cnt:" . $cnt;
						//         if( $cnt == 5 ){
						// if( $userName != '' ){
						//     code commenetd by tarun on 6-mar-2024 as we migrated to bigmint today
						//                 $dat = array(
						//                             //"id"=> NULL, 
						//                             //"f_datetime"=>date( "Y-m-d H:i:s" ), 
						//                             "f_username"=>$userName, 
						//                             "f_reason"=> 'Invalid Login attempt thrice', 
						//                             "f_ip"=> $ipAddress
						//                         );
						//         		DB::table('tbl_blacklisted_ips')->insert($dat);	
						//         		$message = "Username/IP has been blocked due to multiple incorrect logins. Please send an email to info@steelmint.com for further assistance.";
						// }
						//         }


						return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
					} else {

						$code = 1001;
						$message = "success";

						/* 	//uncomment it when u want to apply the concept of multi login			
							if( $user_id  != 116707 ){
								$isMultipleLogin = DB::table('tbl_loggedin_users')
									->select('id')
									->where('mem_id', '=', $user_id )
									->where('status', '=', 'on' )
									->first();				
								
								if($isMultipleLogin['id'])
									return new JsonResponse(array("status"=>array("code" => 2013, "message" => "You are already loggedIn somewhere."))) ;
							}	 */

						$result = DB::table($_ENV['USER_TABLE'])
							->select('is_first_time_user', 'activity_meter')
							->where($_ENV['USER_ID'], '=', $user_id)
							->first();
						$show_manage_pref_screen = 'no';
						if ($result['is_first_time_user']) {
							$show_manage_pref_screen = 'yes';

							DB::table($_ENV['USER_TABLE'])
								->where($_ENV['USER_ID'], '=', $user_id)
								->where('is_first_time_user', '=', 0)
								->update(['activity_meter' => $result['activity_meter'] + $_val]);
						} else {
							DB::table($_ENV['USER_TABLE'])
								->where($_ENV['USER_ID'], '=', $user_id)
								->update(['activity_meter' => $result['activity_meter'] + $_val]);
						}
						$refreshToken['show_manage_pref_screen'] = $show_manage_pref_screen;

						//delete a row from tb1_online_member for teh memid as we want to start his last activity record afresh 
						//if( $user_id == 116707 ){
						DB::table('tbl_loggedin_users')
							->where('mem_id', '=', $user_id)
							->delete();
						DB::table('tb1_online_member')
							->where('mem_id', '=', $user_id)
							->delete();

						$loggin_try = array();
						$loggin_try["mem_id"] = $user_id;
						$loggin_try["log_time"] = $GLOBALS['currDateTime'];
						if ($request->has('toknix') && $request->input('toknix') != '')
							$loggin_try["ip_address"] = $request->input('toknix');
						else {
							include_once('/home/steelmin/public_html/hf.php');
							$loggin_try["ip_address"] = getIpAddress();
						}

						if ($request->has('sender'))
							$loggin_try["device"] = $request->input('sender') . "||" . $GLOBALS['currDateTime'];
						$loggin_try["status"] = "on";
						$loggin_try["remember_me"] = "N";
						//print_r($loggin_try);
						//DB::enableQueryLog(); 
						DB::table('tbl_loggedin_users')
							->insert($loggin_try);

						//}
						return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $refreshToken));
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 1414, "message" => "you are a bot"), "data" => $res_flg));
					//return new JsonResponse(array("status"=>array("code" => 1414 , "message" => "you are a bot")));
				}
			} else {
				return new JsonResponse(array("status" => array("code" => 1414, "message" => "you are a bot")));
			}
		} else {
			/*//added by mohan on <29-11-2021> for the purpose of update gcm divice concept*/
			$gcm_device_table = $this->appType == "CM" ? "gcm_device_cm" : "gcm_device";
			if ((($request->has('userName') || $request->has('email')) && ($request->input('userName') != '' || $request->input('email') != '')) || $request->has('accessToken')) {
				$physical_id = $request->input('deviceID');
				$fcm_token = $request->input('fcmToken');

				$auth = new authentication();
				if ($request->has('accessToken')) {
					$refreshToken = $request->input('accessToken');
				} elseif ($request->has('OTP') && $request->input('OTP') != '') {
					$userName = $request->input('userName');
					//$userName = $request->input('userName');
					if ($request->has('newOTP') && $request->input('newOTP') != '')
						$refreshToken = $auth->generateRefreshTokenV2022ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id, $request->all(), $remember = 0, $this->appType);
					else
						$refreshToken = $auth->generateRefreshTokenV2019ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id, $request->all(), $remember = 0, $this->appType);
				} else {
					$password = $request->input('password');
					$userName = $request->input('userName');
					if (empty($userName))
						$userName = $request->input('email');
					$refreshToken = $auth->generateRefreshTokenV2019($resourceType, $userName, $password, $request->all(), $remember = 0, $this->appType);
				}
				//if($request->input('OTP')==5198)
				//	echo '<pre>', print_r($refreshToken), '</pre>';
				if ($refreshToken == false && $request->has('OTP')) {
					$code = 2002;
					$message = "Unauthorized action. please enter correct OTP";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				} elseif ($refreshToken == false) {
					$code = 2013;
					$message = "Unauthorized action. please enter correct username and password";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				} elseif ($refreshToken == "USER_NOT_EXIST") {
					$code = 2001;
					$message = "Unauthorized action. User doesn't Exist!";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				} elseif ($refreshToken == false) {
					$code = 2001;
					$message = "Unauthorized action. please enter correct username and password";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}
				$show_manage_pref_screen = 'no';
				$user_id = $auth->authRefreshToken($refreshToken, $this->appType);

				if ($request->has('token') && empty($user_id)) {
					return new JsonResponse(array("status" => array("code" => 2013, "message" => 'Invalid Refresh Token')));
				}

				//include_once "/home/steelmin/public_html/api/storage/v2019/login_details.php";
				$code = 1001;
				$message = "success";

				$urlog = DB::table('tbl_reg_logs')
					->select('id')
					->where('memid', '=', $user_id)
					->where('status', '=', 'Active')
					->whereIn('f_product', array('W', 'MA'))
					->get();

				if (count($urlog) >= 1) {
					$_val = 10;
				} else
					$_val = 15;

				$result = DB::table($_ENV['USER_TABLE'])
					->select('*')
					->where($_ENV['USER_ID'], '=', $user_id)
					->first();

				if ($result['is_first_time_user']) {
					$show_manage_pref_screen = 'yes';

					DB::table($_ENV['USER_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id)
						->where('is_first_time_user', '=', 0)
						->update(['activity_meter' => $result['activity_meter'] + $_val]);
				} else {
					DB::table($_ENV['USER_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id)
						->update(['activity_meter' => $result['activity_meter'] + $_val]);
				}
				$activePackageName = '';
				$activePackageTenure = '';
				if ($refreshToken == "NV") {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action. Email not verified")));
					//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));

				} elseif ($refreshToken == 'MLR' && ($user_id != 83757 || $user_id != 99875 || $user_id != 99876 || $user_id != 99874 || $user_id != 99872 || $user_id != 99873)) {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "You are already loggedIn from some other device")));
				} elseif ($refreshToken) {
					$userType = 'Upgrade';
					//if any active log then its paid
					if ($_val == 10)
						$userType = 'Renew';

					$user = new User($user_id, $this->appType);

					$user_data = $user->get($user_id);
					$result = $user_data;
					//$dataArr= array ("refreshToken" => $refreshToken);
					$result["refreshToken"] = $refreshToken;

					$auth = new authentication();
					$token = $auth->generateToken($refreshToken, $this->appType);
					if ($token) {
						$result["accessToken"] = $token;
						//$result["accessToken"]=$token;
						if (is_string($token) && $token !== 'Unauthorized action. Token access denied') {
							$result['jwt'] = ApiJwt::encodeAccess($token, $resourceType, $user_id, $this->appType);
							$result['refreshJwt'] = ApiJwt::encodeRefresh($refreshToken, $user_id, $this->appType);
						}
					} else {
						$result["accessToken"] = "Unauthorized action. Token access denied";
					}

					///$maxCount =	$user->getTakenServicesByUser();
					$maxCount =	$user->isAccessible($resourceType, $section = 'prices', $itemID = '', $itemDate = '', $reportID = 0, $market = 'login');
					$sectionsIncludes =  session('sectionsIncludes');
					$marketsIncludes =  session('marketsIncludes');

					if ($marketsIncludes != '') {
						if ($request->input('debug') == 'Y')
							echo '<pre>=>', $marketsIncludes, '</pre>';
						$marketsIncludes_arr = explode(",", $marketsIncludes);
						if (!empty($marketsIncludes_arr)) {
							if ($request->input('debug') == 'Y')
								echo '<pre>=>', print_r($marketsIncludes_arr), '</pre>';
							$all_markets = ['ferrous', 'coal', 'non-ferrous', 'scrap-recycling', 'agriculture'];
							$firstMatch_market = '';
							foreach ($all_markets as $item) {
								if (in_array($item, $marketsIncludes_arr)) {
									$firstMatch_market = $item;
									break; // Exit the loop once the first match is found
								}
							}
							if ($request->input('debug') == 'Y')
								echo '<pre>=>', $firstMatch_market, '</pre>';
							if ($firstMatch_market != '') {
								$maxCount =	$user->isAccessible($resourceType, $section = 'prices', $itemID = '', $itemDate = '', $reportID = 0, $market = $firstMatch_market);
							}
						}
					}

					if ($request->input('debug') == 'Y')
						echo '<pre>=>', $maxCount, ', ', print_r(session()->all()), '</pre>';

					///$sectionsIncludes = session()->get('sectionsIncludes');
					$activePackageDetails = array();
					//if($user_id == 56350){
					if ($firstMatch_market != '') {
						$activePackageName =  session($firstMatch_market)['userService'];
						$dbresult2 = DB::table('tbl_packages')
							->select('period_name', 'unit_of_tenure')
							->where('id',   session($firstMatch_market)['userPackageID'])
							->first();
						$activePackageTenure = $dbresult2['period_name'] . ' ' . $dbresult2['unit_of_tenure'];
					}
					if (empty($activePackageName)) {
						$result1 = DB::table('tbl_reg_logs')
							->select('inv_no', 'selected_products')
							->where('inv_no', '<>', '')
							->where('id', '=', $user_id)
							->where('status', '<>', 'Active')
							->whereIn('f_product', array('W', 'MA', 'MA_PO'))
							->first();
						$activePackageName = 'Complete New';
						if ($result1) {
							$activePackageName = 'Not Renewed';
						}
					}
					//}

					if ($maxCount == -1)
						$user_type = 'Paid';
					elseif ($maxCount == 0)
						$user_type = 'Upgrade';
					else
						$user_type = 'Login';

					//add as prem want seprate param for $user_type as $CM_user_type
					$CM_user_type = '';
					//as we are merging the cm logs into sm
					//if($appType=='CM'){
					/*	$user1 = new User($user_id, 'CM');
						$maxCount_CM =	$user1->getTakenServicesByUser();
						if($maxCount_CM == -1)
							$CM_user_type='Paid';
						elseif($maxCount_CM == 0)
							$CM_user_type='Upgrade';
						else
							$CM_user_type='Login';
                    */
					//}
					$ud = date("Y-m-d H:i:s");
					DB::table($gcm_device_table)
						->where("device_id", '=', $fcm_token)
						->update(['user_id' => $user_id, 'user_token' => "line 2249;commonController.php; $ud"]);

					$userSysDtls = $fcm_token . '|' . $refreshToken;
					$loggin_try['mem_id'] = $user_id;
					$loggin_try['log_time'] = $GLOBALS['currDateTime'];
					$loggin_try['log_date'] = date("Y-m-d");
					$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR'];

					$loggin_try['device'] = $userSysDtls;
					//$loggin_try['device_name'] = $device_type;

					if ($physical_id != '') {
						$loggin_try['company'] = ($this->appType == 'CM') ? 'CoalMint' : 'SteelMint';
						$loggin_try['device_id'] = $physical_id;
						$loggin_try['device_name'] = 'android';
					} else {
						$loggin_try['device_name'] = 'IOS';
						//$loggin_try['deviceID'] = $fcm_token;
						if ($request->has('appType') && strtoupper($request->input('appType')) == 'CM') {
							$loggin_try['company'] = 'CoalMint';
						} else
							$loggin_try['company'] = 'SteelMint';
					}

					include_once('/home/steelmin/public_html/hf.php');
					$loggin_try['ip_country'] = ipTocntry($_SERVER['REMOTE_ADDR']);


					$creden = DB::table('tb1_online_member_loggin_try')
						->select(array('id'))
						->where('mem_id', '=', $user_id)
						->whereIn('device_name', array('android', 'IOS'))
						->where('company', '=', $loggin_try['company'])
						->get();

					if (!empty($creden)) {
						$online_member_loggin_iid = (isset($creden['id'])) ? $creden['id'] : 0;
						$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid;
					}

					$loggin_try['platform'] = "Mobile APP";
					$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";
					//print_r($loggin_try);
					///DB::enableQueryLog(); 

					DB::table('tb1_online_member_loggin_try')->insert($loggin_try);

					///dd(DB::getQueryLog());		
					if ($online_member_loggin_iid == 0) {
						$last_id = DB::getPdo()->lastInsertId();;
						DB::table('tb1_online_member_loggin_try')
							->where('id', '=', $last_id)
							->update(['parent_loggedin_id' => $last_id]);
						//echo 'get id:'.dd($last_id);
					}	//echo '10';	
					////}
					///end
					calculate_coc($user_id);
					$userTypeNew = 'Demo';
					if ($this->appType == 'SM' && ($activePackageName == 'Price Only' || $activePackageName == 'Standard' || $activePackageName == 'Corporate Standard' || $activePackageName == 'Free Trial'))
						$userTypeNew = 'Upgrade';
					elseif ($this->appType == 'CM' && ($activePackageName == 'Standard' || $activePackageName == 'Price Only' || $activePackageName == 'Free Trial'))
						$userTypeNew = 'Upgrade';
					elseif ($user_type == 'Paid')
						$userTypeNew = '';

					$code = 1001;
					$message = "success";
					/*$result["sections_includes"] = '';
					if(!empty($sectionsIncludes) && $sectionsIncludes !== null)*/
					$result["sections_includes"] = $sectionsIncludes;
					if ($resourceType == "app") {
						foreach ($sectionsIncludes as $key => $val) {
							$sectionsIncludes_key_pair[] = array("key" => $key, "name" => $val);
						}
						$result["sections_includes"] = $sectionsIncludes_key_pair;

						// print_r($result);
					}

					$result["markets_includes"] = strtolower($marketsIncludes);
					$result["activePackageName"] = $activePackageName;
					$result["activePackageTenure"] = $activePackageTenure;
					$result["service_type"] = $userType;
					$result["userType"] = $userTypeNew;
					$result["user_type"] = $user_type;
					$result["CM_user_type"] = $CM_user_type;
					$result["show_manage_pref_screen"] = $show_manage_pref_screen;
					$result["QRImage"] = BASEURL . "memidQRCodes/" . $user_id . ".png";

					\ApiQuery::updatePackageIDForApp($user_id);

					return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
					//return new Response( array( "status#" => "1" , "data#" => $dataArr, "service_type#" => $userType, "user_type#" => $user_type, "CM_user_type#" => $CM_user_type, "show_manage_pref_screen#" => $show_manage_pref_screen), 200);
				}
			} else {
				$code = 2100;
				$message = "Unauthorized action. please enter username and password";
			}
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	/**
	 * Issue new DB access token + JWT pair from refresh token or refresh JWT.
	 * Body: refreshToken (opaque) and optional resourceType (default app).
	 * Or Authorization: Bearer &lt;refreshJwt&gt;.
	 */
	public function refreshJwtTokens(Request $request)
	{
		$refreshToken = $request->input('refreshToken');
		if (empty($refreshToken)) {
			$authHeader = $request->header('Authorization');
			if ($authHeader && stripos($authHeader, 'Bearer ') === 0) {
				$jwt = trim(substr($authHeader, 7));
				$decoded = ApiJwt::decodeRefreshToken($jwt);
				if ($decoded !== null) {
					$refreshToken = $decoded->refresh;
					if ($request->input('appType') === null && isset($decoded->app)) {
						$this->appType = $decoded->app;
					}
				}
			}
		}
		if (empty($refreshToken)) {
			return new JsonResponse(array(
				'status' => array('code' => 2100, 'message' => 'refreshToken or refresh JWT required'),
			));
		}
		$auth = new authentication();
		$user_id = $auth->authRefreshToken($refreshToken, $this->appType);
		if (empty($user_id)) {
			return new JsonResponse(array(
				'status' => array('code' => 2013, 'message' => 'Invalid Refresh Token'),
			));
		}
		$newAccess = $auth->generateToken($refreshToken, $this->appType);
		if (empty($newAccess)) {
			return new JsonResponse(array(
				'status' => array('code' => 2100, 'message' => 'Unauthorized action. Token access denied'),
			));
		}
		$resourceType = $request->input('resourceType', 'app');
		$resourceType = is_string($resourceType) ? strtolower($resourceType) : 'app';

		$data = array(
			'accessToken' => $newAccess,
			'refreshToken' => $refreshToken,
			'jwt' => ApiJwt::encodeAccess($newAccess, $resourceType, $user_id, $this->appType),
			'refreshJwt' => ApiJwt::encodeRefresh($refreshToken, $user_id, $this->appType),
		);

		return new JsonResponse(array(
			'status' => array('code' => 1001, 'message' => 'success'),
			'data' => $data,
		));
	}

	//update FCMToken -
	public function updateFCMToken(Request $request)
	{
		$result = array();

		/* if ($request->has('deviceId') && $request->input('deviceId')!='') {
			$fcmToken = $request->input('fcmToken');//price/insights/tender	
			
			$code = 1001;
			$message = "Token Successfully updated";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		} */
		$resourceType = "app";
		$fireBaseUserValue = "Visitor";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		/*//added by mohan on <29-11-2021> for the purpose of update gcm divice concept*/
		$gcm_device_table = $this->appType == "CM" ? "gcm_device_cm" : "gcm_device";

		if ($request->has('deviceType') && $request->has('deviceID') && $resourceType == 'app') {
			$deviceType = $request->input('deviceType');
			$physical_id = $request->input('deviceID'); ///FCM TOKEN =>android_id 
			$accessToken = $request->input('accessToken'); 	///token  

			if ($physical_id == 'ba19b2a0c7a24cf9' && empty($request->input('fcmToken')))
				$deviceID = 'ef0Cj_x8QPuYhk0zKeXJ7J:APA91bEO5GpKPIic-gpWv2tFV-NjfYhSrNZlad8k9v9VgCIHk3exnrwXbP6EBbX1WErJJjQf43sJJIGuQKyC9z0jJMf5yUv1v2gDXW6mhVusDjsPgc13UqcPvLEiWyMKxYihqo5DbVap'; ///default device id for memid : 107466
			else
				$deviceID = $request->input('fcmToken'); ///android/IOS id (push notification)

			$deviceInfo = $request->input('deviceInfo');
			$isNewApp = 'n';
			if ($request->has('isNewApp'))
				$isNewApp = $request->input('isNewApp');

			/* $_data = array(
						'f_data' => $deviceType . " -- " . $physical_id . " -- " . $accessToken . " -- " . $deviceID . " -- " . $deviceInfo,
						'f_gateway_name' => date("Y-m-d H:i:s")
					);
			
			$insertIntotbltry = DB::table('tbl_try')
				->insertGetId($_data);  */


			///get visitor_iid///
			$company = 'SteelMint';
			$sender = '';
			$lan_ip = '';
			$parent = $physical_id; //physical_id
			$_sender_agent = $deviceID; //fcm token

			$device = '';

			if ($request->has('deviceType'))
				$device = $request->input('deviceType');
			$platform = "Mobile APP";

			if ($request->has('ip'))
				$ip = $request->input('ip');
			else
				$ip =  $_SERVER['REMOTE_ADDR'];

			///include_once("/home/steelmin/public_html/hf.php");
			$ip_country = ipTocntry("$ip");

			$creden = DB::table('tb1_visitor_history')
				->select(array('id'))
				//->where('ip_country', '=', $ip_country )
				//->where('ip_address', '=', $ip )
				//->where('lan_ip', '=', $lan_ip )
				->where('device_id', '=', $parent)
				//->where('device', '=', $_sender_agent )
				->where('device_name', '=', $device)
				->where('platform', '=', $platform)
				->where('company', '=', $company)
				->first();

			$visitor_iid = (isset($creden['id'])) ? $creden['id'] : 0;
			if ($visitor_iid == 0) {
				$_data = array(
					'mem_id' => 0,
					'log_date' => $GLOBALS['currDate'],
					'log_time' => $GLOBALS['currTime'],
					'ip_country' => $ip_country,
					'ip_address' => $ip,
					'lan_ip' => $lan_ip,
					'device_id' => $parent,
					'device' => $_sender_agent,
					'device_name' => $device,
					'company' => $company,
					'platform' => $platform
				);

				$visitor_iid = DB::table('tb1_visitor_history')
					->insertGetId($_data);
			}
			////

			$user_id = '';
			if ($request->has('accessToken')) {
				$token = $request->input('accessToken');
				$auth = new authentication();
				$user_id = $auth->authToken($token, $this->appType);
				if (!$user_id)
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action. Token access denied")));
			}

			///$deviceInfo = $request->input('deviceInfo'); 
			if ($request->input('deviceType') == 'android' || $request->input('deviceType') == 'ios') {
				///$deviceID = $request->input('deviceID') ;
				$deviceID = trim($deviceID);

				///$_app_ver="8.0";//7.4 missing 	
				//$_app_ver= $request->input('deviceType') == 'ios'?"9.4":"9.5";
				$_app_ver = $request->input('deviceType') == 'ios' ? "10.0.0" : "10.0.2";

				if ($this->appType == 'CM') {
					if ($request->input('deviceType') == 'ios')
						$_app_ver = "3.4";
					else
						$_app_ver = "8.6";
				}

				$sel_admob = DB::table($gcm_device_table)
					->where("device", "=", $request->input('deviceType'))
					->where("device_id", "=", $deviceID)
					->where("appType", "=", $this->appType)
					->first();

				//->where("isNewApp" , "=" , $isNewApp )
				if ($sel_admob) {
					////$show_admob=$sel_admob['admob'];
					if ($user_id != '') {
						$ud = date("Y-m-d H:i:s");
						DB::table($gcm_device_table)
							->where("device", "=", $request->input('deviceType'))
							//->where("deviceInfo" , "=" , $deviceInfo )
							->where("device_id", "=", $deviceID)
							->where("appType", "=", $this->appType)
							->update(["user_id" => 0, 'user_token' => 'line 2477;commonController.php--' . $ud . '--' . $request->has('accessToken') . '-- User ID:' . $user_id]);

						/*
						if( $user_id == 96212 || $user_id == 77825 ){
							$str_test = $ud;
							$sd_test = "";
							$u1Data_test = array(
															"f_data"=>$str_test,
															"f_gateway_name"	=>date("Y-m-d H:i:s"),
															"relation_ids"	=>	 ''
														);
							DB::table("tbl_try")->insert($u1Data_test) ;
						}*/
						$cc_comment = 'line 2488;commonController.php, User :' . $user_id . ', physical_id :' . $physical_id . ', DeviceId: ' . $deviceID;
						$uData = array(
							"updated_at" => $GLOBALS['currDateTime'],
							"device" => $deviceType,
							"device_id" => $deviceID,
							"user_id" => $user_id,
							"memid_immortal" => $user_id,
							"deviceInfo" => $deviceInfo,
							'user_token' => $cc_comment,
							"physical_id" => $physical_id,
							"status" => 'enable',
							"appType" => $this->appType
						);

						/*
            START: test code
            */
						/*  $d = date("Y-m-d H:i:s");
                
                $str = htmlentities("common.php->" . $user_id . ' -- ' . $request->input('deviceType') . ' -- ' . $deviceID . ' -- ' . $this->appType . ' -- ' . $gcm_device_table, ENT_QUOTES);
                $sd = serialize($uData);
                $u1Data = array(
                							"f_data"=>$str,
                							"f_gateway_name"	=>	$d,
                							"relation_ids"	=>	$sd
                						);
                DB::table("tbl_try")->insert($u1Data) ;		 */
						/*
            END: test code
            */


						$show_admob = 'N';
						DB::table($gcm_device_table)
							->where("device", "=", $request->input('deviceType'))
							->where("device_id", "=", $deviceID)
							->where("appType", "=", $this->appType)
							->update($uData);


						\ApiQuery::updatePackageIDForApp($user_id);
					}
					$packageDtls = \ApiQuery::getPackageDtlsOfMemid($user_id);
					$a =  json_decode($packageDtls);

					$allowIntel = 'N';
					if ($a->package_status == 'Active' && $a->package_name != 'Price Only') {
						$allowIntel = 'Y';
						if ($a->package_name == 'Free Trial')
							$fireBaseUserValue = "Free Trial";
						else
							$fireBaseUserValue = "Paid";
					} elseif ($a->package_status != 'Active')
						$fireBaseUserValue = "Inactive";
					else
						$fireBaseUserValue = "Paid"; ///when price only

					if ($user_id == 107767 ||  $user_id == 116707 ||  $user_id == 3668 ||  $user_id == 115893 || $user_id == 5652 || $user_id == 44001 || $user_id == 78616 || $user_id == 117471 || $user_id == 107067)
						$FAB_URL = "https://www.steelmint.com/steeladmin/rating/";
					else
						$FAB_URL = "";

					return new JsonResponse(array("status" => array("code" => 1001, "message" => "Device already registered"), "data" => array(
						"latest_app_version_in_play_store" 	=> $_app_ver,
						"allow_copy_news" 					=> "0",
						"visitor_id" 						=> $visitor_iid,
						"package_name"						=> $a->package_name,
						"package_status"					=> $a->package_status,
						"package_duration"					=> $a->package_duration,
						"allow_intel"						=> $allowIntel,
						"FAB_URL"						=> $FAB_URL,
						"fireBaseUserKey" => "steelmint_user_type",
						"fireBaseUserValue" => $fireBaseUserValue
					)));
					/* return new JsonResponse(array(
						"status#" =>"1",
						"message#" => "Device already registered",
						"latest_app_version_in_play_store" => $_app_ver,
						"allow_copy_news" => "0",
						
					)) ; */
				}

				$uData = array(
					"created_at" => $GLOBALS['currDateTime'],
					"device" => $deviceType,
					"device_id" => $deviceID,
					"user_id" => $user_id,
					"memid_immortal" => $user_id,
					"deviceInfo" => $deviceInfo,
					"physical_id" => $physical_id,
					"status" => 'enable',
					"appType" => $this->appType,
					"isNewApp" => $isNewApp
				);
				//print_r($uData);
				//else insert new device details
				try {
					if ($request->input('deviceType') == 'ios') {
						include_once('/home/steelmin/public_html/api/pre_function/helper.php');
						if (setOneSignalNotifiation($deviceID)) {
							$uData["registered_with_onesignal"] = 1;
						}
					}

					DB::table($gcm_device_table)->insert($uData); //insertGetId
				} catch (QueryException $e) {
					dd($e);
				}
				//return new JsonResponse(array("code" => 1001, "message" => "success" , "latest_app_version_in_play_store" => $_app_ver, "allow_copy_news" => "0"));
				//return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success" , "latest_app_version_in_play_store" => $_app_ver, "allow_copy_news" => "0")));
				$packageDtls = \ApiQuery::getPackageDtlsOfMemid($user_id);
				$a =  json_decode($packageDtls);
				$allowIntel = 'N';
				if ($a->package_status == 'Active' && $a->package_name != 'Price Only') {
					$allowIntel = 'Y';
					if ($a->package_name == 'Free Trial')
						$fireBaseUserValue = "Free Trial";
					else
						$fireBaseUserValue = "Paid";
				} elseif ($a->package_status != 'Active')
					$fireBaseUserValue = "Inactive";
				else
					$fireBaseUserValue = "Paid"; ///when price only

				if ($user_id == 107767 ||  $user_id == 116707 ||  $user_id == 3668 ||  $user_id == 115893 || $user_id == 5652 || $user_id == 44001 || $user_id == 78616 || $user_id == 117471 || $user_id == 107067)
					$FAB_URL = "https://www.steelmint.com/steeladmin/rating/";
				else
					$FAB_URL = "";

				return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => array(
					"latest_app_version_in_play_store" => $_app_ver,
					"allow_copy_news" => "0",
					"visitor_id" => $visitor_iid,
					"package_name"						=> $a->package_name,
					"package_status"					=> $a->package_status,
					"package_duration"					=> $a->package_duration,
					"allow_intel"						=> $allowIntel,
					"FAB_URL"						=> $FAB_URL,
					"fireBaseUserKey" => "steelmint_user_type",
					"fireBaseUserValue" => $fireBaseUserValue
				)));

				$code = 1001;
				$message = "success";
			} else {
				//$code = 2100;
				$code = 2001;
				$message = "Device not detected.";
				///return new JsonResponse(array("status"=>array("code" => 2013, "message" => "Device not detected"))) ;
			}
		} elseif ($resourceType == 'web') {
			$company = 'SteelMint';
			$sender = '';
			$lan_ip = '';
			$parent = '';
			$_sender_agent = '';
			$platform = '';
			$device = '';

			if ($request->has('sender'))
				$sender = $request->input('sender');
			if ($request->has('tokinx'))
				$lan_ip = $request->input('tokinx');
			if ($request->has('parent'))
				$parent = $request->input('parent');


			if ($request->has('browser_name_pattern'))
				$_sender_agent = $request->input('browser_name_pattern');
			if ($request->has('deviceType'))
				$platform = $request->input('deviceType');
			if ($request->has('platform'))
				$device = $request->input('platform');

			if ($request->has('ip'))
				$ip = $request->input('ip');
			else {
				$ipAddress = $_SERVER['REMOTE_ADDR'];
				if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
					$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
				}
			}

			///include_once("/home/steelmin/public_html/hf.php");
			$ip_country = ipTocntry("$ip");

			$creden = DB::table('tb1_visitor_history')
				->select(array('id'))
				->where('ip_country', '=', $ip_country)
				->where('ip_address', '=', $ip)
				->where('lan_ip', '=', $lan_ip)
				->where('device_id', '=', $parent)
				->where('device', '=', $_sender_agent)
				->where('device_name', '=', $device)
				->where('platform', '=', $platform)
				->where('company', '=', 'SteelMint')
				->first();

			$visitor_iid = (isset($creden['id'])) ? $creden['id'] : 0;

			if ($visitor_iid == 0) {

				$_data = array(
					//'mem_id' => $memid,
					'log_date' => $GLOBALS['currDate'],
					'log_time' => $GLOBALS['currTime'],
					'ip_country' => $ip_country,
					'ip_address' => $ip,
					'lan_ip' => $lan_ip,
					'device_id' => $parent,
					'device' => $_sender_agent,
					'device_name' => $device,
					'company' => $company,
					'platform' => $platform
				);
				//print_r($_data);
				//	dd();
				$visitor_iid = DB::table('tb1_visitor_history')->insertGetId($_data);
			}

			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => array("allow_copy_news" => "0", "visitor_id" => $visitor_iid)));
		} else {
			//$code = 2100;
			$code = 2001;
			$message = "Invalid request.";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}
	///user profile
	public function savePersonalDetails(Request $request)
	{
		$result = array();
		$resourceType = "app";

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		if ($user_id) {
			$data = array();
			$user = new User($user_id);

			if ($request->has('name')) {
				if (!empty($request->input('name'))) {
					$data['name'] = $request->input('name');
				} else {
					//return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Name must not be empty!")));
				}
			}

			if ($request->has('email') || $request->has('alternateEmail')) {
				if (!empty($request->input('email'))) {
					$value = $request->input('email');
					if ($user->checkEntryWithOthers('email', $value, $user_id)) { ///is user duplicate entry
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "email already registered with some other user.")));
					}

					if ($request->has('alternateEmail') && $user->checkEntryWithOthers('addtnl_email', $value, $user_id)) { ///is user duplicate entry
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate email already registered with some other user.")));
					}

					if ($request->has('alternateEmail')) {
						$alternateEmailvalue = $request->input('alternateEmail');
						if ($user->checkEntryWithOthers('email', $alternateEmailvalue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate email, already registered with some other user.")));
						}

						if ($user->checkEntryWithOthers('addtnl_email', $alternateEmailvalue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate email, already registered with some other user.")));
						}

						if ($user->checkEntryWithSame('email', $alternateEmailvalue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate email, already registered with same user.")));
						}
					}

					if ($resourceType == 'app') {
						$user_data = $user->get($user_id);
						if ($request->has('email') && $user_data['email'] == '') { //update if first time.
							$data['email'] = $request->input('email');
						}

						if ($request->has('alternateEmail') && $user_data['alternateEmail'] == '') { //update if first time.
							$data['addtnl_email'] = $request->input('email');
						}
						/*$result = DB::table('tbl_members')
							->select('send_email_to')
							->where('id', '=', $user_id)
							->first();
						
						if(isset($result['send_email_to']) && $result['send_email_to'] == 'R') {
							$data['email'] = $request->input('email');
						} else {
							$data['addtnl_email'] = $request->input('email');
						}*/
					} else {
						if ($request->has('email'))
							$data['email'] = $request->input('email');
						if ($request->has('alternateEmail'))
							$data['addtnl_email'] = $request->input('alternateEmail');
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "email. must not be empty!")));
				}
			}

			if ($request->has('phoneno') || $request->has('alternatePhoneno')) {
				if (!empty($request->input('phoneno'))) {
					$value = $request->input('phoneno');
					if ($user->checkEntryWithOthers('phoneno', $value, $user_id) || $user->checkEntryWithOthers('alternate_mob_no', $value, $user_id)) { ///is user duplicate entry
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "phoneno already registered with some other id.")));
					}

					if ($request->has('alternatePhoneno')) {
						$alternatePhonenoValue = $request->input('alternatePhoneno');
						if ($user->checkEntryWithOthers('phoneno', $alternatePhonenoValue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate phoneno, already registered with some other user.")));
						}

						if ($user->checkEntryWithOthers('alternate_mob_no', $alternatePhonenoValue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate phoneno, already registered with some other user.")));
						}

						if ($user->checkEntryWithSame('phoneno', $alternatePhonenoValue, $user_id)) { ///is user duplicate entry in same reg user
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "alternate phoneno, already registered with same user.")));
						}
					}

					if ($resourceType == 'app') {
						/*$result = DB::table('tbl_members')
							->select('send_sms_to')
							->where('id', '=', $user_id)
							->first();
						
						if(isset($result['send_sms_to']) && $result['send_sms_to'] == 'R') {
							$data['phoneno'] = $request->input('phoneno');
						} else {
							$data['alternate_mob_no'] = $request->input('phoneno');
						}*/
					} else {
						if ($request->has('phoneno'))
							$data['phoneno'] = $request->input('phoneno');
						if ($request->has('alternatePhoneno'))
							$data['alternate_mob_no'] = $request->input('alternatePhoneno');
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Phone no. must not be empty!")));
				}
			}

			if ($request->has('DOB')) {
				if (!empty($request->input('DOB'))) {
					$data['dob'] = $request->input('DOB');
				}
			}

			if ($request->has('jobTitle')) {
				if (!empty($request->input('jobTitle'))) {
					$data['job_title'] = $request->input('jobTitle');
				}
			}

			if ($request->has('companyName')) {
				if (!empty($request->input('companyName'))) {
					$data['company'] = $request->input('companyName');
				}
			}

			if ($request->has('companyType')) {
				if (!empty($request->input('companyType'))) {
					$data['companytype'] = $request->input('companyType');
				}
			}

			if ($request->has('address')) {
				if (!empty($request->input('address'))) {
					$data['address'] = $request->input('address');
				} else {
					return new JsonResponse(array("status#" => "0", "message#" => "Address must not be empty!"), 200);
				}
			}

			/* if($request->has('city') && !empty($request->input('city'))) {
				$data['city'] = $request->has('city');
			}
			if($request->has('state') && !empty($request->input('state'))) {
				$data['state'] = $request->has('state');
			}
			if($request->has('country') && !empty($request->input('country'))) {
				$data['country'] = $request->has('country');
			} */
			if ($request->has('location')) {
				if (!empty($request->input('location'))) {
					$location = htmlentities($request->input('location'), ENT_QUOTES);
					$location = explode(",", $location);
					$data['city'] = 0;
					$data['state'] = 0;
					$data['country'] = 0;

					if (isset($location[2])) {

						$dbresult1 = DB::table('tbl_country')
							->select('id')
							->where('country', trim($location[2]))
							->orWhere('std_code', $isdCode)
							->first();

						if (count($dbresult1) > 0) {
							$data['country'] = $dbresult1['id'];
						}
					}

					if (isset($location[1])) {
						$dbresult1 = DB::table('tbl_state_city')
							->select('state_id')
							->where('state_name', trim($location[1]))
							->Where('country_id', $data['country'])
							->first();

						if (count($dbresult1) > 0) {
							$data['state'] = $dbresult1['state_id'];
						}
					}

					if (isset($location[0])) {
						$dbresult1 = DB::table('tbl_state_city')
							->select('city_id')
							->where('state_name', trim($location[1]))
							->Where('city_name', trim($location[0]))
							->first();

						if (count($dbresult1) > 0) {
							$data['city'] = $dbresult1['city_id'];
						}
					}

					if ($data['country'] == 0) { //country not found
						$data['other_city'] = $request->has('location');
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Please select location!")));
				}
			}

			/* if($request->has('location')) {
				if(!empty($request->input('location'))) {
					$location = explode(",", $request->input('location'));
					$data['city'] = 0;
					$data['state'] = 0;
					$data['country'] = 0;

					if(isset($location[0])) {
						$data['city'] = trim($location[0]);
					}

					if(isset($location[1])) {
						$data['state'] = trim($location[1]);
					}

					if(isset($location[2])) {
						$data['country'] = trim($location[2]);
					}

				} else {
					return new JsonResponse(array("status#" => "1006" , "message#" => "Please select location!"), 200);
				}
			} */

			if ($request->has('zipCode')) {
				if (!empty($request->input('zipCode'))) {
					$data['pin_code'] = $request->input('zipCode');
				} else {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "zip Code must not be empty!")));
				}
			}

			if ($request->has('profilePic')) {
				$str = str_replace('\\', '', $request->input('profilePic'));
				$str = str_replace(' ', '+', $str);
				$str = base64_decode($str);
				$pic_name = $request->input('profilePic_name');
				$fileExtension = 'png';
				file_put_contents("/home/steelmin/public_html/images/clients/" . $pic_name . ".png", $str);
				$data['profile_pic'] = $pic_name . ".png";

				//uncomment if you want to save the same in AWS
				/*                
                $fileYoPushToAWSBucket = "https://www.steelmint.com/images/clients/".$data['profile_pic'];
                file_get_contents(
                            "http://13.126.2.75/code/multipart_pdf_to_s3.php?uploadToS3=y&pdfFilePath=$fileYoPushToAWSBucket&bucketName=bmserverdbbackup&s3Key=common/images/entity&fileExt=$fileExtension"    
                        );
				$data['profile_pic_aws'] = $pic_name;*/
			}

			/* if($request->has('protype')) {
				$data['protype'] = $request->input('protype');
			} else {
				$data['protype'] = "";
			} */


			if ($request->has('companyProfile')) {
				$data['company_profile'] = $request->input('companyProfile');
			}


			$isd_code = array();

			if ($request->has('isdCode')) {
				//$isd_code = explode(" ", htmlspecialchars($request->input('isdCode'), ENT_QUOTES));
				//$data['isd_code'] = end($isd_code);
				$data['isd_code'] = htmlspecialchars($request->input('isdCode'), ENT_QUOTES);
			}

			if ($data) {
				DB::table('tbl_members')
					->where('id', $user_id)
					->update($data);
			}

			$code = 1001;
			$message = "Successfully Saved";
		} else {
			$code = 2100;
			$message = "Unauthorized action.";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function getPersonalDetails(Request $request)
	{
		$result = array();

		/* if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$memid = $request->input('memid');
			include_once "/home/steelmin/public_html/api/storage/v2019/personal_details.php";
			$code = 1001;
			$message = "success";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		} */
		$result = array();
		$resourceType = "app";

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		if ($user_id) {
			if ($resourceType == 'web') {
				///same
			} else { //$resourceType=='app'
				//same
			}
			$user = new User($user_id);
			$result = $user->getProfile($user_id);
			if ($result) {
				$code = 1001;
				$message = "success";
			} else {
				$code = 2013;
				$message = "No user data";
			}
		} else {
			$code = 2001;
			$message = "Unauthorized action";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	//register -
	public function renewPackages(Request $request)
	{
		$section = 'steelmint';
		/* if ($request->has('section'))
			$section = strtolower($request->input('section'));
		else
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => " section is missing"))); */

		if (!$request->has('logID')) { //tbl_reg_log.id
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "invalid logID for renew!")));
		} elseif ($section == 'steelmint') {
			$logID = $request->input('logID');

			$dbresult = DB::table('tbl_reg_logs')
				->select('*')
				->where('id', $logID)
				->orWhere('parent_id', $logID)
				->orderBy('parent_id', 'asc')
				->get();

			$paren_logID = 0;
			$paren_memid = 0;
			$servType = 'Renew Service';
			if (count($dbresult) > 0) {
				foreach ($dbresult as $logs) {
					$logs['id'] = '';

					$logs['bank_name'] = '';
					$logs['pymDtls'] = '';
					$logs['inv_no'] = '';
					$logs['pymtMode'] = '';

					$packageID = $logs['selected_products'];
					$memid = $logs['memid'];

					//if($logs['parent_id']==0){
					$dbresult2 = DB::table('tbl_packages')
						->select('*')
						->where('id', (int)$packageID)
						->get();

					if (count($dbresult2) > 0) {
						$packageName =  $dbresult2[0]['packageName'];
						$periodName =  $dbresult2[0]['period_name'];
						$totalAmountWoGST =  $dbresult2[0]['totalAmount_Wo_GST'];
						$totalAmountWithGST =  $dbresult2[0]['totalAmount_With_GST'];
						$discountPercentage =  $dbresult2[0]['discount_percentage'];
						$amountPerMonth =  $dbresult2[0]['amountPerMonth'];
						$currencyCode =  $dbresult2[0]['currency_code'];
						/* $scratch_value =  $dbresult2[0]['scratch_value'] ;
							
							$packageGroupID =  $dbresult2[0]['group_id'] ;
							$packageSubGroupId =  $dbresult2[0]['sub_group_id'] ;
							$packageOrder =  $dbresult2[0]['package_order'] ; */
					}
					//}
					$gst_Amt = 0;
					$SBCess = 0;
					if ($logs['ST'] > 0) { //if tax applicable
						//$gst_Rate=$logs['gst_rate'];
						$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax']) / 100);

						$totalAmountWithGST = $totalAmountWoGST + $gst_Amt;

						$SBCess = 0;
						if ($gst['EC'] > 0) { //for C.G.
							$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
							$SBCess = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
						}

						///$logs['amtPaid']=$totalAmountWithGST;
						///$logs['amountWOTax']=$totalAmountWoGST;
						$logs['ST'] = $gst_Amt;
						$logs['EC'] = $SBCess;
						$logs['gst_rate'] = $GLOBALS['STtax'];
					}
					//copy row with following changes
					$logs['startdate'] = date("Y-m-d", strtotime($logs['enddate'] . " +1 day"));
					$logs['enddate'] = date("Y-m-d", strtotime($logs['startdate'] . " +$periodName months"));
					$logs['f_time'] = $GLOBALS['currTime'];
					$logs['status'] = 'Pending';
					$logs['comments'] = 'Renew Service';
					$logs['amtPaid'] = $totalAmountWithGST;
					$logs['amountWOTax'] = $totalAmountWoGST;
					$logs['created_on'] = $GLOBALS['currDateTime'];
					$logs['datepay'] = "0000-00-00 00:00:00";
					$logs['paymentstatus'] = "Pending";
					$logs['pipeline_status'] = "New";
					$logs['mapping_id'] = "";
					$logs['parent_id'] = $paren_logID;

					$currencyCode = $logs['f_currency'];

					try {
						$_log_id = DB::table('tbl_reg_logs')->insertGetId($logs);
					} catch (QueryException $e) {
						dd($e);
					}

					if (!empty($_log_id) && $rm_arr['first_log_id'] == '') {
						//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
						//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
						$data['first_log_id'] = $_log_id;
						DB::table('tbl_reg_logs')
							->where('id', $_log_id)
							->update($data);
					}

					if ($logs['parent_id'] == 0) {
						$paren_logID = $_log_id;
						$paren_memid = $memid;
					}
				}

				DB::table($_ENV['COMMENTS_TABLE'])->insert([
					'memid' => $paren_memid,
					'f_date' => $GLOBALS['currDate'],
					'f_time' => $GLOBALS['currTime'],
					'comments' => "Request Service Type : " . $servType,
					'created_by' => 'self',
					'comments_for' => ''
				]);

				///
				$userMessage = '';
				/* if($packageName=='Price Only'){//send mail to RM and Show RM contact deatils to user
					$userMessage =  \ApiQuery::sendRequestMailToRM($paren_memid);
					$paymentURL='';
					$paymentType='';
				}else */ {
					//$paymentURL='https://www.steelmint.com/pay/newCheckOut_new.php';
					$paymentType = 'web';
				}

				$billNo = getSMorderNoForCCAVENUE("SteelMint");
				if ($logs['pymt_details'] == 'CCAVENUE')
					$paymentURL = BASEURL . "pay/commonCheckOut.php?reglogs_id=" . $_log_id . "&amt=" . intval($totalAmountWithGST) . "&orderid=" . $billNo . "&uid=" . $memid . "&pymtSrc=Renew&productPurchased=" . urlencode($packageName) . "&crency=$currencyCode&page_name=$section&gst_verif=done";
				else
					$paymentURL = BASEURL . "paypal/common_payment.php?reglogs_id=" . $_log_id . "&amt=" . intval($totalAmountWithGST) . "&orderid=" . $billNo . "&pymtSrc=Renew&crency=$currencyCode&productPurchased=" . urlencode($packageName) . "&item_desc=" . urlencode($packageName) . "&page_name=$section&gst_verif=done";

				$result = array(
					"paymentType" => "web", //sdk/web
					"paymentURL" => $paymentURL, //"https://www.steelmint.com/pay/newCheckOut_new.php",
					"message" => $userMessage, //if no payment neended
					"packageName" => $packageName,
					"lastLogId" => $_log_id,
					"totalAmount" => $totalAmountWoGST,
					"amountPayable" => $totalAmountWithGST,
					"gstAmt" => $gst_Amt,
					"gstRate" => $GLOBALS['STtax'],
					"billedText" => '',
					///"tax"=>900,
					"discount" => round(($totalAmountWoGST * $discountPercentage) / 100, 2),
					"discountPercentage" => $discountPercentage,
					"currency" => $currencyCode
				);

				$code = 1001;
				$message = "Successfully Register";
			}

			return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
		} elseif ($section == 'events') {
			//
		}
	}

	public function register(Request $request)
	{
		$result = array();

		$resourceType = "app";
		$section = "steelmint";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($request->has('section'))
			$section = strtolower($request->input('section'));

		if ($section == "steelmint" && $resourceType == 'web') {
			$f_product = 'W';
		}
		if ($section == "steelmint" && $resourceType == 'app') {
			$f_product = 'MA';
		}

		$totalLicenses = 1;
		if (!$request->has('packageID')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "invalid package selection!")));
		} else {
			$packageID = $request->input('packageID');
		}

		if ($request->has('email') && $request->has('mobileNo')) {
			if (empty($request->input('email'))) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "mobile no not be empty!")));
			}
			if (empty($request->input('mobileNo'))) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => " mobile no not be empty!")));
			}


			$email = $request->input('email');
			$mobileNo = $request->input('mobileNo');
			$isdCode = $request->input('isdCode');

			if ($request->has('totalLicenses'))
				$totalLicenses = $request->input('totalLicenses');

			/* if ( $user->checkEntryWithOthers('email' , $value, $user_id) || $user->checkEntryWithOthers('alternateEmail' , $value, $user_id)){///is user duplicate entry
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => "email already registered with some other id.")));
			} */

			$ipAddress = $_SERVER['REMOTE_ADDR'];
			if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
				$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
			}
			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
				->select('id')
				->where(function ($q) use ($email) {
					$q->where('email', $email)
						->orWhere('addtnl_email', $email)
						->orWhere('username', $email);
				})
				->orWhere(function ($q) use ($mobileNo) {
					$q->where('phoneno', $mobileNo)
						->orWhere('alternate_mob_no', $mobileNo)
						->orWhere('username', $mobileNo);
				})
				->first();
			//dd(DB::getQueryLog());
			$location = '';
			$comments = $section . '<br>';

			if (count($dbresult) == 0) { ///new user 

				$newUser['email'] = $email;
				$newUser['username'] = $email;
				$newUser['phoneno'] = $mobileNo;
				$newUser['isd_code'] = $isdCode;

				if ($request->has('name')) {
					if (!empty($request->input('name'))) {
						$newUser['name'] = htmlentities($request->input('name'), ENT_QUOTES);
					} else {
						//return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Name must not be empty!")));
					}
				}
				if ($request->has('jobTitle')) {
					if (!empty($request->input('jobTitle'))) {
						$newUser['job_title'] = htmlentities($request->input('jobTitle'), ENT_QUOTES);;
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Job Title must not be empty!")));
					}
				}

				if ($request->has('companyName')) {
					if (!empty($request->input('companyName'))) {
						$newUser['company'] = htmlentities($request->input('companyName'), ENT_QUOTES);;
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Company Name must not be empty!")));
					}
				}

				if ($request->has('companyType')) {
					if (!empty($request->input('companyType'))) {
						$newUser['companytype'] = $request->input('companyType');
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Select company type!")));
					}
				}

				if ($request->has('location')) {
					if (!empty($request->input('location'))) {
						$location = htmlentities($request->input('location'), ENT_QUOTES);
						$location = explode(",", $location);
						$newUser['city'] = 0;
						$newUser['state'] = 0;
						$newUser['country'] = 0;

						if (isset($location[2])) {

							$dbresult1 = DB::table('tbl_country')
								->select('id')
								->where('country', trim($location[2]))
								->orWhere('std_code', $isdCode)
								->first();

							if (count($dbresult1) > 0) {
								$newUser['country'] = $dbresult1['id'];
							}
						}

						if (isset($location[1])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('state_id')
								->where('state_name', trim($location[1]))
								->Where('country_id', $newUser['country'])
								->first();

							if (count($dbresult1) > 0) {
								$newUser['state'] = $dbresult1['state_id'];
							}
						}

						if (isset($location[0])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('city_id')
								->where('state_name', trim($location[1]))
								->Where('city_name', trim($location[0]))
								->first();

							if (count($dbresult1) > 0) {
								$newUser['city'] = $dbresult1['city_id'];
							}
						}
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Please select location!")));
					}
				}

				if ($request->has('address')) {
					if (!empty($request->input('address'))) {
						$newUser['address'] = $request->input('address');
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "Address must not be empty!")));
					}
				}
				$password = '123456';
				if ($request->has('password')) {
					if (!empty($request->input('password'))) {
						$password = $request->input('password');
					} elseif (strlen($request->input('password')) < 6) {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "password must be greater then 5 characters!")));
					} else {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "password must not be empty!")));
					}
				}

				$type = 'new';

				$newUser['password'] = $password;
				$newUser['ol_be'] = 'MOB APP OTP';
				$newUser['main_source'] = $section . ' APP';
				$newUser['source_from'] = 'New APP';
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = 'CAMP19';
				$newUser['lead_type'] = 'A1';

				if ($request->has('promotionalMails') && $request->input('promotionalMails') == 'Y') {
					$newUser['email_category'] = '22';
				}

				$memid = DB::table('tbl_members')->insertGetId($newUser);
			} else { //existing user
				$memid = $dbresult['id'];
				$type = 'old';


				foreach ($request->all() as $key => $subvalue) {
					$comments = $comments . " $key => " . $subvalue . " <br /> ";
				}

				$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
				$comments .= " ip => " . $ipAddress . " <br /> ";
			}
			$more_memids = '';
			$chiledIds = array();
			if ($request->has('moreLicenses')) {

				$licensesCount = $request->input('licensesCount');
				foreach ($request->input('moreLicenses') as $license) {
					$email =  htmlentities($license['email'], ENT_QUOTES);
					if (!empty(trim($email))) {
						$name = htmlentities($license['name'], ENT_QUOTES);
						$mobileNo = htmlentities($license['mobileNo'], ENT_QUOTES);
						//
						$dbresult0 = DB::table($_ENV['USER_TABLE'])
							->select('id')
							->where(function ($q) use ($email) {
								$q->where('email', $email)
									->orWhere('addtnl_email', $email)
									->orWhere('username', $email);
							})
							->orWhere(function ($q) use ($mobileNo) {
								$q->where('phoneno', $mobileNo)
									->orWhere('alternate_mob_no', $mobileNo)
									->orWhere('username', $mobileNo);
							})
							->first();
						//dd(DB::getQueryLog());

						if (count($dbresult0) == 0) { ///invalid or new user 
							//$code = 2100;
							//$message = "invalid user.";
							$_type = 'new';
							$newUser['username'] = $email;
							$newUser['email'] = $email;
							$newUser['phoneno'] = $mobileNo;
							$newUser['isd_code'] = $isdCode;
							$newUser['password'] = '123456';
							$newUser['ol_be'] = 'MOB APP OTP';
							$newUser['main_source'] = 'SteelMint APP';
							$newUser['source_from'] = 'New APP';
							$newUser['ipaddress'] = $ipAddress;
							$newUser['date'] = $GLOBALS['currDateTime'];
							$newUser['primary_source'] = 'CAMP19';
							$newUser['lead_type'] = 'A1';
							$newUser['parentMemID'] = $memid;

							$new_memid = DB::table('tbl_members')->insertGetId($newUser);
							if ($more_memids)
								$more_memids .= ",";
							$more_memids .= $new_memid;
						} else {
							$new_memid = $dbresult0['id'];
							$_type = 'old';
							if ($more_memids)
								$more_memids .= ",";
							$more_memids .= $new_memid;
						}

						$chiledIds[$new_memid] = $_type;
					}
				}
				$comments .= " Register For => " . $more_memids . " <br /> ";
			}
			///print_r($chiledIds);
			DB::table($_ENV['COMMENTS_TABLE'])->insert([
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => $comments . "<br><br>Google Location : " . $location,
				'created_by' => 'self',
				'comments_for' => $resourceType
			]);

			DB::table('tbl_campaign_history')->insert([
				'memid' => $memid,
				'created_on' => $GLOBALS['currDateTime'],
				'refral_url' => '',
				'camp_code' => 'CAMP19',
				'ip' => $ipAddress,
				'source' => $resourceType
			]);


			$dbresult2 = DB::table('tbl_packages')
				->select('*')
				->where('id', $packageID)
				->get();

			if (count($dbresult2) > 0) {
				$tabType =  $dbresult2[0]['tabType'];
				$packageName =  $dbresult2[0]['packageName'];
				$periodName =  $dbresult2[0]['period_name'];
				$totalAmountWoGST =  $dbresult2[0]['totalAmount_Wo_GST'];
				$totalAmountWithGST =  $dbresult2[0]['totalAmount_With_GST'];
				$discountPercentage =  $dbresult2[0]['discount_percentage'];
				$gst_Rate =  $dbresult2[0]['gst_Rate'];
				$gst_Amt =  $dbresult2[0]['gst_Amt'];
				$billed_text =  $dbresult2[0]['billed_text'];
				$amountPerMonth =  $dbresult2[0]['amountPerMonth'];
				$scratch_value =  $dbresult2[0]['scratch_value'];
				$currencyCode =  $dbresult2[0]['currency_code'];

				$packageGroupID =  $dbresult2[0]['group_id'];
				$packageSubGroupId =  $dbresult2[0]['sub_group_id'];
				$packageOrder =  $dbresult2[0]['package_order'];
			} else {
				$tabType = $request->input('tabType');
				$currencyCode = $request->input('currencyCode');
				$packageName = $request->input('packageName');
				$periodName = $request->input('periodName'); //12 months
				$totalAmountWoGST = $request->input('totalAmountWoGST'); //12 months
				$totalAmountWithGST = $request->input('totalAmountWithGST'); //12 months
				$discountPercentage = $request->input('discountPercentage'); //12 months
				$amountPerMonth = $request->input('amountPerMonth'); //12 months
				$scratchValue = $request->input('scratchValue'); //12 months

				$gst_Rate = $request->input('gstRate'); //12 months
				$gst_Amt = $request->input('gstAmt'); //12 months
				$billed_text = $request->input('billedtext'); //12 months

				//$licensesCount
			}


			require_once("/home/steelmin/public_html/hf.php");

			$arr = array();

			$lead_type = 'A1';
			$mood = '';
			$fudate = '';
			if ($type == 'old') {
				//$lead_type = getLastLeadType($memid, $service_type=$f_product);
				$leadtypeArr = getLastLeadType($memid, $service_type = $f_product, $dflag = 'true');
				if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
					$lead_type = $leadtypeArr['lead_type'];
				if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
					$mood = $leadtypeArr['mood'];
				if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
					$fudate = $leadtypeArr['fudate'];

				if ($lead_type == 'A5' || $lead_type == 'B5')
					$lead_type = 'A11';
			}

			$rm_arr = getRMForRoutingProcess($memid, $company_name = strtolower($section), $lead_type);
			//print_R($rm_arr);
			/* $start_date= $GLOBALS['currDate'];
			$end_date=date("Y-m-d",strtotime("$start_date +$periodName months")); */

			$f_tenure = strtolower($section) == "steelmint" ? 'One Year' : $periodName . ' months';
			//$price = $dtls[23] * $_tax;

			$activePackages = DB::table('tbl_reg_logs')
				->select('selected_products as packageID', 'tbl_reg_logs.enddate', 'tbl_packages.group_id', 'tbl_packages.sub_group_id', 'tbl_packages.package_order')
				->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
				->where('tbl_reg_logs.memid', '=', $memid)
				->where('tbl_reg_logs.status', '=', 'Active')
				->orderBy('selected_products', 'desc')
				->first();
			if (count($activePackages) > 0) {
				$activePackageID = (int)$activePackages['packageID'];
				$activePackageGroupId = (int)$activePackages['group_id'];
				$activePackageSubGroupId = (int)$activePackages['sub_group_id'];
				$activePackageOrder = (int)$activePackages['package_order'];

				if ($packageGroupID < $activePackageGroupId)
					$servType = 'Downgrade';
				elseif ($packageGroupID == $activePackageGroupId) {
					if ($packageSubGroupId < $activePackageSubGroupId)
						$servType = 'Downgrade';
					elseif ($packageOrder < $activePackageOrder)
						$servType = 'Downgrade';
					else
						$servType = 'Renew';
				} else
					$servType = 'Upgrade';
			}

			$start_date = $GLOBALS['currDate'];
			if ($servType == 'Downgrade' || $servType == 'Renew') {
				//$start_date= $activePackages['enddate'];				
				$start_date = date("Y-m-d", strtotime($activePackages['enddate'] . " +1 day"));
			} elseif ($servType == 'Upgrade') { //currDate when to inactive current log
				$start_date = $GLOBALS['currDate'];
			}

			$end_date = date("Y-m-d", strtotime("$start_date +$periodName months"));

			$tbl_reg_logs = array(
				'memid' => $memid,
				'startdate' => $start_date,
				'enddate' => $end_date,
				'f_time' => $GLOBALS['currTime'],
				'f_product' => $f_product,
				'f_tenure' => $f_tenure, //'One Year',
				'status' => 'Pending',
				'selected_products' => $packageID,
				'comments' => $resourceType,
				'amtPaid' => $totalAmountWithGST,
				'amountWOTax' => $totalAmountWoGST,
				'created_on' => $GLOBALS['currDateTime'],
				'lead_type' => $lead_type,
				'fudate' => $fudate,
				'rm' => $rm_arr['rm_id'],
				'subrm' => $rm_arr['subrm_id'],
				'mood' => $mood,
				'pipeline_status' => 'New',
				'routing_status' => $lead_type,
				'first_log_id' => $rm_arr['first_log_id']
			);
			//print_r($tbl_reg_logs);

			/* $r = create_logs_from_array_of_array($arr);
			$_log_id = $r['tbl_reg_logs']; */
			try {
				$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
			} catch (QueryException $e) {
				dd($e);
			}

			if (!empty($_log_id) && $rm_arr['first_log_id'] == '') {
				//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
				//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
				$data['first_log_id'] = $_log_id;
				DB::table('tbl_reg_logs')
					->where('id', $_log_id)
					->update($data);
			}
			//start packeges for child rows
			foreach ($chiledIds as $cMemid => $_type) {
				$lead_type = 'A1';
				$mood = '';
				$fudate = '';
				if ($_type == 'old') {
					//$lead_type = getLastLeadType($memid, $service_type=$f_product);
					$leadtypeArr = getLastLeadType($cMemid, $service_type = $f_product, $dflag = 'true');
					if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
						$lead_type = $leadtypeArr['lead_type'];
					if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
						$mood = $leadtypeArr['mood'];
					if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
						$fudate = $leadtypeArr['fudate'];

					if ($lead_type == 'A5' || $lead_type == 'B5')
						$lead_type = 'A11';
				}

				$rm_arr = getRMForRoutingProcess($cMemid, $company_name = strtolower($section), $lead_type);

				$tbl_reg_logs = array(
					'memid' => $cMemid,
					'parent_id' => $_log_id,
					'startdate' => $start_date,
					'enddate' => $end_date,
					'f_time' => $GLOBALS['currTime'],
					'f_product' => $f_product,
					'f_tenure' => $f_tenure,
					'status' => 'Pending',
					'selected_products' => $packageID,
					'comments' => $resourceType,
					'amtPaid' => $totalAmountWithGST,
					'amountWOTax' => $totalAmountWoGST,
					'created_on' => $GLOBALS['currDateTime'],
					'lead_type' => $lead_type,
					'fudate' => $fudate,
					'rm' => $rm_arr['rm_id'],
					'subrm' => $rm_arr['subrm_id'],
					'mood' => $mood,
					'pipeline_status' => 'New',
					'routing_status' => $lead_type,
					'first_log_id' => $rm_arr['first_log_id']
				);
				//$r = create_logs_from_array_of_array($arr);
				//$_log_id = $r['tbl_reg_logs'];
				$c_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
				if (!empty($c_log_id) && $rm_arr['first_log_id'] == '') {
					//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$c_log_id;
					//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
					$data['first_log_id'] = $c_log_id;
					DB::table('tbl_reg_logs')
						->where('id', $c_log_id)
						->update($data);
				}
			} ///end

			DB::table($_ENV['COMMENTS_TABLE'])->insert([
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => "Request Service Type : " . $servType,
				'created_by' => 'self',
				'comments_for' => $resourceType
			]);
		} else {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "please give Email and Mobile no!")));
		}

		$userMessage = '';
		//if($packageName=='Price Only'){//send mail to RM and Show RM contact deatils to user
		if ($tabType == 'productWise') { //send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM("Product Wise", $memid);
			$paymentURL = '';
			$paymentType = '';
		} elseif ($packageName == 'Free Trial') { //send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM("Free Trial", $memid);
			$paymentURL = '';
			$paymentType = '';
		} elseif ($packageName == 'Platinum+' || $packageName == 'Platinum' || $packageName == 'Request a Demo') { //send mail to RM and Show RM contact deatils to user
			//$userMessage =  \ApiQuery::sendRequestMailToRM("Platinum+",$memid);
			$userMessage =  \ApiQuery::sendRequestMailToRM($packageName, $memid);
			$paymentURL = '';
			$paymentType = '';
		} else {
			//$paymentURL='https://www.steelmint.com/pay/newCheckOut_new.php';
			//$paymentType='sdk';
			$paymentType = 'web';
			$paymentURL = 'https://www.steelmint.com/pay/newCheckOut_new.php?reglogs_id=' . $_log_id . '&uid=' . $memid . '&pymtSrc=website&productPurchased=' . $packageName . '&amt=' . $totalAmountWithGST . '&pckg_incl_sms=0';
		}

		if ($resourceType == 'web') {

			$result = array(
				"paymentType" => "web", //sdk/web
				"paymentURL" => $paymentURL, //"https://www.steelmint.com/pay/newCheckOut_new.php",
				"message" => $userMessage, //if no payment neended
				"packageName" => $packageName,
				"lastLogId" => $_log_id,
				"totalAmount" => $totalAmountWoGST,
				"amountPayable" => $totalAmountWithGST,
				"gstAmt" => $gst_Amt,
				"gstRate" => $gst_Rate,
				"billedText" => $billed_text,
				///"tax"=>900,
				"discount" => round(($totalAmountWoGST * $discountPercentage) / 100, 2),
				"discountPercentage" => $discountPercentage,
				"currency" => $currencyCode
			);
			$code = 1001;
			$message = "Successfully Registered";
		} else {
			$deviceId = $request->input('deviceID');
			if ($request->has('deviceID') && $request->input('deviceID') != '') {
				$fcmToken = $request->input('fcmToken');
				$userDetails = $request->input('userDetails');
				$packageDetails = $request->input('packageDetails');

				$result = array(
					"paymentType" => $paymentType,
					"paymentURL" => $paymentURL,
					"message" => $userMessage, //if no payment neended
					"packageName" => $packageName,
					"lastLogId" => $_log_id,
					"totalAmount" => $totalAmountWoGST,
					"amountPayable" => $totalAmountWithGST,
					"gstAmt" => $gst_Amt,
					"gstRate" => $gst_Rate,
					"billedText" => $billed_text,
					///"tax"=>900,
					"discount" => round(($totalAmountWoGST * $discountPercentage) / 100, 2),
					"discountPercentage" => $discountPercentage,
					"currency" => $currencyCode
				);
				$code = 1001;
				$message = "Successfully Registered";
			} else {
				$code = 2100;
				$message = "Access token is invalid or has expired.";
			}
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function sendOTP(Request $request)
	{
		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$result = array();
		$mobileNumber = $request->input('mobileNumber');
		$deviceID = 'web';
		if ($request->has('deviceID') && $request->has('deviceID') != '')
			$deviceID = $request->input('deviceID');
		$OTP = '';
		$isdCode = '';
		if ($request->has('mobileNumber') && $request->input('mobileNumber') != '') {
			$isdCode = urlencode($request->input('isdCode')); //price/insights/tender	
			if ($request->has('countryCode'))
				$isdCode = urlencode($request->input('countryCode'));
			$mobileNumber = $request->input('mobileNumber'); //price/insights/tender	
			$ipAddress = $_SERVER['REMOTE_ADDR'];
			if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
				$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
			}

			//chekc if IP, phone number/email are blacklisted or not. if yes then return teh user from here
			$logs = DB::table('tbl_blacklisted_ips')
				->select("id")
				->where('f_ip', '=', $ipAddress)
				->orWhere('f_username', '=', $mobileNumber)
				->get();

			if (count($logs) > 0) {
				$code = 2001;
				$message = "IP / phone number/ email is blacklisted due to rate limit.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
			}
			//IP, phone number/email are NOT blacklisted



			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
				->select('id')
				->where(function ($q) use ($mobileNumber) {
					$q->where('email', $mobileNumber)
						->orWhere('addtnl_email', $mobileNumber)
						->orWhere('phoneno', $mobileNumber)
						->orWhere('alternate_mob_no', $mobileNumber)
						->orWhere('username', $mobileNumber);
				})
				->get();
			//dd(DB::getQueryLog());
			if (count($dbresult) == 0) { ///invalid or new user 
				//$code = 2100;
				//$message = "invalid user.";

				if ($request->has('source') && (strtolower($request->input('source')) == 'loginpage' || strtolower($request->input('source')) == 'forgotpassword')) {
					$code = 2001;
					$message = "User Not Registered. Please sign-up to login";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}

				$type = 'new';
				$newUser['username'] = $mobileNumber;
				$newUser['phoneno'] = $mobileNumber;
				$newUser['isd_code'] = $isdCode;
				$newUser['password'] = '123456';
				$newUser['ol_be'] = 'MOB APP OTP';
				$newUser['main_source'] = 'SteelMint APP';
				$newUser['source_from'] = 'New APP';
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = 'CAMP19';
				$newUser['lead_type'] = 'A1';

				$memid = DB::table('tbl_members')->insertGetId($newUser);
			} else {
				$memid = $dbresult[0]['id'];
				$type = 'old';
			}

			///echo $type;
			//require_once("/home/steelmin/public_html/inc/config1.php");
			require_once("/home/steelmin/public_html/hf.php");

			$phnno = $mobileNumber;
			$dbresult = DB::table('tbl_loggin_by_otp')
				->select('OTP')
				//->where('emailOrPhone' , $phnno)
				->where('memid', $memid)
				->where('deviceID', $deviceID)
				->where('status', 1)
				->get();

			if (count($dbresult) > 0) {
				$OTP = $dbresult[0]['OTP'];
			} else {
				$OTP = rand(1000, 9999);


				//DB::enableQueryLog(); 
				DB::table('tbl_loggin_by_otp')->insert([
					'ip' => $ipAddress,
					'memid' => $memid,
					'isdCode' => $isdCode,
					'emailOrPhone' => $phnno,
					'otp' => $OTP,
					'deviceID' => $deviceID,
					'created_on' => $GLOBALS['currDateTime']
				]);
				//dd(DB::getQueryLog());
			}

			$result['userType'] = $type;
			//$result['OTP']=(int)$OTP;
			$result['memid'] = $memid;
			$msg = 'OTP is ' . $OTP . ' for SteelMint Verification. Valid till next 2 hrs only. Dont share OTP for security reasons';
			/*
			if($resourceType=='app')
				//include_once("/home/steelmin/public_html/hf.php");
				sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
			*/
			//if($isdCode!=''){
			if (strpos($phnno, '@') === false) {
				$phnno = ltrim($phnno, '0');
				if (strpos($isdCode, "91") !== false)
					sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
				else
					sendSMSTo($msg, $isdCode . $phnno);
				$aa = 'sendSMS';
			} else {
				$aa = 'sendSMMail';
				include_once("/home/steelmin/public_html/mf.php");
				sendSMMail($msg, $email = $phnno, $name = 'SteelMint', "SteelMint: OTP Credentials", $attachment = "", $from_email = 'info@steelmint.com', $from_name = 'SteelMint', $reply_to = 'info@steelmint.com');
			}

			$code = 1001;
			$message = $aa . "OTP Sent";
		} else {
			$code = 2100;
			$message = "invalid request.";
		}

		$result['OTP'] = $OTP;
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function verifyOTP(Request $request)
	{
		$result = array();
		$resultData = array();
		$deviceID = 'web';
		if ($request->has('deviceID') && $request->has('deviceID') != '')
			$deviceID = $request->input('deviceID');
		if (($request->has('deviceID') && $request->input('deviceID') != '') || $request->has('resourceType')) {
			$memid = $request->input('memid'); //price/insights/tender	
			$isdCode = $request->input('isdCode');
			$mobileNumber = $request->input('mobileNumber');
			$OTP = $request->input('OTP');


			//chekc if IP, phone number/email are blacklisted or not. if yes then return teh user from here
			$logs = DB::table('tbl_blacklisted_ips')
				->select("id")
				->where('f_ip', '=', $_SERVER['REMOTE_ADDR'])
				->orWhere('f_username', '=', $mobileNumber)
				->get();

			if (count($logs) > 0) {
				$code = 2001;
				$message = "IP / phone number/ email is blacklisted due to rate limit.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}
			//IP, phone number/email are NOT blacklisted



			$result = DB::table('tbl_loggin_by_otp')
				->select('id')
				->where('emailOrPhone', $mobileNumber)
				->where('otp', $OTP)
				//->where('deviceID' ,$deviceID)
				->where('status', 1)
				//->where('memid' ,$memid)
				->get();
			if (count($result) == 0) {
				$code = 2002;
				$message = "invalid OTP.";

				$ipAddress = $_SERVER['REMOTE_ADDR'];
				//make an entry in the table tbl_login_attempts that OTP failed
				$dat = array(
					"f_username" => $mobileNumber,
					"f_status" => 'F',
					"f_source" => $deviceID . ' loginWithOTP',
					"f_ip" => $ipAddress,
					"f_useragent" => $request->header('User-Agent')
				);
				DB::table('tbl_login_attempts')->insert($dat);
				//DB::enableQueryLog();
				//blacklist the IP if its the 3rd attempt of invalid OTP
				$logs = DB::table('tbl_login_attempts')
					->select("f_status")
					->where('f_ip', '=', $ipAddress)
					->where('f_username', '=', $mobileNumber)
					->orderBy('id', 'DESC')
					->limit(3)
					->get();
				//dd(DB::getQueryLog());		
				$cnt = 0;
				foreach ($logs as $r) {
					if ($r['f_status'] == 'F') {
						$cnt += 1;
					}
				}
				//echo $cnt;
				if ($cnt == 3) {
					//make an entry in the table tbl_blacklisted_ips to blacklist the IP
					//DB::enableQueryLog();        
					if ($mobileNumber != '') {
						$dat = array(
							//"id"=> NULL, 
							//"f_datetime"=>date( "Y-m-d H:i:s" ), 
							"f_username" => $mobileNumber,
							"f_reason" => 'Invalid OTP thrice',
							"f_ip" => $ipAddress
						);
						DB::table('tbl_blacklisted_ips')->insert($dat);
					}
					//dd(DB::getQueryLog());	
				}
			} else {
				if ($memid) {
					$data['is_mobile_verified'] = 1;
					$data['verified'] = 1;
					DB::table('tbl_members')
						->where('id', $memid)
						->update($data);
				}
				$code = 1001;
				$message = "Successfully verified";
				$resultData['otp'] = $OTP;
			}
		} else {
			$code = 2002;
			$message = "Access token is invalid or has expired.";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $resultData));
		//, "data"=> $result;
		//return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	}

	public function forgotPassword(Request $request)
	{
		$result = array();
		//$accessToken = $request->input('accessToken');
		$resourceType = "app";

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($request->has('email')) {
			$user = new User();

			if ($user->forgetPassword($request->input('email'), $this->appType)) {
				$code = 1001;
				$message = "Password send successfully check your email or SMS";
			} else {

				$code = 2001;
				$message = "Invalid email or phone!";
			}
			///return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));

		} else {
			$code = 2001;
			$message = "Invalid email or phone!";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function resetPassword(Request $request)
	{
		$result = array();
		$resourceType = "app";

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		if ($user_id) {
			$oldPassword = $request->input('oldPassword'); //oldPassword
			$newPassword = $request->input('newPassword');

			if ($oldPassword == '' && $resourceType == 'app') {
				$code = 2001;
				$message = "Invalid old password!";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				//return new JsonResponse(array("code" => $code, "message" => $message));
			}

			if ($newPassword == '') {
				$code = 2001;
				$message = "Invalid new password!";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				//return new JsonResponse(array("code" => $code, "message" => $message));
			}

			$result = DB::table('tbl_members')
				->select('password')
				->where('id', '=', $user_id)
				->first();

			if ($request->has('verifiedThroughOTP') && strtolower($request->input('verifiedThroughOTP')) == 'y') {
				//no need to check old password
			} else {
				if (!$result || ($result['password'] != $oldPassword && $oldPassword != '')) {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "Old password does not match!")));
					//return new JsonResponse(array("code" => 2100, "message" => "Old password does not match!"));
				}
			}

			$data['password'] = $newPassword;

			if ($data) {
				DB::table('tbl_members')
					->where('id', $user_id)
					->update($data);
			}
			$code = 1001;
			$message = "Password updated successfully";
		} else {
			$code = 2013;
			$message = "Invalid  User";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function mapGo(Request $request)
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		$result = array();
		if ($resourceType == 'web') {
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid') != '') {
			} else {
			}
		}
		//return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
		return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function mapSave(Request $request)
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$dataType = strtolower($request->input('dataType'));
		if ($resourceType == 'web') {
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid') != '') {
			} else {
			}
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}



	public function mapDownload()
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		if ($resourceType == 'web') {
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid') != '') {
			} else {
			}
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function mapSelected(Request $request)
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		if ($resourceType == 'web') {
			$code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid') != '') {
				include_once "/home/steelmin/public_html/api/storage/v2019/web/web_map_sel_post.php";
			} else {
				include_once "/home/steelmin/public_html/api/storage/v2019/web/web_map_sel_post.php";
			}
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function search(Request $request)
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		//if($resourceType=='web'){
		$code = 1001;
		$message = "Success";
		include_once "/home/steelmin/public_html/api/storage/v2019/web/web_search.php";
		//}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getSubscriptionDetails(Request $request)
	{
		$resourceType = "app";
		$user_id = 0;

		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section = '';

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		//$accessType='pre';//for visitor///
		$activePackegesIDs = array();
		if ($user_id) {
			$user = new User($user_id, $this->appType);
			$activePackeges = $user->accessiblePackagesToMemid($user_id);

			//$activePackegesIDs = $activePackeges['IDs'];
			if ($this->appType != 'CM') {
				$f_product_IN =  array('W', 'MA', 'MA_PO');
			} else {
				$f_product_IN =  array('C');
			}

			$logs = DB::table('tbl_reg_logs')
				->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
				->select("tbl_packages.*", 'tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status', 'tbl_reg_logs.autoRenewal', 'tbl_reg_logs.inv_no', 'tbl_reg_logs.f_product', 'tbl_reg_logs.selected_products', 'tbl_reg_logs.receipt_no')
				->where('tbl_reg_logs.memid', '=', $user_id)
				->whereIN('tbl_reg_logs.status', array('Active', 'Expired'))
				->whereIn('f_product', $f_product_IN)
				->where('startdate', '<=', $GLOBALS['currDate'])
				->orderBy('tbl_reg_logs.status', 'ASC')
				->orderBy('tbl_reg_logs.id', 'DESC')
				->limit(1)
				->get();
			/* commented on 27/08/2021 as requiremnt by yashwant and  pratham to show active log based on company CM/SM */
			/*$logsB = DB::table('tbl_reg_logs')
					->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
					->select("tbl_packages.*", 'tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status', 'tbl_reg_logs.autoRenewal', 'tbl_reg_logs.inv_no', 'tbl_reg_logs.f_product', 'tbl_reg_logs.selected_products', 'tbl_reg_logs.receipt_no')
					->where('tbl_reg_logs.memid' , '=' , $user_id)
					->whereIN('tbl_reg_logs.status' , array('Active'))
					->whereNOTIn('f_product', $f_product_IN)
					->orderBy('tbl_reg_logs.id' , 'DESC')
					->orderBy('tbl_reg_logs.status' , 'DESC')
					->get();
			
			foreach ($logsB as $lB)
				array_push($logs,$lB); */
			//$logs = $logsA->merge($logsB);			
			//print_R($logs);

			//$logs = $logsA->merge($logsB);

			$result = DB::table('tbl_reg_logs')
				->select('inv_no')
				->where('inv_no', '<>', '')
				->where('id', '=', $user_id)
				->where('status', '<>', 'Active')
				->whereIn('f_product', $f_product_IN)
				->first();
			$userTypeLog = 'Complete New';
			if ($result) {
				$userTypeLog = 'Not Renewed';
			}
			$result['packageDetails'] = array();
			foreach ($logs as $r) {
				///$res['IDs'][$r['id']] = $r['package_order'];
				if ($r['status'] == 'Active') {
					$str = strtotime(date('Y-m-d', strtotime($r['enddate']))) - strtotime($GLOBALS['currDate']);
					$daysLeft = floor($str / 3600 / 24) + 1;
				} else {
					$daysLeft = 0;
				}

				//$activatedBy = getCompanyFromService($r['f_product'])['com'];
				$activatedBy = "BigMint Technologies Private Limited";
				$details = array(
					"logID"    => $r['log_id'], ///show renew/upgrade
					"isActive"    => $r['status'] == 'Active' ? "y" : "n", ///show renew/upgrade					
					"daysLeft"    => $r['f_product'] == 'M' ? 0 : (int)$daysLeft,
					"outOf"        => $r['period_name'] . " " . $r['unit_of_tenure'],
					"autoRenewal" => $r['autoRenewal'],
					"packageId" => (int)$r['id'],
					"packageName" => $r['status'] == 'Active' ? ($r['f_product'] == 'M' ? $r['receipt_no'] . " Magazine" : $r['packageName']) : $userTypeLog,
					"whatYouGet" => $r['f_product'] == 'M' ? array($r['selected_products']) : explode(',', $r['whatYouGet']),
					"amountPerMonth" => (float)$r['amountPerMonth'],
					"currency" => $r['currency_code'],
					"invNo" => $r['inv_no'],
					"licenses_cnt" => $r['licenses_cnt'],
					"activatedON"    => date('d M, Y', strtotime($r['startdate'])),
					"activatedBy" => $activatedBy
				);
				//print_r($details);
				if ($r['licenses_cnt'] > 1) {

					$moreLogs = DB::table('tbl_reg_logs')
						->select(
							"tbl_reg_logs.memid",
							"tbl_members.name",
							DB::raw('(CASE WHEN send_email_to = "R" THEN email ELSE addtnl_email END) AS emailId'),
							DB::raw('(CASE WHEN send_sms_to = "R" THEN phoneno ELSE alternate_mob_no END) AS contacNo')
						)
						->leftJoin('tbl_members', 'tbl_members.id', '=', 'tbl_reg_logs.memid')
						->where('tbl_reg_logs.parent_id', '=', $r['log_id'])
						->whereIN('tbl_reg_logs.status', array('Active', 'Expired'))
						->get();

					foreach ($moreLogs as $mr) {
						$details["licensesInformation"][] = array(
							"memId" => $mr['memid'],
							"name" => $mr['name'],
							"emailId" => $mr['emailId'],
							"contacNo" => $mr['contacNo']
						);
					}
				}

				$result['packageDetails'][]  = $details;
			}




			$code = 1001;
			$message = "Success";
			//include_once "/home/steelmin/public_html/api/storage/v2019/web/subcriptionDetails.php";

			return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
		} else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}
	}

	public function getAnnouncement(Request $request)
	{
		$result = array();

		$result_set = 	DB::table('tbl_announcement')
			->select('*');
		if ($this->appType == 'CM')
			$result_set = $result_set->where('commodity', 'coal');

		$result_set = $result_set->orderBy('date_added_on', 'desc')
			////->	take(15)
			->get();

		foreach ($result_set as $res) {
			$item = array(
				'date' => date("d-M-Y", strtotime($res['date_added_on'])) . " " . $res['time'],
				'commodity' => $res['commodity'],
				'type' => $res['type'],
				'title' => $res['title'],
				'download' => $res['file_url']
			);
			$result[] = $item;
		}
		/*$result = array(
				array(
						"date"=> "18-Mar-2018",
						"comodity" => 3,
						"type" => "correction",
						"title" => "text",
						"download" => "link"
					),
				array(
						"date"=> "18-Mar-2018",
						"comodity" => 3,
						"type" => "holiday",
						"title" => "15th aug",
						"download" => "link"
					)
			);

		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));*/

		//if($resourceType=='web'){
		$code = 1001;
		$message = "Success";

		//}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getMessgeBoard(Request $request)
	{
		if ($request->has('memid'))
			$memid = strtolower($request->input('memid'));

		$results = array();
		$result = DB::select("select t.id, t.title, t.description, t.url from tbl_message_board t where t.id not in (select `itemID` from tbl_message_board_skipped_by_memid where memid={$memid}) order by t.id DESC LIMIT 0,5");

		foreach ($result as $row) {
			$results[] = $row;
		}

		$code = 1001;
		$message = "Success";

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $results));
	}

	public function skipMessage(Request $request)
	{
		if ($request->has('memid'))
			$memid = strtolower($request->input('memid'));

		if ($request->has('itemID'))
			$itemid = strtolower($request->input('itemID'));
		$dat = array("f_datetime" => date('Y-m-d H:i:s'), "memid" => $memid, "itemID" => $itemid);
		$skkip = DB::table('tbl_message_board_skipped_by_memid')->insert($dat);
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $skkip));
	}
	public function logout(Request $request)
	{
		$resourceType = "app";

		$result = array();

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		/*//added by mohan on <29-11-2021> for the purpose of update gcm divice concept*/
		$gcm_device_table = $this->appType == "CM" ? "gcm_device_cm" : "gcm_device";

		if ($resourceType == 'app') {
			if ($request->has('accessToken')) {
				$token = $request->input('accessToken');
				$user = new User();
				$auth = new authentication();
				$user_id = $auth->authToken($token, $this->appType);

				/* if ($user->userLogout($user_id)) { */
				if ($user->userLogout($user_id, $resourceType, $this->appType)) {
					/**
					 * De-register user from notification table
					 */
					$ud = date("Y-m-d H:i:s");
					DB::table($gcm_device_table)
						->where("user_id", "=", $user_id)
						->update(["user_id" => 0, 'user_token' => 'line 4412;commonController.php' . $ud]);
					/*  DB::table('gcm_device')
						->where("user_id" , "=" , $request->input('user_id'))
						->update(["user_id" => '']); */
					// return new JsonResponse(array( "status#" => "1" , "message#" => "Successfully logout") , 200);
					return new JsonResponse(array("status" => array("code" => 1001, "message" => "Successfully logout")));
				} else {
					//return new JsonResponse(array( "status#" => "1" , "message#" => "Successfully logout") , 200);
					return new JsonResponse(array("status" => array("code" => 1001, "message" => "Successfully logout")));
					// doen by tarun on 2-june-2017 as ppl were facing issue when tryiong to logout
					//return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
				}
			} else if ($request->has('username') && $request->has('password')) {
				$user = new User();
				if ($user->userLogout_user_pass($request->input('username'), $request->input('password')))
					return new JsonResponse(array("status" => array("code" => 1001, "message" => "Successfully logout")));
				else
					return new JsonResponse(array("status" => array("code" => 1001, "message" => "Unauthorized action. Please request with token")));
				//return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
			} else {

				return new JsonResponse(array("status" => array("code" => 1001, "message" => "Unauthorized action. Username/password not matched")));
				///return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Username/password not matched") , 403 ) ;
			}
		} else { //web
			if ($request->has('memid')) {
				$memid = $request->input('memid');
				//$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid); //for web user

				if ($user_id) {
					$user = new User();
					if ($user->userLogout($user_id, $resourceType)) {
						//delete a row from tb1_online_member for teh memid as we want to start his last activity record afresh 
						DB::table('tbl_loggedin_users')
							->where('mem_id', '=', $user_id)
							->delete();
						DB::table('tb1_online_member')
							->where('mem_id', '=', $user_id)
							->delete();


						// Get all cookies
						$cookies = $_COOKIE;

						// Define domains and paths
						$domains = ['.bigmint.co', 'www.bigmint.co'];
						$paths = ['/', '/prices', '/historical', '/insights']; // Add other paths if needed

						// Loop through each cookie and delete it for each domain and path
						foreach ($cookies as $cookieName => $cookieValue) {
							foreach ($domains as $domain) {
								foreach ($paths as $path) {
									// Delete the cookie for the domain and path
									//forgetCookie($cookieName, $domain, $path);
									//echo "<br />" . $cookieName;
									setcookie($cookieName, '', time() - 3600, $path, $domain, false, true);
									\Cookie::queue(\Cookie::forget($cookieName));
									\Cookie::queue(\Cookie::forget($cookieName, null, $domain));
								}
							}
						}

						// $domain = '.bigmint.co';
						// foreach ($_COOKIE as $cookieName => $cookieValue) {
						//     \Cookie::queue(\Cookie::forget($cookieName, null, $domain));
						// }						

						session()->flush();
						session()->forget('id');
						session()->forget('name');
						session()->forget('email');
						session()->forget('section_includes');
						session()->forget('authenticated');
						session()->save();

						return new JsonResponse(array("status" => array("code" => 1001, "message" => "Successfully logout")));
					} else {
						return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
					}
				} else {
					return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
				}
			} else {
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action! invalid user.")));
			}
		}
	}

	////
	public function requestDemoOrEnquiry(Request $request)
	{
		$result = array();
		$resourceType = 'web';
		if ($request->has('resourceType') && $request->has('resourceType') != '')
			$resourceType = $request->input('resourceType');

		$section = ''; //enquiry/demo
		if ($request->has('section') && $request->has('section') != '')
			$section = $request->input('section');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Invalid Section')));
			//return new JsonResponse(array("status#" => 1, "message" => "Invalid Section")); 
		}
		/*added by mohan for methodology section on 05052021*/
		if ($section == 'methodology') {
			$comments = '';
			foreach ($request->all() as $key => $subvalue) {
				$comments = $comments . " $key => " . $subvalue . " <br /> ";
			}

			require_once("/home/steelmin/public_html/inc/config1.php");
			require_once("/home/steelmin/public_html/hf.php");

			include_once("/home/steelmin/public_html/mf.php");
			//
			sendSMMail($comments, $email = 'info@steelmint.com', $name = 'SteelMint', "SteelMint: Content Partnership Enquiry", $attachment = "", $from_email = 'info@steelmint.com', $from_name = 'SteelMint', $reply_to = 'info@steelmint.com');

			$code = 1001;
			$message = "Successfully Sent";

			require_once("/home/steelmin/public_html/inc/desconfig.php");
			//, "data"=> $result;
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$email = '';
		if ($request->has('email') && $request->has('email') != '') {
			$email = $request->input('email');
		} else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Email Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Email Required")); 
		}

		$isdCode = '';
		if ($request->has('isd_code') && $request->has('isd_code') != '')
			$isdCode = $request->input('isd_code');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'ISD Code Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "ISD Code Required")); 
		}

		$mobileNumber = '';
		if ($request->has('mobileNumber') && $request->has('mobileNumber') != '')
			$mobileNumber = $request->input('mobileNumber');
		else {
			return new JsonResponse(array("status#" => array("code" => 2100, "message" => 'Phoneno Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Phoneno Required")); 
		}

		$requirement = ''; //demo
		if ($request->has('requirement') && $request->has('requirement') != '')
			$requirement = $request->input('requirement');

		$name = ''; //enquiry
		if ($request->has('name') && $request->has('name') != '')
			$name = $request->input('name');
		elseif ($section == 'enquiry') {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Name Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Name Required")); 
		}

		$enquiryOn = ''; //enquiry
		if ($request->has('enquiryOn') && $request->has('enquiryOn') != '')
			$enquiryOn = $request->input('enquiryOn');
		elseif ($section == 'enquiry') {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Intrested topic is Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Intrested topic is Required")); 
		}

		$address = ''; //enquiry
		if ($request->has('address') && $request->has('address') != '')
			$address = $request->input('address');

		$ipAddress = $_SERVER['REMOTE_ADDR'];
		//DB::enableQueryLog(); 
		$dbresult = DB::table($_ENV['USER_TABLE'])
			->select('id')
			->where(function ($q) use ($email) {
				$q->where('email', $email)
					->orWhere('addtnl_email', $email)
					->orWhere('username', $email);
			})
			->orWhere(function ($q) use ($mobileNumber) {
				$q->where('phoneno', $mobileNumber)
					->orWhere('alternate_mob_no', $mobileNumber)
					->orWhere('username', $mobileNumber);
			})
			->first();
		//dd(DB::getQueryLog());
		if ($section == 'demo')
			$sec = 'Request a demo';
		else
			$sec = 'Business Enquiry';

		//echo "<br>" . print_r($dbresult); dd();
		$campCode = $section == 'demo' ? ($resourceType == 'web' ? 'CAMP112' : 'CAMP139') : 'CAMP149';
		if (count($dbresult) == 0) { ///invalid or new user 
			//$code = 2100;
			//$message = "invalid user.";
			$expVal = explode(" ", $isdCode);
			$std_code = end($expVal);
			$isdCode = '+' . trim($std_code, '+');

			$cntry_id = 0;
			$result = DB::table('tbl_country')
				->select('id')
				->where('std_code', '=', $isdCode)
				->first();
			if (count($result) > 0) {
				$cntry_id = $result['id'];
			}


			$type = 'new';
			$newUser['name'] = htmlspecialchars($name, ENT_QUOTES);
			$newUser['username'] = $email;
			$newUser['email'] = $email;
			$newUser['phoneno'] = $mobileNumber;
			$newUser['isd_code'] = $isdCode;
			$newUser['country'] = $cntry_id;
			$newUser['password'] = '123456';
			$newUser['ol_be'] = $sec;
			$newUser['main_source'] = $resourceType . ' : ' . $sec;
			$newUser['source_from'] = $sec;
			$newUser['address'] = $address;
			$newUser['ipaddress'] = $ipAddress;
			$newUser['date'] = $GLOBALS['currDateTime'];
			$newUser['primary_source'] = $campCode;
			//$newUser['primary_source'] = $section=='demo'?'CAMP112':'CAMP139';
			//$newUser['primary_source'] = 'CAMP139';
			$newUser['lead_type'] = 'A1';

			$memid = DB::table('tbl_members')->insertGetId($newUser);
		} else {
			//$memid = $dbresult[0]['id'] ;
			$memid = $dbresult['id'];
			$type = 'old';
		}
		/* echo "<pre>";
			print_r($dbresult);
			echo "<br>" . $memid . " -- " . $type; dd(); */

		require_once("/home/steelmin/public_html/inc/config1.php");
		require_once("/home/steelmin/public_html/hf.php");
		$lead_type = 'A1';
		$mood = '';
		$fudate = '';
		if ($type == 'old') {
			//$lead_type = getLastLeadType($memid, $service_type=$f_product);
			$leadtypeArr = getLastLeadType($memid, $service_type = 'W', $dflag = 'true');
			if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
				$lead_type = $leadtypeArr['lead_type'];
			if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
				$mood = $leadtypeArr['mood'];
			if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
				$fudate = $leadtypeArr['fudate'];

			if ($lead_type == 'A5' || $lead_type == 'B5')
				$lead_type = 'A11';
		}

		$rm_arr = getRMForRoutingProcess($memid, $company_name = 'steelmint', $lead_type);

		$tbl_reg_logs = array(
			'memid' => $memid,
			'startdate' => $GLOBALS['currDate'],
			'enddate' => $GLOBALS['currDate'],
			'f_time' => $GLOBALS['currTime'],
			'f_product' => 'W',
			'f_tenure' => 'One Day',
			'status' => 'Pending',
			'selected_products' => $sec,
			'comments' => 'From : ' . $sec,
			'created_on' => $GLOBALS['currDateTime'],
			'lead_type' => $lead_type,
			'fudate' => $fudate,
			'rm' => $rm_arr['rm_id'],
			'subrm' => $rm_arr['subrm_id'],
			'mood' => $mood,
			'pipeline_status' => 'New',
			'routing_status' => $lead_type,
			'first_log_id' => $rm_arr['first_log_id']
		);


		try {
			$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
			updateTbltbl_updated_reg_logs($memid);

			$field_array = array();
			$field_array =  array('camp_code' => $campCode, 'memid' => $memid);
			addCampaignHistory($field_array);
		} catch (QueryException $e) {
			dd($e);
		}

		foreach ($request->all() as $key => $subvalue) {
			$comments = $comments . " $key => " . $subvalue . " <br /> ";
		}

		$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
		$comments .= " ip => " . $ipAddress . " <br /> ";

		//DB::enableQueryLog(); 
		DB::table($_ENV['COMMENTS_TABLE'])->insert([
			'memid' => $memid,
			'f_date' => $GLOBALS['currDate'],
			'f_time' => $GLOBALS['currTime'],
			'comments' => "Request Service Type : " . $comments,
			'created_by' => 'self',
			'comments_for' => $section == 'demo' ? 'Sign Up -> Request a demo' : 'Contact Us -> Business Enquiry'
		]);
		//dd(DB::getQueryLog());
		//sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
		$code = 1001;
		$message = "Successfully Sent";

		require_once("/home/steelmin/public_html/inc/desconfig.php");
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("status#" => 1, "message" => $message)); 
	}

	public function requestDemoOrEnquiry1(Request $request)
	{
		$result = array();
		$resourceType = 'web';
		if ($request->has('resourceType') && $request->has('resourceType') != '')
			$resourceType = $request->input('resourceType');

		$section = ''; //enquiry/demo
		if ($request->has('section') && $request->has('section') != '')
			$section = $request->input('section');
		else {
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Invalid Section')));  
			return new JsonResponse(array("status#" => 1, "message" => "Invalid Section"));
		}

		$email = '';
		if ($request->has('email') && $request->has('email') != '') {
			$email = $request->input('email');
		} else {
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Email Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Email Required"));
		}

		$isdCode = '';
		if ($request->has('isd_code') && $request->has('isd_code') != '')
			$isdCode = $request->input('isd_code');

		$mobileNumber = '';
		if ($request->has('mobileNumber') && $request->has('mobileNumber') != '')
			$mobileNumber = $request->input('mobileNumber');
		else {
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Phoneno Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Phoneno Required"));
		}

		$requirement = ''; //demo
		if ($request->has('requirement') && $request->has('requirement') != '')
			$requirement = $request->input('requirement');

		$name = ''; //enquiry
		if ($request->has('name') && $request->has('name') != '')
			$name = $request->input('name');
		elseif ($section == 'enquiry') {
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Name Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Name Required"));
		}

		$enquiryOn = ''; //enquiry
		if ($request->has('enquiryOn') && $request->has('enquiryOn') != '')
			$enquiryOn = $request->input('enquiryOn');
		elseif ($section == 'enquiry') {
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Intrested topic is Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Intrested topic is Required"));
		}

		$address = ''; //enquiry
		if ($request->has('address') && $request->has('address') != '')
			$address = $request->input('address');

		$ipAddress = $_SERVER['REMOTE_ADDR'];
		if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
			$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
		}
		//DB::enableQueryLog(); 
		$dbresult = DB::table($_ENV['USER_TABLE'])
			->select('id')
			->where(function ($q) use ($email) {
				$q->where('email', $email)
					->orWhere('addtnl_email', $email)
					->orWhere('username', $email);
			})
			->orWhere(function ($q) use ($mobileNumber) {
				$q->where('phoneno', $mobileNumber)
					->orWhere('alternate_mob_no', $mobileNumber)
					->orWhere('username', $mobileNumber);
			})
			->get();
		//dd(DB::getQueryLog());
		if (count($dbresult) == 0) { ///invalid or new user 
			$cntry_id = 0;
			if ($isdCode) {
				$expVal = explode(" ", $isdCode);
				$std_code = end($expVal);
				$isdCode = '+' . trim($std_code, '+');


				$result = DB::table('tbl_country')
					->select('id')
					->where('std_code', '=', $isdCode)
					->first();
				if (count($result) > 0) {
					$cntry_id = $result['id'];
				}
			}

			$type = 'new';
			$newUser['username'] = $email;
			$newUser['phoneno'] = $mobileNumber;
			$newUser['isd_code'] = $isdCode;
			$newUser['country'] = $cntry_id;
			$newUser['password'] = '123456';
			$newUser['ol_be'] = $section;
			$newUser['main_source'] = $resourceType . ' : ' . $section;
			$newUser['source_from'] = $section;
			$newUser['address'] = $address;
			$newUser['ipaddress'] = $ipAddress;
			$newUser['date'] = $GLOBALS['currDateTime'];
			$newUser['primary_source'] = $section == 'demo' ? 'CAMP112' : 'CAMP139';
			$newUser['lead_type'] = 'A1';

			$memid = DB::table('tbl_members')->insertGetId($newUser);
		} else {
			$memid = $dbresult[0]['id'];
			$type = 'old';
		}
		require_once("/home/steelmin/public_html/hf.php");
		$lead_type = 'A1';
		$mood = '';
		$fudate = '';
		if ($type == 'old') {
			//$lead_type = getLastLeadType($memid, $service_type=$f_product);
			$leadtypeArr = getLastLeadType($memid, $service_type = 'W', $dflag = 'true');
			if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
				$lead_type = $leadtypeArr['lead_type'];
			if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
				$mood = $leadtypeArr['mood'];
			if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
				$fudate = $leadtypeArr['fudate'];

			if ($lead_type == 'A5' || $lead_type == 'B5')
				$lead_type = 'A11';
		}

		$rm_arr = getRMForRoutingProcess($memid, $company_name = 'steelmint', $lead_type);

		$tbl_reg_logs = array(
			'memid' => $memid,
			'startdate' => $GLOBALS['currDate'],
			'enddate' => $GLOBALS['currDate'],
			'f_time' => $GLOBALS['currTime'],
			'f_product' => 'W',
			'f_tenure' => 'One Day',
			'status' => 'Pending',
			'selected_products' => $section,
			'comments' => 'From : ' . $section,
			'created_on' => $GLOBALS['currDateTime'],
			'lead_type' => $lead_type,
			'fudate' => $fudate,
			'rm' => $rm_arr['rm_id'],
			'subrm' => $rm_arr['subrm_id'],
			'mood' => $mood,
			'pipeline_status' => 'New',
			'routing_status' => $lead_type,
			'first_log_id' => $rm_arr['first_log_id']
		);

		//print_r($tbl_reg_logs);
		try {
			$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
			updateTbltbl_updated_reg_logs($memid);
		} catch (QueryException $e) {
			dd($e);
		}

		foreach ($request->all() as $key => $subvalue) {
			$comments = $comments . " $key => " . $subvalue . " <br /> ";
		}

		$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
		$comments .= " ip => " . $ipAddress . " <br /> ";


		DB::table($_ENV['COMMENTS_TABLE'])->insert([
			'memid' => $memid,
			'f_date' => $GLOBALS['currDate'],
			'f_time' => $GLOBALS['currTime'],
			'comments' => "Request Service Type : " . $comments,
			'created_by' => 'self',
			'comments_for' => $section
		]);

		sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
		$code = 1001;
		$message = "Successfully Sent";


		//, "data"=> $result;
		//return new JsonResponse(array("status#"=>array("code" => $code, "message" => $message)));   
		return new JsonResponse(array("status#" => 1, "message" => $message));
	}

	public function autoRenew(Request $request)
	{

		$result = array();
		$resourceType = 'app';
		if ($request->has('resourceType') && $request->has('resourceType') != '')
			$resourceType = $request->input('resourceType');

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		if ($user_id) {
			if (!$request->has('logID')) { //tbl_reg_log.id
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "invalid logID for renew!")));
			} else {
				$logID = $request->input('logID');
				$autoRenewal = $request->input('autoRenewal');
				//$table_name = 'tbl_reg_logs':'tbl_sm_events_payment_details';
				$table_name = 'tbl_reg_logs';
				DB::table($table_name)
					->where('id', '=', $logID)
					->update(['autoRenewal' => $autoRenewal, 'autoRenewal_activatedOn' => $GLOBALS['currDateTime']]);

				$code = 1001;
				$message = "Successfully Saved";
			}
		} else {
			//return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
			$code = 2100;
			$message = "Unauthorized action";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
	}

	//rework on send otp, verify otp and register process
	public function sendOTPByMemid(Request $request)
	{
		$result = array();
		$resourceType = 'app';
		if ($request->has('resourceType') && $request->has('resourceType') != '')
			$resourceType = $request->input('resourceType');

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		if ($user_id) {
			$result = DB::table('tbl_members')
				->select('email', 'phoneno', 'isd_code')
				->where('id', '=', $user_id)
				->first();

			/* if($result['phoneno']){
				$reqParam = array(
					"resourceType"=>$resourceType,
					"memid"=>$user_id,
					"isdCode"=>$result['isd_code'],
					"primary_detail"=>$result['phoneno'],
					"userType"=>'old',
				);
				
				///$res = $this->sendOTPNewConcept($reqParam);	
			}
			
			if($result['email']){
				$reqParam = array(
					"resourceType"=>$resourceType,
					"memid"=>$user_id,
					"isdCode"=>"",
					"primary_detail"=>$result['email'],
					"userType"=>'old',
				);
				
				///$res = $this->sendOTPNewConcept($reqParam);
			} */

			$ipAddress = $_SERVER['REMOTE_ADDR'];
			if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
				$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
			}
			$type = 'old';
			$OTP = rand(1000, 9999);

			//DB::enableQueryLog(); 
			if ($result['phoneno']) {
				DB::table('tbl_loggin_by_otp')->insert([
					'ip' => $ipAddress,
					'memid' => $user_id,
					'isdCode' => $result['isd_code'],
					'emailOrPhone' => $result['phoneno'],
					'otp' => $OTP,
					'deviceID' => 'web',
					'created_on' => $GLOBALS['currDateTime']
				]);
			}
			if ($result['email']) {
				DB::table('tbl_loggin_by_otp')->insert([
					'ip' => $ipAddress,
					'memid' => $user_id,
					'isdCode' => "",
					'emailOrPhone' => $result['email'],
					'otp' => $OTP,
					'deviceID' => 'web',
					'created_on' => $GLOBALS['currDateTime']
				]);
			}
			//$result = array();
			//$result['userType']=$type;
			$result['OTP'] = (int)$OTP;
			$result['memid'] = $user_id;
			$msg = 'OTP is ' . $OTP . ' for SteelMint Verification. Valid till next 2 hrs only. Do not share OTP for security reasons.';

			if ($isdCode != '') {
				$phnno = ltrim($phnno, '0');
				if (strpos($isdCode, "91") !== false)
					sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
				else
					sendSMSTo($msg, $isdCode . $phnno);
			} else {
				include_once("/home/steelmin/public_html/mf.php");
				sendSMMail($msg, $email = $phnno, $name = 'SteelMint', "SteelMint: OTP Credentials", $attachment = "", $from_email = 'info@steelmint.com', $from_name = 'SteelMint', $reply_to = 'info@steelmint.com');
			}

			$code = 1001;
			$message = "OTP Sent";

			return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
		} else {
			//return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
			$code = 2100;
			$message = "Unauthorized action";
		}
	}

	public function sendOTPNewConcept(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$result = array();

		$deviceID = 'web';
		if ($request->has('deviceID') && $request->has('deviceID') != '')
			$deviceID = $request->input('deviceID');
		$OTP = '';
		$isdCode = '';
		if ($request->has('primary_detail') && $request->input('primary_detail') != '') {
			$isdCode = urlencode($request->input('isdCode')); //price/insights/tender	
			if ($request->has('countryCode'))
				$isdCode = urlencode($request->input('countryCode'));
			$mobileNumber = $request->input('primary_detail'); //price/insights/tender	
			$ipAddress = $_SERVER['REMOTE_ADDR'];
			if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
				$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
			}

			//chekc if IP, phone number/email are blacklisted or not. if yes then return teh user from here
			$logs = DB::table('tbl_blacklisted_ips')
				->select("id")
				->where('f_ip', '=', $_SERVER['REMOTE_ADDR'])
				->orWhere('f_username', '=', $mobileNumber)
				->get();

			if (count($logs) > 0) {
				$code = 2001;
				$message = "IP / phone number/ email is blacklisted due to rate limit.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}
			//IP, phone number/email are NOT blacklisted

			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
				->select('id')
				->where(function ($q) use ($mobileNumber) {
					$q->where('email', $mobileNumber)
						->orWhere('addtnl_email', $mobileNumber)
						->orWhere('phoneno', $mobileNumber)
						->orWhere('alternate_mob_no', $mobileNumber)
						->orWhere('username', $mobileNumber);
				})
				->get();
			//dd(DB::getQueryLog());
			if (count($dbresult) == 0) { ///invalid or new user 
				if ($request->has('source') && (strtolower($request->input('source')) == 'loginpage' || strtolower($request->input('source')) == 'forgotpassword')) {
					$code = 2001;
					$message = "User Not Registered. Please sign-up to login";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}
				//$code = 2100;
				//$message = "invalid user.";
				$memid = 0;
				$type = 'new';
				/* $newUser['username'] = $mobileNumber;
				$newUser['phoneno'] = $mobileNumber;
				$newUser['isd_code'] = $isdCode;
				$newUser['password'] = '123456';
				$newUser['ol_be'] = 'MOB APP OTP';
				$newUser['main_source'] = 'SteelMint APP';
				$newUser['source_from'] = 'New APP';
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = 'CAMP19';
				$newUser['lead_type'] = 'A1';
				
				$memid = DB::table('tbl_members')->insertGetId($newUser); */
			} elseif ($request->has('memid') && $request->input('memid') > 0) {
				$memid = $request->input('memid');
				$type = $request->input('userType');
				if ($isdCode) { ///check phone
					$dbresult = DB::table($_ENV['USER_TABLE'])
						->select('id')
						->where(function ($q) use ($mobileNumber) {
							$q->where('phoneno', $mobileNumber)
								->orWhere('alternate_mob_no', $mobileNumber)
								->orWhere('username', $mobileNumber);
						})
						->first();
					$message = "this mobile no already registered!";
				} else { ///check email
					$dbresult = DB::table($_ENV['USER_TABLE'])
						->select('id')
						->where(function ($q) use ($mobileNumber) {
							$q->where('email', $mobileNumber)
								->orWhere('addtnl_email', $mobileNumber)
								->orWhere('username', $mobileNumber);
						})
						->first();
					$message = "this email already registered with us!";
				}

				if (count($dbresult) > 0 && $dbresult['id'] != $memid) {
					return new JsonResponse(array("status" => array("code" => 2002, "message" => $message)));
				}
			} else {
				$memid = $dbresult[0]['id'];
				$type = 'old';
			}

			///echo $type;
			//require_once("/home/steelmin/public_html/inc/config1.php");
			require_once("/home/steelmin/public_html/hf.php");

			$phnno = $mobileNumber;
			$dbresult = DB::table('tbl_loggin_by_otp')
				->select('OTP')
				->where('emailOrPhone', $phnno)
				->where('memid', $memid)
				->where('isdCode', $isdCode)
				->where('deviceID', $deviceID)
				->where('status', 1)
				->first();

			if (count($dbresult) > 0) {
				$OTP = $dbresult['OTP'];
			} else {
				$OTP = rand(1000, 9999);

				//DB::enableQueryLog(); 
				DB::table('tbl_loggin_by_otp')->insert([
					'ip' => $ipAddress,
					'memid' => $memid,
					'isdCode' => $isdCode,
					'emailOrPhone' => $phnno,
					'otp' => $OTP,
					'deviceID' => $deviceID,
					'created_on' => $GLOBALS['currDateTime']
				]);
				//dd(DB::getQueryLog());
			}

			$result['userType'] = $type;
			//$result['OTP']=(int)$OTP;
			$result['memid'] = $memid;
			if ($this->appType == 'CM') {
				$companyName = 'CoalMint';
				$senderid = 'CoalMt';
				$from_email = 'info@coalmint.com';
				$from_name = 'CoalMint';
			} else {
				$companyName = 'SteelMint';
				$senderid = 'MINTTT';
				$from_email = 'info@steelmint.com';
				$from_name = 'SteelMint';
			}

			$msg = 'OTP is ' . $OTP . ' for ' . $companyName . ' login. Valid till next 2 hrs only. Do not share OTP for security reasons.';

			if ($isdCode != '') {
				$phnno = ltrim($phnno, '0');
				if (strpos($isdCode, "91") !== false)
					sendBULKsms($phnno, $msg, '', $senderid);
				else
					sendSMSTo($msg, $isdCode . $phnno);
			} else {
				include_once("/home/steelmin/public_html/mf.php");
				sendSMMail($msg, $email = $phnno, $name = $companyName, $companyName . ": OTP Credentials", $attachment = "", $from_email, $from_name, $reply_to = $from_email);
			}

			$code = 1001;
			$message = "OTP Sent";
		} else {
			$code = 2002;
			$message = "invalid request.";
		}

		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function verifyOTPNewConcept(Request $request)
	{
		$result = array();
		$deviceID = 'web';
		$OTP = '';
		$isdCode = '';
		$resourceType = 'app';
		if ($request->has('resourceType'))
			$resourceType = $request->input('resourceType');

		$section = 'steelmint';
		if ($request->has('section'))
			$section = strtolower($request->input('section'));
		elseif ($this->appType == 'CM')
			$section = 'coalmint';

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = ($request->input('deviceType'));

		$ipAddress = $_SERVER['REMOTE_ADDR'];
		if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
			$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
		}

		$screenName = '';
		if ($request->has('screenName'))
			$screenName = ($request->input('screenName'));

		if ($request->has('deviceID') && $request->has('deviceID') != '')
			$deviceID = $request->input('deviceID');
		if ($request->has('OTP') && $request->input('OTP') != '') {
			if (($request->has('deviceID') && $request->input('deviceID') != '') || $request->has('resourceType')) {
				$memid = 0;
				if ($request->has('memid'))
					$memid = $request->input('memid'); //price/insights/tender	

				$isdCode = urlencode($request->input('isdCode')); //price/insights/tender	
				if ($request->has('countryCode'))
					$isdCode = urlencode($request->input('countryCode'));
				$mobileNumber = $request->input('primary_detail');
				$OTP = $request->input('OTP');
				$userType = $request->input('userType'); //new/old
				//DB::enableQueryLog();
				$result1 = array();
				if ($OTP != 'skip' && $OTP != 100) {
					$result1 = DB::table('tbl_loggin_by_otp')
						->select('id')
						->where('emailOrPhone', $mobileNumber)
						->where('otp', $OTP)
						->where('deviceID', $deviceID)
						->where('isdCode', $isdCode)
						->where('status', 1)
						//->where('memid' ,$memid)
						->get();
					//dd(DB::getQueryLog());
				}

				if (count($result1) == 0 && $OTP != 'skip' && $OTP != 100) {
					$code = 2002;
					$message = "Invalid OTP.";
				} else {
					if ($memid) { //old user
						if ($userType == 'old' && $memid > 0) {
							//DB::enableQueryLog(); 
							/* $dbresult = DB::table($_ENV['USER_TABLE'])
								->select('id')								
								->where(function($q) use ($mobileNumber) {
											$q->where('email' ,$mobileNumber)
											->orWhere('addtnl_email' ,$mobileNumber)
											->orWhere('username' ,$mobileNumber);
										})
								->orWhere(function($q) use ($mobileNumber) {
											$q->where('phoneno' ,$mobileNumber)
											->orWhere('alternate_mob_no' ,$mobileNumber)
											->orWhere('username' ,$mobileNumber);
										})
								->first(); */
							//
							///print_r($dbresult);
							if ($isdCode) { ///check phone
								$dbresult = DB::table($_ENV['USER_TABLE'])
									->select('id')
									->where(function ($q) use ($mobileNumber) {
										$q->where('phoneno', $mobileNumber)
											->orWhere('alternate_mob_no', $mobileNumber)
											->orWhere('username', $mobileNumber);
									})
									->first();
							} else { ///check email
								$dbresult = DB::table($_ENV['USER_TABLE'])
									->select('id')
									->where(function ($q) use ($mobileNumber) {
										$q->where('email', $mobileNumber)
											->orWhere('addtnl_email', $mobileNumber)
											->orWhere('username', $mobileNumber);
									})
									->first();
							}

							if (count($dbresult) > 0 && $dbresult['id'] != $memid) {
								return new JsonResponse(array("status" => array("code" => 2001, "message" => "duplicate record found!")));
							}
						}

						if ($isdCode) {
							$newUser['isd_code'] = urldecode($isdCode);
							$newUser['phoneno'] = $mobileNumber;
							if ($OTP != 'skip' && $OTP != 100)
								$newUser['is_mobile_verified'] = 1;

							$dbresult1 = DB::table('tbl_country')
								->select('id')
								->where('std_code', urldecode($isdCode))
								->first();

							if (count($dbresult1) > 0) {
								$newUser['country'] = $dbresult1['id'];
							}
						} elseif ($mobileNumber != '' && strpos($mobileNumber, "@") !== false) {
							$newUser['email'] = $mobileNumber;
							$newUser['verified'] = 1;
						}
						//$userType=='new' &&
						if ($memid > 0) {
							DB::table($_ENV['USER_TABLE'])
								->where('id', $memid)
								->update($newUser);
						}

						if ($section == 'events') {
							$primary_source = $resourceType == 'app' ? 'CAMP24' : 'CAMP13';
							$service_type = 'Events';
						} elseif ($section == 'steelmint') {

							//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
							if ($screenName == 'Subscribe_CTA') {
								$primary_source = 'CAMP188';
							} elseif ($deviceType != '' && 'Registration_Page' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP162' : 'CAMP163';
							} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP160' : 'CAMP161';
							} else
								$primary_source = $resourceType == 'app' ? 'CAMP19' : 'CAMP165';

							$service_type = $resourceType == 'app' ? 'MA' : 'W';
							if ($screenName == 'Subscribe_CTA') {
								$service_type = 'MA';
							}
						} elseif ($section == 'coalmint' || $this->appType == 'CM') {

							//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
							if ($deviceType != '' && 'Registration_Page' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP185' : 'CAMP186';
							} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP183' : 'CAMP184';
							} else
								$primary_source = $resourceType == 'app' ? 'CAMP182' : 'CAMP187';

							$service_type = $resourceType == 'app' ? 'MA' : 'W';
						}
					} else {
						///check the user again for safer side
						//DB::enableQueryLog(); 
						$dbresult = DB::table($_ENV['USER_TABLE'])
							->select('id')
							->where(function ($q) use ($mobileNumber) {
								$q->where('email', $mobileNumber)
									->orWhere('addtnl_email', $mobileNumber)
									->orWhere('username', $mobileNumber);
							})
							->orWhere(function ($q) use ($mobileNumber) {
								$q->where('phoneno', $mobileNumber)
									->orWhere('alternate_mob_no', $mobileNumber)
									->orWhere('username', $mobileNumber);
							})
							->first();
						//dd(DB::getQueryLog());
						//print_r($dbresult);
						if (count($dbresult) > 0 && $dbresult['id'] != $memid) {
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "duplicate record found!")));
						}
						///

						$newUser['username'] = $mobileNumber;
						if ($isdCode) {
							$newUser['phoneno'] = $mobileNumber;
							$newUser['isd_code'] = urldecode($isdCode);
							if ($OTP != 'skip' && $OTP != 100)
								$newUser['is_mobile_verified'] = 1;

							$dbresult1 = DB::table('tbl_country')
								->select('id')
								->where('std_code', urldecode($isdCode))
								->first();

							if (count($dbresult1) > 0) {
								$newUser['country'] = $dbresult1['id'];
							}
						} elseif ($mobileNumber != '' && strpos($mobileNumber, "@") !== false) {
							include_once('/home/steelmin/public_html/hf.php');
							$t_cn = ipTocntry($ipAddress);
							if ($t_cn == 'INDIA')
								$newUser['country'] = 113;
							$newUser['email'] = $mobileNumber;
							$newUser['verified'] = 1;
						}



						if ($section == 'events') {
							$ol_be = "EVT " . $resourceType;
							$primary_source = $resourceType == 'app' ? 'CAMP24' : 'CAMP13';
							$service_type = 'Events';
						} elseif ($section == 'steelmint') {
							$ol_be = "SM " . $resourceType;
							//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
							if ($screenName == 'Subscribe_CTA') {
								$primary_source = 'CAMP188';
							} elseif ($deviceType != '' && 'Registration_Page' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP162' : 'CAMP163';
							} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP160' : 'CAMP161';
							} else
								$primary_source = $resourceType == 'app' ? 'CAMP19' : 'CAMP165';

							$service_type = $resourceType == 'app' ? 'MA' : 'W';
							if ($screenName == 'Subscribe_CTA') {
								$service_type = 'MA';
							}
						} elseif ($section == 'coalmint' || $this->appType == 'CM') {
							$ol_be = "CM " . $resourceType;
							//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
							if ($deviceType != '' && 'Registration_Page' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP185' : 'CAMP186';
							} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
								$primary_source = strtolower($deviceType) == 'android' ? 'CAMP183' : 'CAMP184';
							} else
								$primary_source = $resourceType == 'app' ? 'CAMP182' : 'CAMP187';

							$service_type = $resourceType == 'app' ? 'MA' : 'W';
						}
						//$newUser['isd_code'] = $isdCode;
						$newUser['password'] = '123456';
						$newUser['ol_be'] = $ol_be;
						$newUser['main_source'] = $section . ' Registraion Page';
						$newUser['source_from'] = $resourceType == 'app' ? 'Mobile App' : 'Web';
						$newUser['ipaddress'] = $ipAddress;
						$newUser['date'] = $GLOBALS['currDateTime'];
						$newUser['primary_source'] = $primary_source;
						$newUser['lead_type'] = 'A1';

						try {
							$memid = DB::table('tbl_members')->insertGetId($newUser);
							/*			
							$msg='';
			foreach($newUser as $key=>$subvalue)
						{	
							$msg = $msg." $key => ".$subvalue." <br /> ";
						}
			
				include_once "/home/steelmin/public_html/mf.php"; 
				$res = sendSMMail($msg, $rmEmail="mohan@theitbooth.com", "", $sub_txt='test reg form APP', $invFileName='', $rmEmail="info@steelmint.com", $rmName="Registraion", $rmEmail="info@steelmint.com");
				DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $memid,
									'f_date' => $GLOBALS['currDate'],
									'f_time' => $GLOBALS['currTime'],
									'comments' => " test by mohan : ".$msg,
									'created_by' => 'self',
									'comments_for' => $section]);
			*/
							////$userMessage =  \ApiQuery::sendRequestMailToRM('regMail',$memid);
						} catch (QueryException $e) {
							dd($e);
						}
						////////visitor log id


						if ($section == 'steelmint' || $section == 'coalmint') {
							$lead_type = 'A1';
							$mood = '';
							$fudate = '';
							///if($type=='old')
							{
								//$lead_type = getLastLeadType($memid, $service_type=$f_product);
								$leadtypeArr = getLastLeadType($memid, $service_type, $dflag = 'true');
								if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
									$lead_type = $leadtypeArr['lead_type'];
								if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
									$mood = $leadtypeArr['mood'];
								if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
									$fudate = $leadtypeArr['fudate'];

								if ($lead_type == 'A5' || $lead_type == 'B5')
									$lead_type = 'A11';
							}

							$rm_arr = getRMForRoutingProcess($memid, $company_name = $section, $lead_type);

							if (empty($rm_arr)) {
								$rm_arr['rm_id'] = $section == "coalmint" ? 125 : 0;
								$mood = 0;
								$rm_arr['subrm_id'] = $section == "coalmint" ? 125 : 0;
								$rm_arr['first_log_id'] = $section == "coalmint" ? 0 : 0;
							}

							$f_product = $section == 'coalmint' ? 'C' : ($resourceType == 'app' ? 'MA' : 'W');

							$start_date = $GLOBALS['currDate'];
							$end_date = $GLOBALS['currDate'];
							$f_tenure = 'One Day';

							$selected_products = $resourceType == 'app' ? 'Mobile App' : 'Web';
							if ($request->has('packageID') && $request->has('packageID') != '') {
								$selected_products = $request->input('packageID');

								$dbresult2 = DB::table('tbl_packages')
									->select('*')
									->where('id', $selected_products)
									->get();

								if (count($dbresult2) > 0) {
									$tabType =  $dbresult2[0]['tabType'];
									$packageName =  $dbresult2[0]['packageName'];
									$periodName =  $dbresult2[0]['period_name'];

									$end_date = date("Y-m-d", strtotime("$start_date +$periodName months"));
									$f_tenure = (strtolower($section) == "steelmint" || strtolower($section) == "coalmint") ? 'One Year' : $periodName . ' months';
								}
							}

							$tbl_reg_logs = array(
								'memid' => $memid,
								'startdate' => $start_date,
								'enddate' => $end_date,
								'f_time' => $GLOBALS['currTime'],
								'f_product' => $f_product,
								'f_tenure' => $f_tenure,
								'status' => 'Pending',
								'selected_products' => $selected_products,
								'comments' => 'From : verifyOTP',
								'created_on' => $GLOBALS['currDateTime'],
								'lead_type' => $lead_type,
								'fudate' => $fudate,
								'rm' => $rm_arr['rm_id'],
								'subrm' => $rm_arr['subrm_id'],
								'mood' => $mood,
								'pipeline_status' => 'New',
								'routing_status' => $lead_type,
								'first_log_id' => $rm_arr['first_log_id'],
								'form_no' => $screenName
							);

							//print_r($tbl_reg_logs);
							try {
								$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
								////updateTbltbl_updated_reg_logs($memid);					
							} catch (QueryException $e) {
								dd($e);
							}
						} elseif ($section == 'events') {
							$tbl_reg_logs = array(
								'registering_id' => $memid,
								'datetime' => $GLOBALS['currDateTime'],
								'email' => $mobileNumber,
								'mobile' => $mobileNumber,
								'event_id' => $request->input('eventID')
							);

							//print_r($tbl_reg_logs);
							try {
								$_log_id = DB::table('tbl_sm_events_registration_logs')->insertGetId($tbl_reg_logs);
								makeEntryInTableFinalStatus($memid, $request->input('eventID'));
							} catch (QueryException $e) {
								dd($e);
							}
						}
					}
					foreach ($request->all() as $key => $subvalue) {
						$comments = $comments . " $key => " . $subvalue . " <br /> ";
					}

					$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
					$comments .= " ip => " . $ipAddress . " <br /> ";


					DB::table($_ENV['COMMENTS_TABLE'])->insert([
						'memid' => $memid,
						'f_date' => $GLOBALS['currDate'],
						'f_time' => $GLOBALS['currTime'],
						'comments' => "Request Service Type : " . $comments,
						'created_by' => 'self',
						'comments_for' => $section
					]);

					DB::table('tbl_campaign_history')->insert([
						'memid' => $memid,
						'created_on' => $GLOBALS['currDateTime'],
						'refral_url' => '',
						'camp_code' => $primary_source,
						'ip' => $ipAddress,
						'source' => $resourceType
					]);
					//////

					$code = 1001;
					$message = "Successfully verified";

					if ($userType == 'old' && $memid > 0) {
						$result = DB::table($_ENV['USER_TABLE'])
							->select('email', 'phoneno', 'isd_code', 'name', 'job_title', 'company', 'companytype', 'city', 'state', 'country', 'pin_code', DB::raw("CONCAT(city,'-',state,'-',country ) as `selectedLocation`"), 'address')
							->where('id', $memid)
							->first();
						$is_encoded = preg_match('~%[0-9A-F]{2}~i', $result['isd_code']);
						if ($is_encoded)
							$result['isd_code'] = urldecode($result['isd_code']);
					} else {
						$result = DB::table($_ENV['USER_TABLE'])
							->select('country')
							->where('id', $memid)
							->first();
					}

					$countryID = $result['country'];
					if ($countryID == 0) {
						$dbresult1 = DB::table('tbl_country')
							->select('id')
							->where('std_code', urldecode($isdCode))
							->first();

						if (count($dbresult1) > 0) {
							$countryID = $dbresult1['id'];
						}
					}

					if ($countryID == 113) {
						$dblocation = DB::table('tbl_state_city')
							->select(DB::raw("CONCAT(city_id,'-',state_id,'-', 113 ) as `city_id`"), DB::raw("CONCAT(city_name,', ',state_name ) as `city_name`"))
							->where('country_id', $countryID)
							->get();
					} else {
						$dblocation = DB::table('tbl_state_city')
							->select(DB::raw("CONCAT(city_id,'-',state_id,'-', country_id ) as `city_id`"), 'city_name')
							->where('country_id', $countryID)
							->get();
					}

					$result['memid'] = $memid;
					$result['location'] = $dblocation;

					updateTbltbl_updated_reg_logs($memid);

					//if($userType=='new'){
					if ($section != "coalmint") {
						if ($resourceType == 'app') {
							$template_name = "1st_reg_app";
							$template_param = array("https://www.steelmint.com/web_app.php?share=profile");
						} else {
							$template_name = "1st__registration";
							$template_param = array("https://www.steelmint.com/web_app.php?source=openapp");
						}
						sendWhatsAppMessage($to = $result['isd_code'] . $result['phoneno'], $template_name, $template_param);
					}
					//}
				}
			} else {
				$code = 2002;
				$message = "Access token is invalid or has expired.";
			}
		} else {
			$code = 2002;
			$message = "invalid OTP.";
		}
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function registrationProcessNewConcept(Request $request)
	{
		$result = array();
		// return $request->all();
		$resourceType = "app";
		$section = "steelmint";
		$serviceType = 'new';


		// ✅ ALWAYS resolve memid first
		//$memid = (int) $request->input('memid', 0);


		if ($request->has('serviceType'))
			$serviceType = strtolower($request->input('serviceType')); //new/ upgrade

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($request->has('section'))
			$section = strtolower($request->input('section'));
		if ($this->appType == 'CM')
			$section = 'coalmint';
		$extra_details = '';
		$screenName = '';
		if ($request->has('ScreenName')) {
			$screenName = $request->input('ScreenName');
			$extra_details = $request->input('ScreenName');
		}
		if ($screenName == 'Subscribe_CTA')
			$f_product = 'MA';
		elseif ($section == "steelmint" && $resourceType == 'web') {
			$f_product = 'W';
		} elseif ($section == "steelmint" && $resourceType == 'app') {
			$f_product = 'MA';
		} elseif ($section == "events") {
			$f_product = 'EVT';
		} elseif ($section == "coalmint") {
			$f_product = 'C';
		}





		//code by Nirmal for Industry type

		// ================= INDUSTRY DATA SAVE =================

		// 1. Get member id
		$memberId = 0;
		if ($request->has('memid')) {
			$memberId = (int) $request->input('memid');
		}

		// If memberId missing, do nothing safely
		if ($memberId > 0) {

			// 2. Read level arrays (OLD Laravel compatible)
			$level1 = [];
			$level2 = [];
			$level3 = [];

			if ($request->has('level1')) {
				$level1 = (array) $request->input('level1');
			}

			if ($request->has('level2')) {
				$level2 = (array) $request->input('level2');
			}

			if ($request->has('level3')) {
				$level3 = (array) $request->input('level3');
			}

			// 3. Merge all selected industry IDs
			$allSelected = array_unique(array_merge($level1, $level2, $level3));

			// 4. Delete old mappings (Edit-safe)
			DB::table('tbl_member_industry_types')
				->where('member_id', $memberId)
				->delete();

			// 5. Prepare insert rows
			$insertData = [];
			$currentDateTime = date('Y-m-d H:i:s');

			foreach ($allSelected as $industryId) {
				$industryId = (int) $industryId;

				if ($industryId > 0) {
					$insertData[] = [
						'member_id'        => $memberId,
						'industry_type_id' => $industryId,
						'created_by'       => $memberId,
						'created_on'       => $currentDateTime
					];
				}
			}

			// 6. Insert if data exists
			if (!empty($insertData)) {
				DB::table('tbl_member_industry_types')->insert($insertData);
			}
		}

		// ================= END INDUSTRY SAVE =================




		$marketMap = [
			'ferrous'         => (array) $request->input('ferrous_sub', []),
			'non-ferrous'     => (array) $request->input('nonferrous_sub', []),
			'scrap-recycling' => (array) $request->input('scrap_sub', []),
			'coal'            => (array) $request->input('coal_sub', []),
			'agriculture'     => (array) $request->input('agri_sub', []),
			'logistics'       => (array) $request->input('logistics_sub', []),
		];

		if (
			$request->has('ferrous_sub') ||
			$request->has('nonferrous_sub') ||
			$request->has('scrap_sub') ||
			$request->has('coal_sub') ||
			$request->has('agri_sub') ||
			$request->has('logistics_sub')
		) {
			DB::table('tbl_member_market_preferences')
				->where('member_id', $memberId)
				->delete();
		}

		$insertMarkets = [];
		$now = date('Y-m-d H:i:s');

		foreach ($marketMap as $market => $subs) {
			foreach ($subs as $sub) {
				if (!empty($sub)) {
					$insertMarkets[] = [
						'member_id'  => $memberId,
						'market'     => $market,
						'sub_market' => $sub,
						'created_on' => $now,
						'created_by' => $memberId,
					];
				}
			}
		}

		if (!empty($insertMarkets)) {
			DB::table('tbl_member_market_preferences')->insert($insertMarkets);
		}

		//end of code 


		//$extra_details = "Final Sec: ".$request->input('section').", Service Type: ".$request->input('serviceType').", resourceType:". $request->input('resourceType').", App Type:".$this->appType . ", F_pro: ".$f_product . ", Pckg ID:".$request->input('packageID')."";
		if (!$request->has('memid')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "user id missing !")));
		} else {
			$memid = $request->input('memid');
		}

		$licensesCount = 1;
		if ($section != "events") {
			if (!$request->has('packageID')) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "invalid package selection!")));
			} else {
				$packageID = $request->input('packageID');
			}
			if ($request->has('selected_market')) {
				$selected_market = $request->input('selected_market');
			} else
				$selected_market = '';
		}

		// 🔹 Ensure market & features from for loop (comma separated)
		$marketValues   = isset($request['marketValues']) ? trim($request['marketValues']) : '';
		$featuresValues = isset($request['featuresValues']) ? trim($request['featuresValues']) : '';

		// 🔹 Final fallback logic
		if (!empty($marketValues)) {
			$final_market = $marketValues;
		} else {
			$final_market = $selected_market;
		}

		if ($section == "events" && ($request->input('eventID') == 97 || $request->input('eventID') == 102)) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Sorry, Our registraion is closed.")));
		}


		if ($request->has('name')) {
			if (!empty($request->input('name'))) {
				$newUser['name'] = htmlentities($request->input('name'), ENT_QUOTES);
			} else {
				//return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Name must not be empty!")));
			}
		}
		if ($request->has('jobTitle')) {
			if (!empty($request->input('jobTitle'))) {
				$newUser['job_title'] = htmlentities($request->input('jobTitle'), ENT_QUOTES);;
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Job Title must not be empty!")));
			}
		}

		if ($request->has('companyName')) {
			if (!empty($request->input('companyName'))) {
				$newUser['company'] = htmlentities($request->input('companyName'), ENT_QUOTES);;
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Company Name must not be empty!")));
			}
		}


		if ($request->has('companyType')) {
			if (!empty($request->input('companyType'))) {
				$newUser['companytype'] = $request->input('companyType');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Select company type!")));
			}
		}

		if ($request->has('location')) {
			if (!empty($request->input('location'))) {
				$location = htmlentities($request->input('location'), ENT_QUOTES);
				$location = explode("-", $location);
				///$location = explode(",", $location);
				$newUser['city'] = $location[0];
				$newUser['state'] = $location[1];
				$newUser['country'] = $location[2];
			}
		}

		if ($request->has('address')) {
			if (!empty($request->input('address'))) {
				$newUser['address'] = $request->input('address');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Address must not be empty!")));
			}
		}

		if ($request->has('zipCode')) {
			if (!empty($request->input('zipCode'))) {
				$newUser['pin_code'] = $request->input('zipCode');
			} /* else {
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => "zip Code must not be empty!")));
			} */
		}

		////$password='123456';password
		if ($request->has('password')) {
			if (empty($request->input('password'))) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "password must not be empty!")));
			} elseif (strlen($request->input('password')) < 6) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "password must be greater then 5 characters!")));
			} else {
				$password = $request->input('password');
				$newUser['password'] = $password;
			}
		}


		$userType = '';
		if ($request->has('userType')) {
			$userType = $request->input('userType');;
		} else {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "User Type, must not be empty!")));
		}

		if ($request->has('promotionalMails') && $request->input('promotionalMails') == 'Y') {
			$email_category = $resourceType == 'app' ? '22' : '23';
			$newUser['email_category'] = DB::raw('CONCAT(email_category,",' . $email_category . '")');
		}

		$mem_newUser = array();
		if ($request->has('isd_code') && $request->has('isd_code') != '')
			$newUser['isd_code'] = $request->input('isd_code');
		elseif ($request->has('mem_isdCode') && $request->has('mem_isdCode') != '') {
			$mem_newUser['isd_code'] = $request->input('mem_isdCode');
		}

		if ($request->has('mem_phone') && $request->has('mem_phone') != '') {
			$mem_newUser['phoneno'] = $request->input('mem_phone');
			//$mem_newUser['comments'] = $request->input('mem_phone');
		}



		if ($userType == 'old' && $serviceType == 'new') { //store old details and update new
			$comments .= "<br> OLD Registraion Details of this memId is: <br /> ";
			$userArrKeys = array_keys($newUser);

			$keyStr = "'" . implode("','", $userArrKeys) . "'";

			$result = DB::table('tbl_members')
				->select('name', 'job_title', 'company', 'companytype', 'address', 'email_category', 'pin_code', 'phoneno', 'isd_code')
				->where('id', '=', $memid)
				->first();
			//DB::enableQueryLog(); dd(DB::getQueryLog());	

			foreach ($result as $key => $subvalue) {
				$comments = $comments . " $key => " . $subvalue . " <br /> ";
			}

			DB::table($_ENV['COMMENTS_TABLE'])->insert([
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => $comments,
				'created_by' => 'self',
				'comments_for' => $resourceType
			]);
		}/* else{//update new form data
			DB::table('tbl_members')
						->where('id', $memId)
						->update($newUser);
		} */

		if (!empty($newUser)) {
			DB::table('tbl_members')
				->where('id', $memid)
				->update($newUser);

			$result_chk = DB::table('tbl_members')
				->select('phoneno', 'isd_code')
				->where('id', '=', $memid)
				->first();

			if (!empty($mem_newUser)) {
				DB::table('tbl_members')
					->where('id', $memid)
					->where('phoneno', '=', '')
					->limit(1)
					->update($mem_newUser);
			}
			if (!empty($mem_newUser)) {
				if ($result_chk['phoneno'] != $mem_newUser['phoneno'] || $result_chk['isd_code'] != $mem_newUser['isd_code']) {
					$comment_by_user = ' <b> Details filled by user while registering :  </b>';
					foreach ($mem_newUser as $key => $subvalue) {
						$comment_by_user = $comment_by_user . " $key => " . $subvalue . "<br />";
					}
					$comment_by_user  =  rtrim($comment_by_user, "<br />");
					DB::table($_ENV['COMMENTS_TABLE'])->insert([
						'memid' => $memid,
						'f_date' => $GLOBALS['currDate'],
						'f_time' => $GLOBALS['currTime'],
						'comments' => $comment_by_user,
						'created_by' => 'self',
						'comments_for' => $resourceType
					]);
				}
			}
		}

		$gst_id = 0;
		if ($request->has('gstDetails') && strtoupper($request->input('gstDetails')) == 'Y') {
			if (!empty($request->input('gstNo'))) {
				$gst['gst_no'] = $request->input('gstNo');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Number must not be empty!")));
			}

			if (!empty($request->input('gstCompany'))) {
				$gst['company_name'] = $request->input('gstCompany');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Company must not be empty!")));
			}

			if (!empty($request->input('gstLocation'))) {
				//$gst['gstLocation'] = $request->input('gstLocation');
				$gstLocation = $request->input('gstLocation');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Location must not be empty!")));
			}

			if (!empty($request->input('gstAddress'))) {
				$gst['address'] = $request->input('gstAddress');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Address must not be empty!")));
			}

			$gst['memid'] = $memid;
			$gst['contact_person'] = $newUser['name'];
			$gst['email'] = $request->has('email') ? $request->input('email') : '';
			$gst['phoneno'] = $request->input('phoneno');
			$gst['default'] = 1;

			$location = htmlentities($gstLocation, ENT_QUOTES);
			$gstLocation = explode("-", str_replace(",", "-", $location));

			$gst['city'] = $gstLocation[0];
			$gst['state'] = $gstLocation[1];
			$gst['country'] = $gstLocation[2];

			$dbresult = DB::table('tbl_gst_no')
				->select('id')
				->where($gst)
				->orderBy('default', 'desc')
				->orderBy('id', 'desc')
				->first();
			if (count($dbresult) > 0) {
				$gst_id = $dbresult['id'];
			} else {

				$gst['created_on'] = date("Y-m-d H:i:s");
				$gst_id = DB::table('tbl_gst_no')->insertGetId($gst);
			}
		} elseif ($userType == 'old') {
			$dbresult = DB::table('tbl_gst_no')
				->select('id', 'country', 'state', 'city')
				->where('memid', '=', $memid)
				->orderBy('default', 'desc')
				->orderBy('id', 'desc')
				->first();

			if (count($dbresult) > 0) {
				$gst_id = $dbresult['id'];

				$gst['city'] = $dbresult['city'];
				$gst['state'] = $dbresult['state'];
				$gst['country'] = $dbresult['country'];
			} else { //insert members deatils
				$oldUser = DB::table('tbl_members')
					->select('company', 'address', 'name', 'email', 'phoneno', 'city', 'state', 'country')
					->where('id', '=', $memid)
					->first();

				$gst['memid'] = $memid;
				$gst['gst_no'] = '';
				$gst['company_name'] = $oldUser['company'];
				$gst['address'] = $oldUser['address'];
				$gst['contact_person'] = $oldUser['name'];
				$gst['email'] = $oldUser['email'];
				$gst['phoneno'] = $oldUser['phoneno'];
				$gst['default'] = 1;

				$gst['city'] = $oldUser['city'];
				$gst['state'] = $oldUser['state'];
				$gst['country'] = $oldUser['country'];

				/* $location = htmlentities($gstLocation, ENT_QUOTES);
				$gstLocation = explode(",", $location);
				
				$gst['city'] = $gstLocation[0];
				$gst['state'] = $gstLocation[1];
				$gst['country'] = $gstLocation[2]; */
				$gst['created_on'] = date("Y-m-d H:i:s");
				$gst_id = DB::table('tbl_gst_no')->insertGetId($gst);
			}
		}

		$deviceType = 'website';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		$source_from = $resourceType == 'app' ? 'mobileapp' : 'website';
		////$source_from = $deviceType;

		if ($section == 'steelmint' || $section == 'reports' || strtolower($section) == 'coalmint') {
			$dbresult2 = DB::table('tbl_packages')
				->select('*')
				->where('id', $packageID)
				->get();
			$unit_of_tenure = 'Months';
			if (count($dbresult2) > 0) {
				$tabType =  $dbresult2[0]['tabType'];
				$packageName =  $dbresult2[0]['packageName'];
				$periodName =  $dbresult2[0]['period_name'];
				$unit_of_tenure =  $dbresult2[0]['unit_of_tenure'];
				$totalAmountWoGST =  $dbresult2[0]['totalAmount_Wo_GST'];
				$totalAmountWithGST =  $dbresult2[0]['totalAmount_With_GST'];
				$discountPercentage =  $dbresult2[0]['discount_percentage'];
				$gst_Rate =  $dbresult2[0]['gst_Rate'];
				$gst_Amt =  $dbresult2[0]['gst_Amt'];
				$billed_text =  $dbresult2[0]['billed_text'];
				$amountPerMonth =  $dbresult2[0]['amountPerMonth'];
				$scratch_value =  $dbresult2[0]['scratch_value'];
				$currencyCode =  $dbresult2[0]['currency_code'];

				$packageGroupID =  $dbresult2[0]['group_id'];
				$packageSubGroupId =  $dbresult2[0]['sub_group_id'];
				$packageOrder =  $dbresult2[0]['package_order'];
				$totalLicenses =  $dbresult2[0]['licenses_cnt'];
				$apple_package_ID =  $dbresult2[0]['apple_package_ID'];
			} else {
				$tabType = $request->input('tabType');
				$currencyCode = $request->input('currencyCode');
				$packageName = $request->input('packageName');
				$periodName = $request->input('periodName'); //12 months
				$totalAmountWoGST = $request->input('totalAmountWoGST'); //12 months
				$totalAmountWithGST = $request->input('totalAmountWithGST'); //12 months
				$discountPercentage = $request->input('discountPercentage'); //12 months
				$amountPerMonth = $request->input('amountPerMonth'); //12 months
				$scratchValue = $request->input('scratchValue'); //12 months

				$gst_Rate = $request->input('gstRate'); //12 months
				$gst_Amt = $request->input('gstAmt'); //12 months
				$billed_text = $request->input('billedtext'); //12 months
				$totalLicenses = $request->input('totalLicenses'); //12 months
				$apple_package_ID = ''; //12 months

				//$licensesCount
			}

			if (strtolower($packageName) == 'free trial') {
				$activePackages = DB::table('tbl_reg_logs')
					->select('selected_products as packageID', 'tbl_reg_logs.enddate', 'tbl_packages.group_id', 'tbl_packages.sub_group_id', 'tbl_packages.package_order')
					->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
					->where('tbl_reg_logs.memid', '=', $memid)
					->where('tbl_packages.packageName', '=', 'Free Trial')
					->where('tbl_packages.section', '=', strtolower($section))
					->whereIN('tbl_reg_logs.status', array('Active', 'expired'))
					->orderBy('selected_products', 'desc')
					->first();
				if (count($activePackages) > 0) {
					return new JsonResponse(array("status" => array("code" => 2001, "message" => "user already taken free trial !")));
				}
			}

			if (strtolower($deviceType) == 'ios' && (strtolower($section) == 'steelmint' || $section == "coalmint")) {
				$packageName = $apple_package_ID;
				//$packageName = 'com.steelmint.1YearSubscriptionplan'; 
			}
			$arr = array();

			$lead_type = 'A1';
			$mood = '';
			$fudate = '';


			if ($type == 'old') {
				//$lead_type = getLastLeadType($memid, $service_type=$f_product);
				$leadtypeArr = getLastLeadType($memid, $service_type = $f_product, $dflag = 'true');
				if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
					$lead_type = $leadtypeArr['lead_type'];
				if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
					$mood = $leadtypeArr['mood'];
				if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
					$fudate = $leadtypeArr['fudate'];

				if ($lead_type == 'A5' || $lead_type == 'B5')
					$lead_type = 'A11';
			}

			$rm_arr = getRMForRoutingProcess($memid, $company_name = strtolower($section), $lead_type);

			if (empty($rm_arr)) {
				$rm_arr['rm_id'] = $section == "coalmint" ? 125 : 0;
				$mood = 0;
				$rm_arr['subrm_id'] = $section == "coalmint" ? 125 : 0;
				$rm_arr['first_log_id'] = $section == "coalmint" ? 0 : 0;
			}

			//print_R($rm_arr);
			/* $start_date= $GLOBALS['currDate'];
			$end_date=date("Y-m-d",strtotime("$start_date +$periodName months")); */

			$f_tenure = (strtolower($section) == "steelmint" || $section == "coalmint") ? 'One Year' : $periodName . ' months';
			if (strtolower($packageName) == 'free trial')
				$f_tenure = $packageName;
			//$price = $dtls[23] * $_tax;

			$activePackages = DB::table('tbl_reg_logs')
				->select('selected_products as packageID', 'tbl_reg_logs.enddate', 'tbl_packages.group_id', 'tbl_packages.sub_group_id', 'tbl_packages.package_order')
				->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
				->where('tbl_reg_logs.memid', '=', $memid)
				->where('tbl_reg_logs.status', '=', 'Active')
				->where('tbl_packages.section', '=', strtolower($section))
				->orderBy('selected_products', 'desc')
				->first();
			if (count($activePackages) > 0) {
				$activePackageID = (int)$activePackages['packageID'];
				$activePackageGroupId = (int)$activePackages['group_id'];
				$activePackageSubGroupId = (int)$activePackages['sub_group_id'];
				$activePackageOrder = (int)$activePackages['package_order'];

				if ($packageGroupID < $activePackageGroupId)
					$servType = 'Downgrade';
				elseif ($packageGroupID == $activePackageGroupId) {
					if ($packageSubGroupId < $activePackageSubGroupId)
						$servType = 'Downgrade';
					elseif ($packageOrder < $activePackageOrder)
						$servType = 'Downgrade';
					else
						$servType = 'Renew';
				} else
					$servType = 'Upgrade';
			}

			$start_date = $GLOBALS['currDate'];
			if ($servType == 'Downgrade' || $servType == 'Renew') {
				//$start_date= $activePackages['enddate'];				
				$start_date = date("Y-m-d", strtotime($activePackages['enddate'] . " +1 day"));
			} elseif ($servType == 'Upgrade') { //currDate when to inactive current log
				$start_date = $GLOBALS['currDate'];
			}

			//$end_date=date("Y-m-d",strtotime("$start_date +$periodName months"));
			$end_date = date("Y-m-d", strtotime("$start_date +$periodName $unit_of_tenure"));

			$billNo = '';
			$logStatus = 'Pending';
			if (strtolower($packageName) != 'free trial' && strtolower($packageName) != 'request a demo') {
				if ($section == "coalmint")
					$billNo = getSMorderNoForCCAVENUE("CoalMint");
				else
					$billNo = getSMorderNoForCCAVENUE("SteelMint");
			} else {
				//
				///$logStatus = 'Active';
			}

			///$discount = round(($totalAmountWoGST*$discountPercentage)/100, 2);

			$SBCess = 0;
			if ($gst['state'] == 5 && $gst_Amt > 0) {
				$gst_Amt = $gst_Amt / 2;
				$SBCess = $gst_Amt;
			}

			if ($totalAmountWithGST == 0)
				$totalAmountWithGST = $totalAmountWoGST;



			$tbl_reg_logs = array(
				'memid' => $memid,
				'startdate' => $start_date,
				'enddate' => $end_date,
				'f_time' => $GLOBALS['currTime'],
				'f_product' => $f_product,
				'f_tenure' => $f_tenure, //'One Year',
				'status' => $logStatus,
				'selected_products' => $packageID,
				'comments' => $resourceType . ' registrationProcessNewConcept',
				'amtPaid' => $totalAmountWithGST,
				'amountWOTax' => $totalAmountWoGST,
				'ST' => $gst_Amt,
				'EC' => $SBCess,
				'gst_rate' => $gst_Rate,
				///'discount'=>$discount,
				'paymentstatus' => 'Pending',
				'created_on' => $GLOBALS['currDateTime'],
				'lead_type' => $lead_type,
				'fudate' => $fudate,
				'rm' => $rm_arr['rm_id'],
				'subrm' => $rm_arr['subrm_id'],
				'mood' => $mood,
				'pipeline_status' => 'New',
				'routing_status' => $lead_type,
				'billNo' => $billNo,
				'f_currency' => $currencyCode,
				'first_log_id' => $rm_arr['first_log_id'],
				'source_from' => $source_from,
				'gst_log_id' => $gst_id,
				'apple_package_ID' => $apple_package_ID,
				'form_no' => $extra_details,
				//'f_market'=>$selected_market,
				'f_market'   => $final_market,
				'package_feature' => $featuresValues
			);
			///print_r($tbl_reg_logs);

			/* $r = create_logs_from_array_of_array($arr);
			$_log_id = $r['tbl_reg_logs']; */
			try {
				$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
				$_rz_order_id = '';

				if (strtolower($deviceType) == 'ios' && (strtolower($section) == 'steelmint' || strtolower($section) == 'coalmint') && (strtolower($packageName) != 'free trial' && strtolower($packageName) != 'request a demo')) {
					//in app 
					$_rz_order_id = '';
				} elseif (strtolower($packageName) != 'free trial' && strtolower($packageName) != 'request a demo') {
					include_once('/home/steelmin/public_html/rz_functions.php');
					$r_rz_data = array(
						'type'		=>	'order',
						'order_id'	=>	$billNo,
						'cur'		=>	$currencyCode,
						'amt'	=>	$totalAmountWithGST,
						//										'cur'		=>	"INR",
						//										'amt'	=>	1,
						'company'	=>	strtolower($section), //'steelmint',
						'log_id'	=>	$_log_id
					);
					//print_R($r_rz_data);
					$_rz_order_id = create_rz_order($r_rz_data);
				} else {
					include_once('/home/steelmin/public_html/hf.php');
					updateTbltbl_updated_reg_logs($memid);
				}
			} catch (QueryException $e) {
				//dd($e);
				echo $e->getMessage();
			}



			if (!empty($_log_id) && empty($rm_arr['first_log_id'])) {
				//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
				//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
				$data['first_log_id'] = $_log_id;
				$data['rz_order_id'] = $_rz_order_id;

				DB::table('tbl_reg_logs')
					->where('id', $_log_id)
					->update($data);
			} elseif (!empty($_log_id) && !empty($_rz_order_id)) {
				$data['rz_order_id'] = $_rz_order_id;

				DB::table('tbl_reg_logs')
					->where('id', $_log_id)
					->update($data);
			}

			DB::table($_ENV['COMMENTS_TABLE'])->insert([
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => "Request Service Type : " . $servType,
				'created_by' => 'self',
				'comments_for' => $resourceType
			]);

			$comments_for = $this->appType; //'SM';

			$pymt_details = 'RZ_PAY';
		} elseif ($section == 'events') {
			$discountPercentage = 0;


			$eventID = $request->input('eventID');
			$eventType = $request->input('eventType'); //early_bird
			$currencyCode = $request->input('currencyCode');
			$perDelegatePrice = $request->input('perDelegatePrice');
			$totalLicenses = $request->input('totalLicenses');
			//$eventLocation = $request->input('eventLocation');
			//$packageName = $request->input('packageName');
			if ($eventID == '')
				$eventID = getActiveEventId();
			$arrEvntDtls = get_latest_event_details($eventID);
			$exArrEvntDtls = explode("/*/", $arrEvntDtls);

			$packageName = $exArrEvntDtls[2];
			$event_venue = $exArrEvntDtls[0];
			$event_date = $exArrEvntDtls[1];
			$event_pos = $exArrEvntDtls[33];

			$totalAmountWoGST = $perDelegatePrice * $totalLicenses;


			$gst_Amt = 0;
			$discount = 0;
			$SBCess = 0;
			$gst_Rate = 0;
			if (($gst['country'] == 113 && $currencyCode == 'USD') || $currencyCode == 'INR') {

				$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax']) / 100);

				$totalAmountWithGST = $totalAmountWoGST + $gst_Amt;

				if ($gst['state'] == 5) { //for C.G.
					$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
					$SBCess = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
				}

				$pymt_details = 'CCAVENUE';
				$gst_Rate = $GLOBALS['STtax'];
			} else {
				$pymt_details = 'PAYPAL';
				$totalAmountWithGST = $totalAmountWoGST;
			}

			$pymt_details = 'RZ_PAY';
			///$pymt_details='CCAVENUE';
			$pym_mode = 'NEFT/Online';
			$billNo = getSMorderNoForCCAVENUE($section);

			$tbl_reg_logs = array(
				'event_id' => $eventID,
				'registering_id' => $memid,
				'created_on' => $GLOBALS['currDateTime'],
				'pay_date' => $GLOBALS['currDateTime'],
				'pymt_details' => $pymt_details,
				'pym_mode' => $pym_mode,
				////'f_time'=>$GLOBALS['currTime'],
				'status' => 'Pending',
				'selected_services' => '',
				'comments' => $resourceType . ' registrationProcessNewConcept',
				'pay_amt' => $totalAmountWithGST,
				'sub_total' => $totalAmountWoGST,
				'stax' => $gst_Amt,
				'cess' => $SBCess,
				'gst_rate' => $gst_Rate,
				'round_off' => '',
				'discount' => $discount,
				'bill_no' => $billNo,
				'nb_order_no' => '',
				'nb_bid' => '',
				'card_category' => '',
				'bank_name' => '',
				'delegates_ids' => $memid,
				'f_currency' => $currencyCode,
				'no_of_memids' => $totalLicenses, //'One Year',
				'paymentstatus' => 'Pending',
				'source_from' => $source_from,
				'gst_log_id' => $gst_id
			);

			$billed_text = 'Billed for event Only';
			///print_r($tbl_reg_logs);

			/* $r = create_logs_from_array_of_array($arr);
			$_log_id = $r['tbl_reg_logs']; */
			try {
				$_log_id = DB::table('tbl_sm_events_payment_details')->insertGetId($tbl_reg_logs);
				makeEntryInTableFinalStatus($memid, $eventID);

				if (!$request->has('gstDetails') || ($request->has('gstDetails') && strtoupper($request->input('gstDetails')) != 'Y')) {
					include_once('/home/steelmin/public_html/rz_functions.php');
					$r_rz_data = array(
						'type'	=>	'order',
						'order_id'	=>	$billNo,
						'cur'	=>	$currencyCode,
						'amt'	=>	$totalAmountWithGST,
						//										'cur'	=>	"INR",
						//										'amt'	=>	1,
						'company'	=>	'events',
						'log_id'	=>	$_log_id
					);

					$_rz_order_id = create_rz_order($r_rz_data);

					if (!empty($_log_id)) {
						///$data['first_log_id'] = $_log_id;
						$data['rz_order_id'] = $_rz_order_id;

						DB::table('tbl_sm_events_payment_details')
							->where('id', $_log_id)
							->update($data);
					}
				}
			} catch (QueryException $e) {
				dd($e);
			}

			$comments_for = 'EVT';
		}
		$moreLicenses = '';
		/* foreach($request->input('moreLicenses') as $key=>$subvalue)
			{	
				$moreLicenses = $moreLicenses." $key => ".$subvalue." <br /> ";
			} */
		if ($request->has('moreLicenses') && !empty($request->input('moreLicenses'))) {
			$moreLicenses = json_encode($request->input('moreLicenses'));

			DB::table($_ENV['COMMENTS_TABLE'])->insert([
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => $moreLicenses,
				'created_by' => 'self',
				'log_id' => $_log_id,
				'comments_for' => $comments_for
			]);
		}



		$userMessage = '';
		//if($packageName=='Price Only'){//send mail to RM and Show RM contact deatils to user
		if ($tabType == 'productWise') { //send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM("Product Wise", $memid);
			$paymentURL = '';
			$paymentType = '';
		} elseif (strtolower($section) == 'coalmint' && strtolower($packageName) == 'free trial') { //send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM("Free Trial", $memid);
			$paymentURL = "https://www.coalmint.com/" . 'freeTrialSuccessful';
			$paymentType = '';
		} elseif (strtolower($packageName) == 'free trial') { //send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM("Free Trial", $memid);
			$paymentURL = '';
			$paymentType = '';
		} elseif (((strtolower($packageName) == 'platinum+' || (strtolower($packageName) == 'platinum' && strtolower($section) != 'coalmint'))) || strtolower($packageName) == 'request a demo') {
			//strtolower($section)=='steelmint' &&
			//send mail to RM and Show RM contact deatils to user
			//$userMessage =  \ApiQuery::sendRequestMailToRM("Platinum+",$memid);
			$userMessage =  \ApiQuery::sendRequestMailToRM($packageName, $memid);
			///$paymentURL='https://www.steelmint.com/tnxPageForPlatinumPlusBuyers';
			if (strtolower($section) == 'coalmint')
				$paymentURL = 'https://www.coalmint.com/tnxPageForPlatinumPlusBuyers';
			else
				$paymentURL = BASEURL . 'tnxPageForPlatinumPlusBuyers';
			$paymentType = '';
		} else {
			//$paymentURL='https://www.steelmint.com/pay/newCheckOut_new.php';
			//$paymentType='sdk';
			$paymentType = 'web';


			if ($pymt_details == 'RZ_PAY') {
				$paymentURL = BASEURL . "rzpay/init.php?memid=" . $memid . "&order_id=" . $_rz_order_id . "&section=" . $section;
			}
		}

		if ($resourceType == 'web') {

			$result = array(
				"paymentType" => "web", //sdk/web
				"paymentURL" => $paymentURL, //"https://www.steelmint.com/pay/newCheckOut_new.php",
				"message" => $userMessage, //if no payment neended
				"packageName" => $packageName,
				"lastLogId" => $_log_id,
				"rz_order_id" => $_rz_order_id,
				"totalAmount" => (float)$totalAmountWoGST,
				"amountPayable" => (float)$totalAmountWithGST,
				"gstAmt" => (float)$gst_Amt + $SBCess,
				"gstRate" => (float)$gst_Rate,
				"billedText" => $billed_text,
				///"tax"=>900,
				"discount" => $discount,
				"discountPercentage" => $discountPercentage,
				"currency" => $currencyCode
			);
			$code = 1001;
			$message = "Successfully Registered";
		} else {
			$deviceId = $request->input('deviceID');
			//if ($request->has('deviceID') && $request->input('deviceID')!='') {
			if (1) {
				/*$fcmToken = $request->input('fcmToken');
				$userDetails = $request->input('userDetails');
				$packageDetails = $request->input('packageDetails');*/

				$result = array(
					"displayMessage" => "Thank you for registering on Bigmint.co. Our team will contact you soon.",
					"paymentType" => $paymentType,
					"paymentURL" => $paymentURL,
					"message" => $userMessage, //if no payment neended
					"packageName" => $packageName,
					"lastLogId" => $_log_id,
					"rz_order_id" => $_rz_order_id,
					"totalAmount" => (float)$totalAmountWoGST,
					"amountPayable" => (float)$totalAmountWithGST,
					"gstAmt" => (float)$gst_Amt + $SBCess,
					//"gstAmt"=>(double)$SBCess,
					"gstRate" => (float)$gst_Rate,
					"billedText" => $billed_text,
					///"tax"=>900,
					"discount" => $discount,
					"discountPercentage" => $discountPercentage,
					"currency" => $currencyCode
				);
				$code = 1001;
				$message = "Successfully Registered";
			} else {
				$code = 2001;
				$message = "Access token is invalid or has expired.";
			}
		}
		//, "data"=> $result;
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}


	public function registerRequestademo_old(Request $request)
	{
		try {

			// =========================
			// NORMALIZE ARRAYS → CSV
			// =========================
			$toCsv = function ($key) use ($request) {
				$val = $request->input($key);
				return is_array($val) ? implode(',', $val) : $val;
			};

			// =========================
			// PREPARE DATA
			// =========================
			$insert = [
				'name'            => $request->input('name'),
				'email'           => $request->input('email'),
				'mobile'          => $request->input('mobile_number'),
				'isd_code'        => $request->input('isdCode'),
				'company_name'    => $request->input('company_name'),
				'company_type'    => $request->input('company_type'),
				'job_title'       => $request->input('job_title'),

				'market_values'   => $toCsv('marketValues'),
				'features_values' => $toCsv('featuresValues'),

				'ferrous_sub'     => $toCsv('ferrous_sub'),
				'nonferrous_sub'  => $toCsv('nonferrous_sub'),
				'scrap_sub'       => $toCsv('scrap_sub'),
				'coal_sub'        => $toCsv('coal_sub'),
				'agri_sub'        => $toCsv('agri_sub'),
				'logistics_sub'   => $toCsv('logistics_sub'),

				'raw_payload'     => json_encode($request->all()),
				'created_at'      => date('Y-m-d H:i:s'),
				'updated_at'      => date('Y-m-d H:i:s'),
				'page_type'       => $toCsv('page_type'),
			];

			$id = DB::table('tbl_demo_form_leads')->insertGetId($insert);

			return response()->json([
				'status' => ['code' => 1001, 'message' => 'Lead captured'],
				'data' => ['lead_id' => $id]
			]);
		} catch (\Exception $e) {

			\Log::error('Demo form error: ' . $e->getMessage());

			return response()->json([
				'status' => ['code' => 2001, 'message' => 'Something went wrong']
			]);
		}
	}

	public function registerRequestademo(Request $request)
	{
		$result = array();
		$resourceType = 'web';
		if ($request->has('resourceType') && $request->has('resourceType') != '')
			$resourceType = $request->input('resourceType');

		$section = 'steelmint';
		if ($request->has('page_type') && $request->has('page_type') != '')
			$section = $request->input('page_type');

		if ('signup' == strtolower($section))
			$section = 'steelmint';
		$email = '';
		if ($request->has('email') && $request->has('email') != '') {
			$email = $request->input('email');
		} else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Email Required')));
		}

		$isdCode = '';
		if ($request->has('isdCode') && $request->has('isdCode') != '')
			$isdCode = $request->input('isdCode');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'ISD Code Required')));
		}

		$country_code = '';
		if ($request->has('countryCode') && $request->has('countryCode') != '')
			$country_code = $request->input('countryCode');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Country Code Required')));
		}

		$mobileNumber = '';
		if ($request->has('mobile_number') && $request->has('mobile_number') != '')
			$mobileNumber = $request->input('mobile_number');
		else {
			return new JsonResponse(array("status#" => array("code" => 2100, "message" => 'Phoneno Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Phoneno Required")); 
		}
		$name = '';
		if ($request->has('name') && $request->has('name') != '')
			$name = $request->input('name');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Name Required')));
			//return new JsonResponse(array("status#" => 1, "message" => "Name Required")); 
		}

		$job_title = '';
		if ($request->has('job_title') && $request->has('job_title') != '')
			$job_title = $request->input('job_title');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Job Title Required')));
		}
		$company_name = '';
		if ($request->has('company_name') && $request->has('company_name') != '')
			$company_name = $request->input('company_name');
		else {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Company Name Required')));
		}

		$company_type = '';
		if ($request->has('company_type') && $request->has('company_type') != '') {
			$company_type = $request->input('company_type');
			//$company_type = (array) $request->input('company_type');    
			// $company_type_id = implode(",",$company_type);
			/*$industry_type = DB::table('tbl_industry_types')
                            ->where('id', $company_type)
                            ->pluck('name')
                            ->implode('*');
			*/
			$industry_type = DB::table('tbl_industry_types')
				->where('id', $company_type)
				->value('name');
		}



		$GLOBALS['currDate'] = date('Y-m-d'); // Current date in YYYY-MM-DD format
		$GLOBALS['currTime'] = date('H:i:s'); // Current time in HH:MM:SS format
		$GLOBALS['currDateTime'] = date('Y-m-d H:i:s'); // Current date and time in YYYY-MM-DD HH:MM:SS format

		// 🔹 Ensure market & features from for loop (comma separated)
		$marketValues   = isset($request['marketValues']) ? trim($request['marketValues']) : '';
		$featuresValues = isset($request['featuresValues']) ? trim($request['featuresValues']) : '';


		if ($marketValues == '')
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Please select at-least one market.')));

		if ($featuresValues == '')
			return new JsonResponse(array("status" => array("code" => 2100, "message" => 'Please select at-least one feature.')));

		//market fetch        
		/*
       $marketMap = [
            'ferrous'      => (array) $request->input('ferrous_sub', []),
            'non-ferrous'  => (array) $request->input('nonferrous_sub', []),
            'scrap-recycling' => (array) $request->input('scrap_sub', []),
            'coal'         => (array) $request->input('coal_sub', []),
            'agriculture'  => (array) $request->input('agri_sub', []),
            'logistics'    => (array) $request->input('logistics_sub', []),
        ];*/
		// Define all possible market keys and corresponding request keys
		/* $marketKeys = [
          'ferrous'        => 'ferrous_sub[]',
          'non-ferrous'    => 'nonferrous_sub[]',
          'scrap-recycling'=> 'scrap_sub[]',
          'coal'           => 'coal_sub[]',
          'agriculture'    => 'agri_sub[]',
          'logistics'      => 'logistics_sub[]',
      ];

        // Build $marketMap dynamically
        $marketMap = [];

        foreach ($marketKeys as $marketName => $requestKey) {
            // Always cast input to array, fallback to empty array
            $marketMap[$marketName] = (array) $request->input($requestKey, []);
        }
       
		print_r($marketMap); */


		$marketMap = [
			'ferrous'      => (array) $request->input('ferrous_sub', []),
			'non-ferrous'  => (array) $request->input('nonferrous_sub', []),
			'scrap-recycling' => (array) $request->input('scrap_sub', []),
			'coal'         => (array) $request->input('coal_sub', []),
			'agriculture'  => (array) $request->input('agri_sub', []),
			'logistics'    => (array) $request->input('logistics_sub', []),
		];

		$ipAddress = $_SERVER['REMOTE_ADDR'];
		//DB::enableQueryLog(); 
		$dbresult = DB::table($_ENV['USER_TABLE'])
			->select('id')
			->where(function ($q) use ($email) {
				$q->where('email', $email)
					->orWhere('addtnl_email', $email)
					->orWhere('username', $email);
			})
			->orWhere(function ($q) use ($mobileNumber) {
				$q->where('phoneno', $mobileNumber)
					->orWhere('alternate_mob_no', $mobileNumber)
					->orWhere('username', $mobileNumber);
			})
			->first();

		$dbresult = json_decode(json_encode($dbresult), true);

		if ($section == 'demo') {
			$sec = 'Request a demo';
			$sec_id = 2094;
		} else {
			$sec = "SM " . $resourceType;
			$sec_id = "SM " . $resourceType;
		}


		$campCode = $section == 'demo' ? ($resourceType == 'web' ? 'CAMP112' : 'CAMP139') : ($resourceType == 'app' ? 'CAMP19' : 'CAMP165');
		//php version
		if (count($dbresult) == 0) {
			//if (is_null($dbresult)) {
			//new user
			$expVal = explode(" ", $isdCode);
			$std_code = end($expVal);
			$isdCode = '+' . trim($std_code, '+');

			$cntry_id = 0;
			/*
				$result = DB::table('tbl_country')
                    ->select('id')
                    ->where('std_code', '=', $isdCode)
                    ->first();
*/
			$result = DB::table('tbl_country')
				->select('id')
				->where('std_code', '=', $isdCode)
				->where('country_code', '=', $country_code)
				->first();

			if (count($result) > 0) {
				//$result = json_decode(json_encode($result), true);
				//if ($result) {
				$cntry_id = $result['id'];
			}
			$type = 'new';
			$newUser['name'] = htmlspecialchars($name, ENT_QUOTES);
			$newUser['username'] = $email;
			$newUser['email'] = $email;
			$newUser['phoneno'] = $mobileNumber;
			$newUser['isd_code'] = $isdCode;
			$newUser['country'] = $cntry_id;
			$newUser['job_title'] = $job_title;
			$newUser['password'] = bin2hex(random_bytes(4));
			$newUser['ol_be'] = $sec;
			$newUser['main_source'] = $section . ' Registraion Page';
			$newUser['source_from'] = $resourceType == 'app' ? 'Mobile App' : 'Web';
			$newUser['ipaddress'] = $ipAddress;
			$newUser['date'] = $GLOBALS['currDateTime'];
			$newUser['primary_source'] = $campCode;
			$newUser['company'] = $company_name;

			$newUser['lead_type'] = 'A1';
			$memid = DB::table('tbl_members')->insertGetId($newUser);

			// 5. Prepare insert rows
			$insertIndData = [];
			$currentDateTime = date('Y-m-d H:i:s');
			$insertIndData[] = [
				'member_id'        => $memid,
				'industry_type_id' => $company_type,
				'created_by'       => $memid,
				'created_on'       => $currentDateTime
			];


			// 6. Insert if data exists
			if (!empty($insertIndData)) {
				DB::table('tbl_member_industry_types')->insert($insertIndData);
			}
		} else {
			$memid = $dbresult['id'];
			$type = 'old';
		}
		/* echo "<pre>";
			print_r($dbresult);
			echo "<br>" . $memid . " -- " . $type; dd(); */

		$field_array = array();
		$field_array =  array(
			'created_on' => $GLOBALS['currDateTime'],
			'camp_code' => $campCode,
			'memid' => $memid,
			'refral_url' => '',
			'ip' => $ipAddress,
			'source' => $resourceType
		);
		addCampaignHistory($field_array);

		//require_once("/var/www/html/inc/db.php"); 
		require_once("/home/steelmin/public_html/hf.php");
		$lead_type = 'A1';
		$mood = '';
		$fudate = '';
		if ($type == 'old') {
			//$lead_type = getLastLeadType($memid, $service_type=$f_product);
			$leadtypeArr = getLastLeadType($memid, $service_type = 'W', $dflag = 'true');
			if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
				$lead_type = $leadtypeArr['lead_type'];
			if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
				$mood = $leadtypeArr['mood'];
			if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
				$fudate = $leadtypeArr['fudate'];

			if ($lead_type == 'A5' || $lead_type == 'B5')
				$lead_type = 'A11';
		}

		$rm_arr = getRMForRoutingProcess($memid, $company_name = 'steelmint', $lead_type);
		// $rm_arr=[];
		$tbl_reg_logs = array(
			'memid' => $memid,
			'startdate' => $GLOBALS['currDate'],
			'enddate' => $GLOBALS['currDate'],
			'f_time' => $GLOBALS['currTime'],
			'f_product' => 'W',
			'f_tenure' => 'One Day',
			'status' => 'Pending',
			'selected_products' => $sec_id,
			'comments' => 'From : ' . $sec,
			'created_on' => $GLOBALS['currDateTime'],
			'lead_type' => $lead_type,
			'fudate' => $fudate,
			'rm' => isset($rm_arr['rm_id']) ? $rm_arr['rm_id'] : '',
			'subrm' => isset($rm_arr['subrm_id']) ? $rm_arr['subrm_id'] : '',
			'mood' => $mood,
			'pipeline_status' => 'New',
			'routing_status' => $lead_type,
			'first_log_id' =>  isset($rm_arr['first_log_id']) ? $rm_arr['first_log_id'] : '',
			'f_market'   => $marketValues,
			'package_feature' => $featuresValues
		);
		try {
			$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
			updateTbltbl_updated_reg_logs($memid);
			//insert details of  selected market commodity 
			$insertMarkets = [];
			$now = date('Y-m-d H:i:s');
			//print_r($marketMap);
			foreach ($marketMap as $market => $subs) {
				foreach ($subs as $sub) {
					if (!empty($sub)) {
						$insertMarkets[] = [
							'log_id' => $_log_id,
							'member_id'   => $memid,
							'market'      => $market,
							'sub_market'  => $sub,
							'created_on'  => $now,
							'created_by'  => $memid,
						];
					}
				}
			}
			if (!empty($insertMarkets)) {
				DB::table('tbl_member_market_preferences')->insert($insertMarkets);
			}
		} catch (QueryException $e) {
			dd($e);
		}
		$comments = '';
		/*  foreach($request->all() as $key=>$subvalue){
                $comments = $comments." $key => ".$subvalue." <br /> ";
            }    
            */
		$ignoreKeys = ['license_count', 'packageType', 'package_id', 'no_of_months', 'memid', '_token', 'countryCode'];
		// Key rename mapping
		$keyLabels = [
			'ferrous_sub'        => 'Ferrous commodities',
			'ferrous_sub[]'      => 'Ferrous commodities',

			'nonferrous_sub'     => 'Non-ferrous commodities',
			'nonferrous_sub[]'   => 'Non-ferrous commodities',

			'scrap_sub'          => 'Scrap recycling commodities',
			'scrap_sub[]'        => 'Scrap recycling commodities',

			'coal_sub'           => 'Coal & energy commodities',
			'coal_sub[]'         => 'Coal & energy commodities',

			'agri_sub'           => 'Agriculture commodities',
			'agri_sub[]'         => 'Agriculture commodities',

			'logistics_sub'      => 'Logistics commodities',
			'logistics_sub[]'    => 'Logistics commodities',
		];
		foreach ($request->all() as $key => $subvalue) {
			// Skip unwanted keys
			if (in_array($key, $ignoreKeys)) {
				continue;
			}
			// Rename key if exists in mapping
			$displayKey = $keyLabels[$key] ?? $key;
			// Convert array values to string
			if (is_array($subvalue)) {
				$subvalue = implode(', ', $subvalue);
			}
			if ($key == 'company_type') {
				$comments .= "$displayKey => $industry_type <br />";
			} else {
				$comments .= "$displayKey => $subvalue <br />";
			}
		}
		$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
		$comments .= " ip => " . $ipAddress . " <br /> ";
		DB::table($_ENV['COMMENTS_TABLE'])->insert(
			[
				'memid' => $memid,
				'f_date' => $GLOBALS['currDate'],
				'f_time' => $GLOBALS['currTime'],
				'comments' => "Request Service Type : " . $comments,
				'created_by' => 'self',
				'comments_for' => $section
			]
		);
		$code = 1001;
		$message = "Successfully Sent";

		require_once("/home/steelmin/public_html/inc/desconfig.php");
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
	}



	public function goWithGSTDetails(Request $request)
	{

		$result = array();
		if (!$request->has('memid')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "user id missing !")));
		} else {
			$memid = $request->input('memid');

			if ($request->has('promotionalMails') && $request->input('promotionalMails') == 'Y') {
				$email_category = $request->input('resourceType') == 'app' ? '22' : '23';
				$newUser['email_category'] = DB::raw('CONCAT(email_category,",' . $email_category . '")');
				DB::table('tbl_members')
					->where('id', $memid)
					->update($newUser);
			}
		}

		if (!$request->has('lastLogID')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "log id missing !")));
		} else {
			$lastLogId = $request->input('lastLogID');
		}

		$section = 'steelmint';
		if ($request->has('section'))
			$section = strtolower($request->input('section'));

		$paymentURL = '';
		if ($request->has('paymentURL'))
			$paymentURL = $request->input('paymentURL');

		$gstDetails = 'N';
		if ($request->has('gstDetails'))
			$gstDetails = $request->input('gstDetails');

		if ($gstDetails == 'Y') {
			if (!empty($request->input('gstNo'))) {
				$gst['gst_no'] = $request->input('gstNo');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Number must not be empty!")));
			}

			if (!empty($request->input('gstCompany'))) {
				$gst['company_name'] = $request->input('gstCompany');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Company must not be empty!")));
			}

			if (!empty($request->input('gstLocation'))) {
				//$gst['gstLocation'] = $request->input('gstLocation');
				$gstLocation = $request->input('gstLocation');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Location must not be empty!")));
			}

			if (!empty($request->input('gstAddress'))) {
				$gst['address'] = $request->input('gstAddress');
			} else {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "GST Address must not be empty!")));
			}

			$oldUser = DB::table('tbl_members')
				->select('company', 'address', 'name', 'email', 'phoneno')
				->where('id', '=', $memid)
				->first();

			$gst['memid'] = $memid;
			///$gst['gst_no'] = '';
			//$gst['company_name'] = $oldUser['company'];
			///$gst['address'] = $oldUser['address'];
			$gst['contact_person'] = $oldUser['name'];
			$gst['email'] = $oldUser['email'];
			$gst['phoneno'] = $oldUser['phoneno'];
			$gst['default'] = 1;

			$location = htmlentities($gstLocation, ENT_QUOTES);
			$gstLocation = explode("-", str_replace(",", "-", $location));

			$gst['city'] = $gstLocation[0];
			$gst['state'] = $gstLocation[1];
			$gst['country'] = $gstLocation[2];

			$dbresult = DB::table('tbl_gst_no')
				->select('id')
				->where($gst)
				->orderBy('default', 'desc')
				->first();
			if (count($dbresult) > 0) {
				$gst_id = $dbresult['id'];
			} else {
				$gst_id = DB::table('tbl_gst_no')->insertGetId($gst);
			}

			$data['gst_log_id'] = $gst_id;

			$currencyCode = 'N';
			if ($request->has('currencyCode'))
				$currencyCode = $request->input('currencyCode');


			if ($section == "events") {
				$logRow = DB::table('tbl_sm_events_payment_details')
					->select('sub_total', 'pay_amt', 'bill_no', 'rz_order_id')
					->where('id', '=', $lastLogId)
					->first();

				$totalAmountWoGST = $logRow['sub_total'];
				$billNo = $logRow['bill_no'];
				$oldTotalAmountWithGST = $logRow['pay_amt'];
				$_rz_order_id = $logRow['rz_order_id'];

				$table_name = "tbl_sm_events_payment_details";
			} else {
				$logRow = DB::table("tbl_reg_logs")
					->select('amountWOTax', 'amtPaid', 'rz_order_id')
					->where('id', '=', $lastLogId)
					->first();

				$totalAmountWoGST = $logRow['amountWOTax'];
				$oldTotalAmountWithGST = $logRow['amtPaid'];
				$_rz_order_id = $logRow['rz_order_id'];

				$table_name = "tbl_reg_logs";
			}

			////
			$gst_Amt = 0;
			$discount = 0;
			$SBCess = 0;
			if (($gst['country'] == 113 && $currencyCode == 'USD') || $currencyCode == 'INR') {

				$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax']) / 100);

				$totalAmountWithGST = $totalAmountWoGST + $gst_Amt;

				if ($gst['state'] == 5) { //for C.G.
					$gst_Amt = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
					$SBCess = strval(($totalAmountWoGST * $GLOBALS['STtax'] / 2) / 100);
				}

				$pymt_details = 'CCAVENUE';
				$gst_Rate = $GLOBALS['STtax'];
			} else {
				$pymt_details = 'PAYPAL';
				$totalAmountWithGST = $totalAmountWoGST;
			}

			if ($section == "events") {
				if ($_rz_order_id == '') {
					include_once('/home/steelmin/public_html/rz_functions.php');
					$r_rz_data = array(
						'type'	=>	'order',
						'order_id'	=>	$billNo,
						'company'	=>	'events',
						'cur'	=>	$currencyCode,
						'amt'	=>	$totalAmountWithGST,
						//										'cur'	=>	"INR",
						//										'amt'	=>	1,
						'log_id'	=>	$lastLogId
					);

					$_rz_order_id = create_rz_order($r_rz_data);

					if (!empty($lastLogId)) {
						///$data['first_log_id'] = $_log_id;
						$data['rz_order_id'] = $_rz_order_id;

						/* DB::table('tbl_sm_events_payment_details')
							->where('id', $lastLogId)
							->update($data);	 */
					}
				}

				$data['pay_amt'] = $totalAmountWithGST;
				$data['sub_total'] = $totalAmountWoGST;
				$data['stax'] = $gst_Amt;
				$data['cess'] = $SBCess;
			} else {
				$data['amtPaid'] = $totalAmountWithGST;
				$data['amountWOTax'] = $totalAmountWoGST;
				$data['ST'] = $gst_Amt;
				$data['EC'] = $SBCess;
			}
			////
			//print_r($data);

			DB::table($table_name)
				->where('id', $lastLogId)
				->update($data);
			/* if($section=="events"){
				DB::table('tbl_sm_events_payment_details')
					->where('id', $lastLogId)
					->update($data);
			}else{
				DB::table('tbl_reg_logs')
					->where('id', $lastLogId)
					->update($data);
			} */
			$paymentURL = str_replace("&amt=" . intval($oldTotalAmountWithGST) . "&", "&amt=" . intval($totalAmountWithGST) . "&", $paymentURL);
			$paymentURL = BASEURL . "rzpay/init.php?memid=" . $memid . "&order_id=" . $_rz_order_id;
		} else {
			$data = array();
			if ($request->has('promotionalMails') && $request->input('promotionalMails') == 'Y') {
				$email_category = $resourceType == 'app' ? '22' : '23';
				$data['email_category'] = DB::raw('CONCAT(email_category,",' . $email_category . '")');

				DB::table('tbl_members')
					->where('id', $memid)
					->update($data);
			}
		}

		$result["paymentURL"] = $paymentURL;
		$result["rz_order_id"] = $_rz_order_id;
		$code = 1001;
		$message = "Success";

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}


	public function rzpayResponceHandler(Request $request)
	{ //Response

		if ($request->has('error')) {
			$errorMsg = $request->input('error');
			$logID = $request->input('logID');
			if ($request->has('razorpay_order_id'))
				$razorpay_order_id = $request->input('razorpay_order_id');
			else
				$razorpay_order_id = $logID;

			include_once('/home/steelmin/public_html/rz_functions.php');
			$message = paymentFailedAction($razorpay_order_id, $errorMsg, $sourceFrom = 'mobileapp');

			return new JsonResponse(array("status" => array("code" => 2001, "message" => $errorMsg)));
		} elseif ($request->has('razorpay_payment_id') && $request->has('razorpay_order_id')) {
			//	return $request->all();
			$logID = $request->input('logID');
			$razorpay_order_id = $request->input('razorpay_order_id');
			$razorpay_payment_id = $request->input('razorpay_payment_id');
			$razorpay_signature = $request->input('razorpay_signature');
			$user_contact_after_payment = '';
			$user_email_after_payment = '';

			$argu['razorpay_order_id'] = $razorpay_order_id;
			$argu['razorpay_payment_id'] = $razorpay_payment_id;
			$argu['razorpay_signature'] = $razorpay_signature;
			$argu['source_from'] = 'mobileapp';
			//print_r($argu);
			include_once('/home/steelmin/public_html/rz_functions.php');

			$message = save_verify_signature_and_capture($argu);
			//print_r($argu);
			return new JsonResponse(array("status" => array("code" => 1001, "message" => $message)));
		} else {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => 'error! invalid request')));
		}
	}

	public function jobApply(Request $request)
	{

		$result = array();
		if (!$request->has('position')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Position Applied for is Empty !")));
		} else {
			$result['position'] = $request->input('position');
			//$result['position'] = $position;
		}

		if (!$request->has('name')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Name is Empty !")));
		} else {
			$result['name'] = $request->input('name');
			//$result['name'] = $name;
		}

		if (!$request->has('email')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Email is Empty !")));
		} else {
			$result['email'] = $request->input('email');
			//$result['email'] = $position;
		}

		if (!$request->has('isdCode')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "ISD Code is Empty !")));
		} else {
			$result['isdCode'] = $request->input('isdCode');
			//$result['email'] = $position;
		}

		if (!$request->has('phonneno')) {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Phone is Empty !")));
		} else {
			$result['phonneno'] = $request->input('phonneno');
			//$result['email'] = $position;
		}

		if (!$request->has('address')) {
			$result['address'] = '';
		} else {
			$result['address'] = $request->input('address');
		}

		if (!$request->has('workExperience')) {
			$result['workExperience'] = '';
		} else {
			$result['workExperience'] = $request->input('workExperience');
		}

		if (!$request->has('presentOrganisation')) {
			$result['presentOrganisation'] = '';
		} else {
			$result['presentOrganisation'] = $request->input('presentOrganisation');
		}

		if (!$request->has('serviceDuration')) {
			$result['serviceDuration'] = '';
		} else {
			$result['serviceDuration'] = $request->input('serviceDuration');
		}

		$from_type = 'SteelMint';

		/* if($request->has('profileDoc')) {
			$str= str_replace('\\','',$request->input('profileDoc'));
			$str= str_replace(' ','+',$str);
			$str = base64_decode($str);
			$profileDoc = date('HiYMD');
			file_put_contents("/home/steelmin/public_html/resumes/" . $profileDoc . ".png", $str);           
			$data['profileDoc'] = $profileDoc . ".png";
							
		} */
		include("/home/steelmin/public_html/mf.php");
		$to = 'jobs@steelmint.com'; // Replace with your email
		//$to = 'mohan@theitbooth.com,pratham.soni@steelmintgroup.com'; // Replace with your email

		//$filePath = 'https://www.steelmint.com/resumes/'.basename($_FILES["file"]["name"]);
		//$filePath = 'https://www.steelmint.com/resumes/mohan.pdf';
		if ($request->has('filePath')) {
			$filePath = str_replace('\\', '', $request->input('filePath'));
		}
		$subject = $from_type . ': Inquiry from Careers Page'; // Replace with your subject if you need
		$message = 	 'Position: ' . $result['position'] . "<br />" .
			'Name: ' . $result['name'] . "<br /><br />" .
			'Phone: ' . $result['isdCode'] . $result['phonneno'] . "<br /><br />" .
			'E-mail: ' . $result['email'] . "<br />" .
			'Address: ' . $result['address'] . "<br />" .
			'Experience: ' . $result['workExperience'] . "<br />" .
			'Organisation: ' . $result['presentOrganisation'] . "<br />" .
			// 'Designation: ' . $result['designation']. "<br />" .
			'serviceDuration: ' . $result['serviceDuration'] . "<br />" .
			'File uploaded: ' . $filePath;

		//$r = sendSMMail($message, $to, "", $subject, '', "hr@steelmint.com", $from_type, "hr@steelmint.com");
		$r = sendSMMail($message, $to, "HR | " . $from_type, $subject, '', "info@steelmint.com", "SteelMint | Career", "info@steelmint.com");

		$message = "Successfully Applied";
		return new JsonResponse(array("status" => array("code" => 1001, "message" => $message)));
	}

	public function verifyOTPNewConcept_mobile(Request $request)
	{

		$result = array();
		$deviceID = 'web';
		$OTP = '';
		$isdCode = '';
		$resourceType = 'app';
		if ($request->has('resourceType'))
			$resourceType = $request->input('resourceType');

		$section = 'steelmint';
		if ($request->has('section'))
			$section = strtolower($request->input('section'));
		elseif ($this->appType == 'CM')
			$section = 'coalmint';

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = ($request->input('deviceType'));

		$ipAddress = $_SERVER['REMOTE_ADDR'];
		if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
			$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
		}
		$screenName = '';
		if ($request->has('screenName'))
			$screenName = ($request->input('screenName'));

		if ($request->has('deviceID') && $request->has('deviceID') != '')
			$deviceID = $request->input('deviceID');

		if (($request->has('deviceID') && $request->input('deviceID') != '') || $request->has('resourceType')) {
			$is_google_verified = '';
			if ($request->has('is_google_verified')) {
				$is_google_verified = $request->input('is_google_verified');
			}
			if ($is_google_verified == 'Y') {
				$memid = 0;
				if ($request->has('memid'))
					$memid = $request->input('memid'); //price/insights/tender	

				$isdCode = urlencode($request->input('isdCode')); //price/insights/tender	
				if ($request->has('countryCode'))
					$isdCode = urlencode($request->input('countryCode'));

				$mobileNumber = $request->input('primary_detail');

				$userType = $request->input('userType'); //new/old
				//DB::enableQueryLog();


				if ($section == 'events') {
					$ol_be = "EVT " . $resourceType;
					$primary_source = $resourceType == 'app' ? 'CAMP24' : 'CAMP13';
					$service_type = 'Events';
				} elseif ($section == 'steelmint') {
					$ol_be = "SM " . $resourceType;
					//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
					if ($screenName == 'Subscribe_CTA') {
						$primary_source = 'CAMP188';
					} elseif ($deviceType != '' && 'Registration_Page' == $screenName) {
						$primary_source = strtolower($deviceType) == 'android' ? 'CAMP162' : 'CAMP163';
					} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
						$primary_source = strtolower($deviceType) == 'android' ? 'CAMP160' : 'CAMP161';
					} else
						$primary_source = $resourceType == 'app' ? 'CAMP19' : 'CAMP165';

					$service_type = $resourceType == 'app' ? 'MA' : 'W';
					if ($screenName == 'Subscribe_CTA') {
						$service_type = 'MA';
					}
				} elseif ($section == 'coalmint' || $this->appType == 'CM') {
					$ol_be = "CM " . $resourceType;
					//$primary_source = $resourceType=='app'?'CAMP19':'CAMP1';
					if ($deviceType != '' && 'Registration_Page' == $screenName) {
						$primary_source = strtolower($deviceType) == 'android' ? 'CAMP185' : 'CAMP186';
					} elseif ($deviceType != '' && 'Get_Updates' == $screenName) {
						$primary_source = strtolower($deviceType) == 'android' ? 'CAMP183' : 'CAMP184';
					} else
						$primary_source = $resourceType == 'app' ? 'CAMP182' : 'CAMP187';

					$service_type = $resourceType == 'app' ? 'MA' : 'W';
				}


				if ($memid) { //old user
					if ($userType == 'old' && $memid > 0) {
						///check phone
						$dbresult = DB::table($_ENV['USER_TABLE'])
							->select('id')
							->where(function ($q) use ($mobileNumber) {
								$q->where('phoneno', $mobileNumber)
									->orWhere('alternate_mob_no', $mobileNumber)
									->orWhere('username', $mobileNumber);
							})
							->first();


						if (count($dbresult) > 0 && $dbresult['id'] != $memid) {
							return new JsonResponse(array("status" => array("code" => 2001, "message" => "duplicate record found!")));
						}
					}
					/*if(!empty($mobileNumber))
                        $newUser['phoneno'] = $mobileNumber;
                    if($isdCode!=''){
                        $newUser['isd_code'] = urldecode($isdCode);
                        $dbresult1 = DB::table('tbl_country')
                        ->select('id' )				
                        ->where('std_code' , urldecode($isdCode))
                        ->first();
                    
                        if (count($dbresult1) > 0 ){
                            $newUser['country'] = $dbresult1['id'] ;
                        }
                    }*/

					$newUser['is_mobile_verified'] = 1;

					//$userType=='new' &&
					if ($request->has('debug'))
						print_r($newUser);

					if ($memid > 0) {
						DB::table($_ENV['USER_TABLE'])
							->where('id', $memid)
							->update($newUser);
					}
					$userType = 'old';
				} elseif (!empty($mobileNumber) && $mobileNumber != '') {
					///check the user again for safer side
					//DB::enableQueryLog(); 
					$dbresult = DB::table($_ENV['USER_TABLE'])
						->select('id')
						->Where(function ($q) use ($mobileNumber) {
							$q->where('phoneno', $mobileNumber)
								->orWhere('alternate_mob_no', $mobileNumber)
								->orWhere('username', $mobileNumber);
						})
						->first();
					//dd(DB::getQueryLog());
					//print_r($dbresult);
					if (count($dbresult) > 0 && $dbresult['id'] != $memid && !empty($memid)) {
						return new JsonResponse(array("status" => array("code" => 2001, "message" => "duplicate record found!")));
					} elseif (count($dbresult) > 0) {
						$memid = $dbresult['id'];
						$newUser['is_mobile_verified'] = 1;

						//$userType=='new' &&
						if ($request->has('debug'))
							print_r($newUser);
						DB::table($_ENV['USER_TABLE'])
							->where('id', $memid)
							->update($newUser);
						$userType = 'old';
					} else {
						$userType = 'new';
						$newUser['username'] = $mobileNumber;
						$newUser['phoneno'] = $mobileNumber;
						$newUser['isd_code'] = urldecode($isdCode);
						$newUser['is_mobile_verified'] = 1;

						$dbresult1 = DB::table('tbl_country')
							->select('id')
							->where('std_code', urldecode($isdCode))
							->first();

						if (count($dbresult1) > 0) {
							$newUser['country'] = $dbresult1['id'];
						}
						//$newUser['isd_code'] = $isdCode;                            
						if ($request->has('debug'))
							print_r($newUser);

						$newUser['password'] = '123456';
						$newUser['ol_be'] = $ol_be;
						$newUser['main_source'] = $section . ' Registraion Page';
						$newUser['source_from'] = $resourceType == 'app' ? 'Mobile App' : 'Web';
						$newUser['ipaddress'] = $ipAddress;
						$newUser['date'] = $GLOBALS['currDateTime'];
						$newUser['primary_source'] = $primary_source;
						$newUser['lead_type'] = 'A1';

						try {
							$memid = DB::table('tbl_members')->insertGetId($newUser);
						} catch (QueryException $e) {
							dd($e);
						}
						////////visitor log id
						if ($section == 'steelmint' || $section == 'coalmint') {
							$lead_type = 'A1';
							$mood = '';
							$fudate = '';
							///if($type=='old')
							{
								//$lead_type = getLastLeadType($memid, $service_type=$f_product);
								$leadtypeArr = getLastLeadType($memid, $service_type, $dflag = 'true');
								if (isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type'] != '')
									$lead_type = $leadtypeArr['lead_type'];
								if (isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type'] != '')
									$mood = $leadtypeArr['mood'];
								if (isset($leadtypeArr['fudate']) && $leadtypeArr['fudate'] != '')
									$fudate = $leadtypeArr['fudate'];

								if ($lead_type == 'A5' || $lead_type == 'B5')
									$lead_type = 'A11';
							}

							$rm_arr = getRMForRoutingProcess($memid, $company_name = $section, $lead_type);

							if (empty($rm_arr)) {
								$rm_arr['rm_id'] = $section == "coalmint" ? 125 : 0;
								$mood = 0;
								$rm_arr['subrm_id'] = $section == "coalmint" ? 125 : 0;
								$rm_arr['first_log_id'] = $section == "coalmint" ? 0 : 0;
							}
							$f_product = $section == 'coalmint' ? 'C' : ($resourceType == 'app' ? 'MA' : 'W');
							$start_date = $GLOBALS['currDate'];
							$end_date = $GLOBALS['currDate'];
							$f_tenure = 'One Day';

							$selected_products = $resourceType == 'app' ? 'Mobile App' : 'Web';
							if ($request->has('packageID') && $request->has('packageID') != '') {
								$selected_products = $request->input('packageID');

								$dbresult2 = DB::table('tbl_packages')
									->select('*')
									->where('id', $selected_products)
									->get();

								if (count($dbresult2) > 0) {
									$tabType =  $dbresult2[0]['tabType'];
									$packageName =  $dbresult2[0]['packageName'];
									$periodName =  $dbresult2[0]['period_name'];

									$end_date = date("Y-m-d", strtotime("$start_date +$periodName months"));
									$f_tenure = (strtolower($section) == "steelmint" || strtolower($section) == "coalmint") ? 'One Year' : $periodName . ' months';
								}
							}
							$tbl_reg_logs = array(
								'memid' => $memid,
								'startdate' => $start_date,
								'enddate' => $end_date,
								'f_time' => $GLOBALS['currTime'],
								'f_product' => $f_product,
								'f_tenure' => $f_tenure,
								'status' => 'Pending',
								'selected_products' => $selected_products,
								'comments' => 'From : verifyOTP',
								'created_on' => $GLOBALS['currDateTime'],
								'lead_type' => $lead_type,
								'fudate' => $fudate,
								'rm' => $rm_arr['rm_id'],
								'subrm' => $rm_arr['subrm_id'],
								'mood' => $mood,
								'pipeline_status' => 'New',
								'routing_status' => $lead_type,
								'first_log_id' => $rm_arr['first_log_id'],
								'form_no' => $screenName
							);

							if ($request->has('debug'))
								print_r($tbl_reg_logs);
							try {
								$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
								////updateTbltbl_updated_reg_logs($memid);					
							} catch (QueryException $e) {
								dd($e);
							}
						} elseif ($section == 'events') {
							$tbl_reg_logs = array(
								'registering_id' => $memid,
								'datetime' => $GLOBALS['currDateTime'],
								'email' => $mobileNumber,
								'mobile' => $mobileNumber,
								'event_id' => $request->input('eventID')
							);

							//print_r($tbl_reg_logs);
							try {
								$_log_id = DB::table('tbl_sm_events_registration_logs')->insertGetId($tbl_reg_logs);
								makeEntryInTableFinalStatus($memid, $request->input('eventID'));
							} catch (QueryException $e) {
								dd($e);
							}
						}
					}
				} else {
					$code = 2002;
					$message = "Error : mobile no. blank.";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}
				foreach ($request->all() as $key => $subvalue) {
					$comments = $comments . " $key => " . $subvalue . " <br /> ";
				}
				$comments .= "<br> Tried to register in " . $resourceType . " <br /> ";
				$comments .= " ip => " . $ipAddress . " <br /> ";
				if ($request->has('debug'))
					print_r($comments);
				DB::table($_ENV['COMMENTS_TABLE'])->insert([
					'memid' => $memid,
					'f_date' => $GLOBALS['currDate'],
					'f_time' => $GLOBALS['currTime'],
					'comments' => "Request Service Type : " . $comments,
					'created_by' => 'self',
					'comments_for' => $section
				]);
				DB::table('tbl_campaign_history')->insert([
					'memid' => $memid,
					'created_on' => $GLOBALS['currDateTime'],
					'refral_url' => '',
					'camp_code' => $primary_source,
					'ip' => $ipAddress,
					'source' => $resourceType
				]);

				$code = 1001;
				$message = "Successfully verified";
				if ($memid > 0) {
					$result = DB::table($_ENV['USER_TABLE'])
						->select('email', 'phoneno', 'isd_code', 'name', 'job_title', 'company', 'companytype', 'city', 'state', 'country', 'pin_code', DB::raw("CONCAT(city,'-',state,'-',country ) as `selectedLocation`"), 'address')
						->where('id', $memid)
						->first();
					$is_encoded = preg_match('~%[0-9A-F]{2}~i', $result['isd_code']);
					if ($is_encoded)
						$result['isd_code'] = urldecode($result['isd_code']);
				}/*else{
                        $result = DB::table($_ENV['USER_TABLE'])
                            ->select('country')
                            ->where('id' ,$memid)
                            ->first();
                    }*/
				$countryID = $result['country'];
				if ($countryID == 0) {
					$dbresult1 = DB::table('tbl_country')
						->select('id')
						->where('std_code', urldecode($isdCode))
						->first();
					if (count($dbresult1) > 0) {
						$countryID = $dbresult1['id'];
					}
				}
				if ($countryID == 113) {
					$dblocation = DB::table('tbl_state_city')
						->select(DB::raw("CONCAT(city_id,'-',state_id,'-', 113 ) as `city_id`"), DB::raw("CONCAT(city_name,', ',state_name ) as `city_name`"))
						->where('country_id', $countryID)
						->get();
				} else {
					$dblocation = DB::table('tbl_state_city')
						->select(DB::raw("CONCAT(city_id,'-',state_id,'-', country_id ) as `city_id`"), 'city_name')
						->where('country_id', $countryID)
						->get();
				}
				$result['memid'] = $memid;
				$result['location'] = $dblocation;
				$result['userType'] = $userType;

				updateTbltbl_updated_reg_logs($memid);
				//if($userType=='new'){
				if ($section != "coalmint") {
					if ($resourceType == 'app') {
						$template_name = "1st_reg_app";
						$template_param = array("https://www.steelmint.com/web_app.php?share=profile");
					} else {
						$template_name = "1st__registration";
						$template_param = array("https://www.steelmint.com/web_app.php?source=openapp");
					}
					sendWhatsAppMessage($to = $result['isd_code'] . $result['phoneno'], $template_name, $template_param);
				}
				//}
			} else {
				$code = 2002;
				$message = "Verification failed.";
			}
		} else {
			$code = 2002;
			$message = "Access token is invalid or has expired.";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}


	public function GetuserType(Request $request)
	{
		$result = array();
		if ($request->has('mobileNumber') && $request->input('mobileNumber') != '' && !empty($request->input('mobileNumber'))) {
			$mobileNumber = $request->input('mobileNumber');
			$dbresult = DB::table("tbl_members")
				->select('id')
				->where(function ($q) use ($mobileNumber) {
					$q->where('phoneno', $mobileNumber)
						->orWhere('alternate_mob_no', $mobileNumber)
						->orWhere('username', $mobileNumber);
				})
				->first();

			if (count($dbresult) > 0 && !empty($dbresult['id'])) {
				$memid = $dbresult['id'];
				$result['memId'] = $memid;
				$result['userType'] = "old";
			} else {
				$result['memId'] = 0;
				$result['userType'] = "new";
			}
			return new JsonResponse(array("status" => array("code" => 1001, "message" => "member found in database.", "data" => $result)));
		} else {
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "Blank input")));
		}
	}

	public function getPriceSpreadSectionWiseFilters(Request $request)
	{
		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		// 		if(!$request->has('price_section_type')){
		// 			 return new JsonResponse(array("code" => 2001, "message" => "invalid section type"));
		// 		}
		// 		
		$price_section_type = strtolower($request->input('price_section_type'));

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		/*if($this->appType == 'CM') //if coalmint, show all coal related records only
			$where_condition = " WHERE commodityID = 401 AND  subCommodityID NOT IN('') ";		
		else*/
		$where_condition = " WHERE 1 AND r.subCommodityID NOT IN('')  ";

		if ($request->has('market')) {
			$market = strtolower($request->input('market'));
			$where_condition .= " and FIND_IN_SET('" . $market . "', mst.f_market)  ";
		}
		include_once('/home/steelmin/public_html/hf.php'); {
			$sqlQry = "
                SELECT r.commodityID ,
                       r.subCommodityID,
                    r.regionID,
                    r.countryID as subRegionID,                    
                    r1.itemName as commodityName,
                    r2.itemName as subCommodityName,
                    r3.itemName as regionName,
                    r4.itemName as subRegionName
                FROM `tbl_spread_master` as r
                inner join tbl_op_commodity_master as mst ON r.id2= mst.id
                left join `tbl_region_commodity_master` as r1 ON r1.ID=r.commodityID
                left join `tbl_region_commodity_master` as r2 ON r2.ID=r.subCommodityID
                left join `tbl_region_commodity_master` as r3 ON r3.ID=r.regionID
                left join `tbl_region_commodity_master` as r4 ON r4.ID=r.countryID
                $where_condition";
		}
		$sqlQryC = $sqlQry . " group by r.subCommodityID, r.countryID 
					order by r1.parentID, r1.f_order_by, r2.parentID, r2.f_order_by, r3.f_order_by, r4.f_order_by, subCommodityName";

		$resultData = DB::select($sqlQryC);
		$commodityID = 0;
		$m = 0;
		foreach ($resultData as $data):
			if ($commodityID != $data['commodityID']) {
				$m++;
				$commodityID = $data['commodityID'];
				$result['commodity'][$m - 1] = array(
					"id" => $data['commodityID'],
					"name" => $data['commodityName'],
					"isSelectable" => 'n'
				);

				$c = 0;
				$subCommodityID = '';
			}
			///echo '<prE>', $m, '-',$c, '-',$commodityID, '-',$data['subCommodityID'], '-','</pre>'; 
			if ($subCommodityID != $data['subCommodityID']) {
				$c++;
				$subCommodityID = $data['subCommodityID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1] = array(
					"id" => $data['subCommodityID'],
					"name" => $data['subCommodityName'],
					"isSelectable" => 'y'
				);

				$regionID = 0;
				$r = 0;
			}

			if ($regionID != $data['regionID']) {
				$r++;
				$regionID = $data['regionID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1] = array(
					"id" => $data['regionID'],
					"name" => $data['regionName'],
					"isSelectable" => 'y'
				);

				$subRegionID = 0;
				$sr = 0;
			}


			if ($subRegionID != $data['regionID']) {
				$sr++;
				$subRegionID = $data['subRegionID'];
				$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
					"id" => $data['subRegionID'],
					"name" => $data['subRegionName'],
					"isSelectable" => 'y'
				);
			}
		endforeach;
		$sqlQryR = $sqlQry . " group by r.regionID, r.countryID, r.subCommodityID 
				  order by r3.parentID, r3.f_order_by, r4.parentID, r4.f_order_by, r1.f_order_by, r.regionID, r.countryID, r2.f_order_by ";
		$resultData = DB::select($sqlQryR);
		$regionID = 0;
		$m = 0;
		foreach ($resultData as $data):
			if ($regionID != $data['regionID']) {
				$m++;
				$regionID = $data['regionID'];
				$result['region'][$m - 1] = array(
					"id" => $data['regionID'],
					"name" => $data['regionName'],
					"isSelectable" => 'n'
				);

				$c = 0;
				$subRegionID = '';
			}

			if ($subRegionID != $data['subRegionID']) {
				$c++;
				$subRegionID = $data['subRegionID'];
				$result['region'][$m - 1]['sub_region'][$c - 1] = array(
					"id" => $data['subRegionID'],
					"name" => $data['subRegionName'],
					"isSelectable" => 'y'
				);

				$commodityID = 0;
				$r = 0;
			}

			if ($commodityID != $data['commodityID']) {
				$r++;
				$commodityID = $data['commodityID'];
				$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1] = array(
					"id" => $data['commodityID'],
					"name" => $data['commodityName'],
					"isSelectable" => 'y'
				);

				$subCommodityID = 0;
				$sr = 0;
			}


			if ($subCommodityID != $data['subCommodityID']) {
				$sr++;
				$subCommodityID = $data['subCommodityID'];
				$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
					"id" => $data['subCommodityID'],
					"name" => $data['subCommodityName'],
					"isSelectable" => 'y'
				);
			}
		endforeach;
		$result['dataType'] = array(
			array("name" => "Imp", "value" => "cnf"),
			array("name" => "Exp", "value" => "fob"),
			array("name" => "Dom", "value" => "f")
		);

		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}


	public function getCommodityDetails(Request $request)
	{
		$result = array();
		if (!$request->has('itemID')  || !$request->has('section')) {
			return new JsonResponse(array("code" => 2001, "message" => "item id/section  blank", "allowed_market" => $result));
		}
		$itemID = $request->input('itemID');
		$section = $request->input('section');

		if (strtolower($section) == 'insights') {
			$tbl = 'tbl_news_post';
			$where_condition = " post_id = $itemID  ";
		}
		if (strtolower($section) == 'intel') {
			$tbl = 'intel';
			$where_condition = " itemId = $itemID  ";
		}
		if ($tbl == '')
			return new JsonResponse(array("code" => 2001, "message" => "Table name blank.", "allowed_market" => $result));

		$sqlQry = "
            SELECT r.commodityID ,
                    r.subCommodityID                    
            FROM `" . $tbl . "` as r where              
            $where_condition";
		$resultData = DB::select($sqlQry);

		foreach ($resultData as $data):
			$result['commodityID'] = $data['commodityID'];
			$result['subCommodityID'] = $data['subCommodityID'];
		endforeach;
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "allowed_market" => $result));
	}

	public function getPriceSectionWiseFiltersBM(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		// 		if(!$request->has('price_section_type')){
		// 			 return new JsonResponse(array("code" => 2001, "message" => "invalid section type"));
		// 		}

		//$price_section_type = strtolower($request->input('price_section_type'));
		$price_section_type = 'spot_prices';

		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		/* if($resourceType=='web')
			$where_condition=" WHERE category <> 'Non Ferrous' and showOnlyInSteelmint=1 and continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') ";
		else
			$where_condition=" WHERE showOnlyInSteelmint=1 and continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') ";
        */
		if ($resourceType == 'web')
			$where_condition = " WHERE category <> 'Non Ferrous' and continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') ";
		else
			$where_condition = " WHERE  continue_or_discontinue=1 AND category<>'INDEX' and sub_category NOT IN('') ";
		///add this condition when anamika work will start for non Ferrous and category <> 'Non Ferrous'  when NFS is+

		$market_arr =
			array(
				'ferrous' => 'Ferrous Metals',
				'non-ferrous' => 'Non Ferrous',
				'coal' => 'Coal & Energy',
				'scrap-recycling' => 'Scrap Recycling',
				'agriculture' => 'Agriculture',
				'future_prices' => 'Future Prices'
			);
		$final_arr = array();
		$market_key = array('ferrous', 'non-ferrous', 'coal', 'scrap-recycling', 'agriculture');
		foreach ($market_arr as $key => $val) {
			if (in_array($key, $market_key))
				$where_condition_mkt = " and FIND_IN_SET('$key', f_market) and price_section_type like '%$price_section_type%'  ";
			else
				$where_condition_mkt = " and price_section_type like '%$key%'  ";
			$sqlQry = "(
            SELECT id 
            FROM `tbl_dom_master` 
            $where_condition
            $where_condition_mkt
            )	
            ";
			$sqlQry .= " union all (";
			$sqlQry .= "
            SELECT id
            FROM `tbl_exim_master` 
            $where_condition 
            $where_condition_mkt
            ";

			$sqlQry .= ") union all (";
			$sqlQry .= "
            SELECT id
            FROM `tbl_global_dom_master` 
            $where_condition
            $where_condition_mkt
            )";
			//echo $sqlQry . "<hr>";
			include_once('/home/steelmin/public_html/hf.php');
			$relIDs = qryToCommaSepString($sqlQry);

			$result = array();
			if ($relIDs == '')
				$relIDs = 0;
			$where_condition1 = " WHERE r.relation_id in ($relIDs) and continue_or_discontinue=1 AND category<>'INDEX' and product NOT IN('') and commodityID > 0 and regionID > 0  ";

			$sqlQry = ""; {
				$sqlQry .= "
                SELECT r.commodityID ,
                    case 
                        when r.commodityID=413 then r.subSubCommodityID
                        else r.subCommodityID
                    end as subCommodityID,
                    regionID,
                    r.countryID as subRegionID,
                    r.f_cnf_fob,
                        r1.itemName as commodityName,
                    case 
                        when r.commodityID=413 then r21.itemName
                        else r2.itemName
                    end as subCommodityName,
                    r3.itemName as regionName,
                    r4.itemName as subRegionName
                FROM `tbl_price_static` as r
                left join `tbl_region_commodity_master` as r1 ON r1.ID=r.commodityID
                left join `tbl_region_commodity_master` as r2 ON r2.ID=r.subCommodityID
                left join `tbl_region_commodity_master` as r21 ON r21.ID=r.subSubCommodityID
                left join `tbl_region_commodity_master` as r3 ON r3.ID=r.regionID
                left join `tbl_region_commodity_master` as r4 ON r4.ID=r.countryID
                $where_condition1";
			}
			$sqlQryC = $sqlQry . " group by subCommodityID, subSubCommodityID, countryID 
                        order by r1.parentID, r1.f_order_by, r2.parentID, r2.f_order_by, r21.f_order_by, r.f_order_by, r3.f_order_by, r4.f_order_by, subCommodityName"; //
			//echo $sqlQryC . "<hr>";
			$resultData = DB::select($sqlQryC);
			$commodityID = 0;
			$m = 0;
			foreach ($resultData as $data):
				if ($commodityID != $data['commodityID']) {
					$m++;
					$commodityID = $data['commodityID'];
					$result['commodity'][$m - 1] = array(
						"id" => $data['commodityID'],
						"name" => $data['commodityName'],
						"isSelectable" => 'n'
					);

					$c = 0;
					$subCommodityID = '';
				}

				if ($subCommodityID != $data['subCommodityID']) {
					$c++;
					$subCommodityID = $data['subCommodityID'];
					$result['commodity'][$m - 1]['sub_commodity'][$c - 1] = array(
						"id" => $data['subCommodityID'],
						"name" => $data['subCommodityName'],
						"isSelectable" => 'y'
					);

					$regionID = 0;
					$r = 0;
				}

				if ($regionID != $data['regionID']) {
					$r++;
					$regionID = $data['regionID'];
					$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1] = array(
						"id" => $data['regionID'],
						"name" => $data['regionName'],
						"isSelectable" => 'y'
					);

					$subRegionID = 0;
					$sr = 0;
				}


				if ($subRegionID != $data['regionID']) {
					$sr++;
					$subRegionID = $data['subRegionID'];
					$result['commodity'][$m - 1]['sub_commodity'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
						"id" => $data['subRegionID'],
						"name" => $data['subRegionName'],
						"isSelectable" => 'y'
					);
				}
			endforeach;

			$sqlQryR = $sqlQry . " group by regionID, countryID, subCommodityID, subSubCommodityID 
                    order by r3.parentID, r3.f_order_by, r4.parentID, r4.f_order_by, r1.f_order_by, regionID, countryID, r2.f_order_by ";
			$resultData = DB::select($sqlQryR);
			$regionID = 0;
			$m = 0;
			foreach ($resultData as $data):
				if ($regionID != $data['regionID']) {
					$m++;
					$regionID = $data['regionID'];
					$result['region'][$m - 1] = array(
						"id" => $data['regionID'],
						"name" => $data['regionName'],
						"isSelectable" => 'n'
					);

					$c = 0;
					$subRegionID = '';
				}
				if ($subRegionID != $data['subRegionID']) {
					$c++;
					$subRegionID = $data['subRegionID'];
					$result['region'][$m - 1]['sub_region'][$c - 1] = array(
						"id" => $data['subRegionID'],
						"name" => $data['subRegionName'],
						"isSelectable" => 'y'
					);

					$commodityID = 0;
					$r = 0;
				}

				if ($commodityID != $data['commodityID']) {
					$r++;
					$commodityID = $data['commodityID'];
					$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1] = array(
						"id" => $data['commodityID'],
						"name" => $data['commodityName'],
						"isSelectable" => 'y'
					);

					$subCommodityID = 0;
					$sr = 0;
				}


				if ($subCommodityID != $data['subCommodityID']) {
					$sr++;
					$subCommodityID = $data['subCommodityID'];
					$result['region'][$m - 1]['sub_region'][$c - 1]['filters'][$r - 1]['sub_filters'][$sr - 1] = array(
						"id" => $data['subCommodityID'],
						"name" => $data['subCommodityName'],
						"isSelectable" => 'y'
					);
				}
			endforeach;

			$final_arr['commodity'][] =
				array(
					"market_id" => $key,
					"name" => $val,
					"data" => $result['commodity']
				);
			$final_arr['region'][] =
				array(
					"market_id" => $key,
					"name" => $val,
					"data" => $result['region']
				);
		}

		$final_arr['dataType'] = array(
			array("name" => "Imp", "value" => "cnf"),
			array("name" => "Exp", "value" => "fob"),
			array("name" => "Dom", "value" => "f")
		);
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $final_arr));
	}

	public function getArrayBM(Request $request)
	{

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if ($request->has('app_type'))
			$app_type = strtolower($request->input('app_type'));
		else
			$app_type = "SM";
		$place = '';
		$itemType = '';
		$section = '';
		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($request->has('place'))
			$place = strtolower($request->input('place'));

		if ($request->has('itemType'))
			$itemType = strtolower($request->input('itemType'));

		if ($request->has('section'))
			$section = strtolower($request->input('section'));

		//START: form key for redis using above parameters
		$redisKeyName = '';
		if ($resourceType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $resourceType;
			else
				$redisKeyName .= "_" . $resourceType;
		}

		if ($deviceType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $deviceType;
			else
				$redisKeyName .= "_" . $deviceType;
		}

		if ($app_type !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $app_type;
			else
				$redisKeyName .= "_" . $app_type;
		}


		if ($place !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $place;
			else
				$redisKeyName .= "_" . $place;
		}

		if ($itemType !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $itemType;
			else
				$redisKeyName .= "_" . $itemType;
		}

		if ($section !== '') {
			if ($redisKeyName == '')
				$redisKeyName = $section;
			else
				$redisKeyName .= "_" . $section;
		}
		//END: form key for redis using above parameters

		//check if the above key exists in redis DB
		//if yes, then return the same
		//include_once "/home/steelmin/public_html/redisFn.php";
		/* if(isKeyExistsInRedis($redisKeyName)){
		    return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> json_decode(getKeyValueFromRedis($redisKeyName), true)));
		} */

		if ($resourceType == 'web' && $section == 'event') {
			$resultset = $this->refDataBM($resourceType, $itemType, $section = 'event', $place = "WEB_EVENTS_LANDING_LISTING_CMBBOX", $otherCondition = '', '', $app_type);
			$result = $resultset['WEB_EVENTS_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && $section == 'tender') {
			$resultset = $this->refDataBM($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_TENDER_LISTING_FILTER'];
		} elseif ($resourceType == 'web' && $section == 'insight') {
			$resultset = $this->refDataBM($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_INSIGHT_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && $section == 'price') {
			$resultset = $this->refDataBM($resourceType, $itemType, $section, '', '', '', $app_type);
			$result = $resultset['WEB_PRICE_LANDING_LISTING_CMBBOX'];
		} elseif ($resourceType == 'web' && ($place != '' || $itemType != ''))
			$result = $this->refDataFilter($resourceType, $itemType, $section, $place);
		else
			$result = $this->refDataBM($resourceType, '', '', '', '', $deviceType, $app_type);

		//set $redisKeyName in redis with $result for one day
		//after every 24 hours it will expire
		//setInRedis($redisKeyName, json_encode($result), 86400);

		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $result));
	}

	public function appPopupContent(Request $request)
	{
		$result = file_get_contents("/home/steelmin/public_html/v2019_bm/Json/appPopupContent.json");
		$final_arr = json_decode($result);
		// return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $final_arr));
		$final_arr_1 = array();
		foreach ($final_arr as $key => $val) {
			$final_arr_1[] = $val;
		}
		return new JsonResponse(array("status" => array("code" => 1001, "message" => "success"), "data" => $final_arr_1));
	}

	public function storeSearchData(Request $request)
	{
		if ($request->has('f_search_term')) {
			$f_date = $request->has('f_date') ? date("Y-m-d", strtotime($request->input('f_date'))) : null;
			$f_time = $request->input('f_time', null);
			$memid = $request->input('memid', null);
			$f_section = $request->input('f_section', null);
			$f_search_term = $request->input('f_search_term', null);
			$platform = $request->input('platform', null);

			DB::table('tbl_searches')->insert(
				[
					'f_date' => $f_date,
					'f_time' => $f_time,
					'memid' => $memid,
					'f_section' => $f_section,
					'f_search_term' => $f_search_term,
					'platform' => $platform,
					'id' => NULL
				]
			);
			return new JsonResponse(array("status" => array("code" => 1001, "message" => "success")));
		} else
			return new JsonResponse(array("status" => array("code" => 2001, "message" => "No data provided.")));
	}
	public function participantLead(Request $request)
	{
		include_once('/home/steelmin/public_html/hf.php');
		/*
		// ✅ Validate input
		$validated = $request->validate([
			'name' => 'required|string|max:255',
			'company_name' => 'required|string|max:255',
			'designation' => 'required|string|max:255',
			'phone_no' => 'required|string|max:20',
			'event_id' => 'required|integer',
			'country' => 'required|string|max:10',
            'isd_code' => 'required|string|max:10'
		]);
		*/
		// ✅ Validate input
		$validator = Validator::make($request->all(), [
			'name' => 'required|string|max:255',
			'company_name' => 'required|string|max:255',
			'designation' => 'required|string|max:255',
			'phone_no' => 'required|string|max:20',
			'event_id' => 'required|integer',
			'country' => 'required|string|max:10',
			'isd_code' => 'required|string|max:10'
		]);

		if ($validator->fails()) {
			return response()->json([
				'status' => 'error',
				'message' => 'All fields are mandatory. Kindly provide all the necessary information.'
				// 				'memid' => 0,
				// 				'data' => ''
			]);
		}


		$validated = $request->only([
			'name',
			'company_name',
			'designation',
			'phone_no',
			'event_id',
			'country',
			'isd_code'
		]);

		$campCode = $request->input('camp_code');
		//$campCode = $validated['camp_code'];

		if ($campCode === null || trim($campCode) === '') {
			$campCode = 'CAMP219';
		}

		$mobileNumber = $validated['phone_no'];
		$eventId = $validated['event_id'];
		$memid = 0;

		$currDateTime =  date("Y-m-d H:i:s");
		$ipAddress = $_SERVER['REMOTE_ADDR'];
		$refralUrl = $_SERVER['HTTP_REFERER'] ?? '';

		// ✅ Check if user already exists
		$existingRecord = DB::table($_ENV['USER_TABLE'])
			->where(function ($q) use ($mobileNumber) {
				$q->where('phoneno', $mobileNumber)
					->orWhere('alternate_mob_no', $mobileNumber)
					->orWhere('username', $mobileNumber);
			})
			->first();

		if ($existingRecord) {
			$memid = $existingRecord['id'];
		} else {
			// ✅ Insert if not found		
			$password = Str::upper(Str::random(10));
			$newUser = [
				'name'           => $validated['name'],
				'company'        => $validated['company_name'],
				'job_title'      => $validated['designation'],
				'phoneno'        => $mobileNumber,
				'username'       => $mobileNumber,
				'password'       => $password,
				'ol_be'          => 'EVT FE',
				'main_source'    => 'web',
				'source_from'    => 'EVENTS_DOWNLOAD_PARTICIPANTS_LIST',
				'ipaddress'      => $ipAddress,
				'date'           => $currDateTime,
				'primary_source' => $campCode,
				'lead_type'      => 'A1',
				'country'        => $validated['country'],
				'countrycode'    => $validated['isd_code']
			];
			$memid = DB::table('tbl_members')->insertGetId($newUser);
		}


		DB::table('tbl_campaign_history')->insert([
			'camp_code'   => $campCode,
			'refral_url'  => $refralUrl,
			'source'      => 'web',
			'memid'       => $memid,
			'ip'          => $ipAddress,
			'created_on'  => $currDateTime,
			'eventId'     => $eventId,
		]);

		$commentText =
			"Name => " . $validated['name'] . "<br>" .
			"Company => " . $validated['company_name'] . "<br>" .
			"Designation => " . $validated['designation'] . "<br>" .
			"Country => " . $validated['country'] . "<br>" .
			"ISD Code => " . $validated['isd_code'] . "<br>" .
			"Phone =>" . $validated['phone_no'] . "<br>" .
			"Event ID => " . $validated['event_id'];

		DB::table('tbl_comments')->insert([
			'memid'        => $memid,
			'f_date'       => date("Y-m-d"),
			'f_time'       => date("H:i:s"),
			'comments'     => $commentText,
			'created_by'   => 'self',
			'comments_for' => 'EV',
		]);

		// ✅ Call final status function for new user
		makeEntryInTableFinalStatus($memid, $eventId);

		return response()->json([
			'status' => 'success',
			'message' => 'Details submitted successfully!'
			//'memid' => $memid
			//'data' => $validated
		]);
	}


	public function insertVisitorPass(Request $request)
	{
		// Phone already comes with ISD from intl-tel-input
		$phone = trim($request->phone_no);

		/* =============================
		BASIC VALIDATION
		============================= */
		if (
			empty($request->person_name) ||
			empty($request->company_name) ||
			empty($phone) ||
			empty($request->email)
		) {
			return response()->json([
				"status" => 0,
				"msg"    => "Required fields missing"
			]);
		}

		/* =============================
		DUPLICATE PHONE CHECK
		============================= */
		$phoneExists = DB::table('tbl_visitor_passes')
			->where('phone', $phone)
			->exists();

		if ($phoneExists) {
			return response()->json([
				"status" => 0,
				"msg"    => "Phone number already exists"
			]);
		}

		/* =============================
		DUPLICATE EMAIL CHECK
		============================= */
		$emailExists = DB::table('tbl_visitor_passes')
			->where('email', $request->email)
			->exists();

		if ($emailExists) {
			return response()->json([
				"status" => 0,
				"msg"    => "Email already exists"
			]);
		}

		/* =============================
		INSERT DATA
		============================= */
		DB::table('tbl_visitor_passes')->insert([
			'person_name'  => $request->person_name,
			'company_name' => $request->company_name,
			'phone'        => $phone, // +91XXXXXXXXXX
			'email'        => $request->email,
			'created_at'   => date("Y-m-d H:i:s")
		]);

		if (!empty($request->email)) {
			$email  = $request->email;
			$message  = "Dear $request->person_name, <br/> <br/> Thank you for registering for the Visitor Pass. Your visitor badge can be collected from the registration desk at the Expo. <br>
			<div style='background-color:#fff4e5; padding:12px; margin:12px 0;'>
			⚠️ <strong>Note:</strong> Access is limited to the Visitor area only.
			</div> <br>
			Regards,<br>BigMint Events Team, ";
			include_once("/home/steelmin/public_html/mf.php");
			//$email = 'anamika@bigmint.co';
			sendSMMail($message, $email, $name = 'BigMint Events', "BigMint Events : Your Visitor Details have been Submitted", $attachment = "", $from_email = 'events@bigmint.co', $from_name = 'BigMint Events', $reply_to = 'events@bigmint.co');
		}
		return response()->json([
			"status" => 1,
			"msg" => "Visitor details have been saved successfully. Thank you for registering with us!"
		]);
	}
}
