<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Controllers\EbayDataController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Artisan;
use Carbon\Carbon;
use PHPShopify;
use Mail;
use Illuminate\Support\Facades\Storage;
use App\User;
use App\ShopifyStore;
use App\StoreCronJob;
use App\Mail\WelcomeEmail;
use App\Helpers\AppHelper;
use App\AmazonAccount;
use App\Profile;
use App\EbayCategory;
use Illuminate\Support\Facades\Log;
use App\Helpers\mail2user;

class ProfileController extends Controller{

	public $shopifyStore = null;
	
	public function __construct(Request $request){
	}

	public function index(Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$fetch_all = $request->input("fetch_all");
			$profiles = ($fetch_all == 1) ? $shopifyStore->profiles()->get() : $shopifyStore->profiles()->paginate(10);
			return response()->json($profiles,200);
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

// 	public function save(Request $request){
// 	       Log::info(" category  ".$request);
// 		$shopifyStore = AppHelper::getShopifyStore($request);
// 		if($shopifyStore){
// 			$update_install_step = false;
// 			if($request->has("update_install_step")) $update_install_step = (bool) $request->input("update_install_step");

// 			$validationRules = [
// 				'name' => 'required|unique:tenants.profiles',
// 				'ebay_category_1' => 'required'
// 			];
// 			$validator = Validator::make($request->all(),$validationRules);
// 			if($validator->fails()){
// 				return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
// 			}
// 			$item_specifics = ($request->has("item_specifics")) ? $request->input("item_specifics") : [];
// 			$item_specifics2 = ($request->has("item_specifics2")) ? $request->input("item_specifics2") : [];

// 			$ebayDataController = new EbayDataController();

// 			$ebayCategory1 = EbayCategory::select('id','category_tree_name','category_attributes','ebay_category_id')->find($request->input("ebay_category_1"));
// 			if($ebayCategory1){
// 				$category_attributes = json_decode($ebayCategory1->category_attributes,true);
// 				if(!$category_attributes){
// 					$category_attributes = $ebayDataController->getEbayCategorySpecifics($ebayCategory1->ebay_category_id,$ebayCategory1->ebay_site);
// 				}
// 				if($category_attributes){
// 					$requiredFields = [];
// 					foreach($category_attributes as $category_attribute){
// 						$cfield = $category_attribute["name"];
// 						if($category_attribute["min_values"] > 0){
// 							if(!$item_specifics || !isset($item_specifics[$cfield]) || !$item_specifics[$cfield]){
// 								$requiredFields[] = $cfield;
// 							}
// 						}
// 					}
// 					if($requiredFields){
// 						$cerrors = implode(",",$requiredFields);
// 						return response()->json(['status' => 'error','msg' => 'please fill required category fields : '.$cerrors],406);
// 					}
// 				}
// 			}



// 			$is_default_profile = (int) $request->input("is_default_profile");
// 			if($is_default_profile){
// 				$dprofile = $shopifyStore->profiles()->where("is_default_profile","1")->first();
// 				if($dprofile){
// 					$dprofile->is_default_profile = 0;
// 					$dprofile->save();
// 				}
// 			}

// 			$profileData = $request->all();
// 			$profileData["trim_title"] = ($request->input("trim_title")) ? 1 : 0;
// 			$profileData["is_default_profile"] = $is_default_profile;
// 			$profileData["store_id"] = $shopifyStore->id;
// 			$profileData["user_id"] = $shopifyStore->user->id;

			

// 			if($request->has("item_specifics")) $profileData["item_specifics"] = json_encode($request->input("item_specifics"));
// 			if($request->has("item_specifics2")) $profileData["item_specifics2"] = json_encode($request->input("item_specifics2"));
			
// 			if($request->has("domestic_ship_additional_services")) $profileData["domestic_ship_additional_services"] = json_encode($request->input("domestic_ship_additional_services"));
// 			if($request->has("intl_ship_additional_services")) $profileData["intl_ship_additional_services"] = json_encode($request->input("intl_ship_additional_services"));
// 			//if($request->has("ship_global_locations")) $profileData["ship_global_locations"] = json_encode($request->input("ship_global_locations"));
// 			if($request->has("payment_methods")) $profileData["payment_methods"] = json_encode($request->input("payment_methods"));
// 			if($request->has("intl_locations1")) $profileData["intl_locations1"] = json_encode($request->input("intl_locations1"));
			

// 			$profile = $shopifyStore->profiles()->create($profileData);
// 			if($profile){
// 				if($update_install_step && $shopifyStore->install_step == 3){
// 					$shopifyStore->install_step = 4;
// 					$shopifyStore->save();
// 				}
// 				return response()->json(['status' => 'success','msg' => 'profile added successfully','profile' => $profile->toArray()],200);
// 			}
// 			else{
// 				return response()->json(['status' => 'error','msg' => 'profile not added, please try again'],406);
// 			}
// 		}
// 		return response()->json(['status' => 'error','msg' => "invalid request"],403);
// 	}

public function save(Request $request) {

        Log::info(" category  " . $request);
        $shopifyStore = AppHelper::getShopifyStore($request);
        if ($shopifyStore) {
            $update_install_step = false;
            if ($request->has("update_install_step")) $update_install_step = (bool)$request->input("update_install_step");
            $validationRules = ['name' => 'required|unique:tenants.profiles',
            // 'ebay_category_1' => 'required'
            ];
            $validator = Validator::make($request->all(), $validationRules);
            if ($validator->fails()) {
                return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors() ], 406);
            }
            $item_specifics = ($request->has("item_specifics")) ? $request->input("item_specifics") : [];
            $item_specifics2 = ($request->has("item_specifics2")) ? $request->input("item_specifics2") : [];
            $ebayDataController = new EbayDataController();
            $ebayCategory1 = EbayCategory::select('id', 'category_tree_name', 'category_attributes', 'ebay_category_id')->find($request->input("ebay_category_1"));
            if ($ebayCategory1) {
                $category_attributes = json_decode($ebayCategory1->category_attributes, true);
                if (!$category_attributes) {
                    $category_attributes = $ebayDataController->getEbayCategorySpecifics($ebayCategory1->ebay_category_id, $ebayCategory1->ebay_site);
                }
                if ($category_attributes) {
                    $requiredFields = [];
                    foreach ($category_attributes as $category_attribute) {
                        $cfield = $category_attribute["name"];
                        if ($category_attribute["min_values"] > 0) {
                            if (!$item_specifics || !isset($item_specifics[$cfield]) || !$item_specifics[$cfield]) {
                                $requiredFields[] = $cfield;
                            }
                        }
                    }
                    if ($requiredFields) {
                        $cerrors = implode(",", $requiredFields);
                        return response()->json(['status' => 'error', 'msg' => 'please fill required category fields : ' . $cerrors], 406);
                    }
                }
            }
            $is_default_profile = (int)$request->input("is_default_profile");
            if ($is_default_profile) {
                $dprofile = $shopifyStore->profiles()->where("is_default_profile", "1")->first();
                if ($dprofile) {
                    $dprofile->is_default_profile = 0;
                    $dprofile->save();
                }
            }
            $profileData = $request->all();
            $profileData["trim_title"] = ($request->input("trim_title")) ? 1 : 0;
            $profileData["is_default_profile"] = $is_default_profile;
            $profileData["store_id"] = $shopifyStore->id;
            $profileData["user_id"] = $shopifyStore->user->id;
            if ($request->has("item_specifics")) $profileData["item_specifics"] = json_encode($request->input("item_specifics"));
            if ($request->has("item_specifics2")) $profileData["item_specifics2"] = json_encode($request->input("item_specifics2"));
            if ($request->has("domestic_ship_additional_services")) $profileData["domestic_ship_additional_services"] = json_encode($request->input("domestic_ship_additional_services"));
            if ($request->has("intl_ship_additional_services")) $profileData["intl_ship_additional_services"] = json_encode($request->input("intl_ship_additional_services"));
            //if($request->has("ship_global_locations")) $profileData["ship_global_locations"] = json_encode($request->input("ship_global_locations"));
            if ($request->has("payment_methods")) $profileData["payment_methods"] = json_encode($request->input("payment_methods"));
            if ($request->has("intl_locations1")) $profileData["intl_locations1"] = json_encode($request->input("intl_locations1"));
            $profile = $shopifyStore->profiles()->create($profileData);
            
            if ($profile) {
                // print_r($update_install_step);
                // print_r($shopifyStore->install_step);
                // if ($update_install_step && $shopifyStore->install_step == 2) {
                if ($shopifyStore->install_step == 2) {
                    $shopifyStore->install_step = 3;
                    $shopifyStore->save();
                }
                return response()->json(['status' => 'success', 'msg' => 'profile added successfully', 'profile' => $profile->toArray() ], 200);
            } else {
                return response()->json(['status' => 'error', 'msg' => 'profile not added, please try again'], 406);
            }
        }
        return response()->json(['status' => 'error', 'msg' => "invalid request"], 403);
    }
    
// 	public function show($id,Request $request){
// 		$shopifyStore = AppHelper::getShopifyStore($request);
// 		if($shopifyStore){
// 			$profile = $shopifyStore->profiles()->find($id);
// 			if($profile){
// 				$ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid","1")->first();

// 				$profile->payment_methods = ($profile->payment_methods) ? json_decode($profile->payment_methods,true) : array();
// 				$profile->intl_locations1 = ($profile->intl_locations1) ? json_decode($profile->intl_locations1,true) : array();

// 				$profile->item_specifics = ($profile->item_specifics) ? json_decode($profile->item_specifics,true) : array();
// 				$profile->item_specifics2 = ($profile->item_specifics2) ? json_decode($profile->item_specifics2,true) : array();

// 				$profile->domestic_ship_additional_services = ($profile->domestic_ship_additional_services) ? json_decode($profile->domestic_ship_additional_services,true) : array();
// 				$profile->intl_ship_additional_services = ($profile->intl_ship_additional_services) ? json_decode($profile->intl_ship_additional_services,true) : array();

// 				$ebayDataController = new EbayDataController();

// 				if($profile->ebay_category_1 > 0){
// 					$ebay_category_1 = EbayCategory::select('id','category_tree_name','category_attributes','ebay_category_id')->find($profile->ebay_category_1);
// 					if($ebay_category_1){
// 						$profile->ebay_category_1 = $ebay_category_1;
// 						$category_attributes = json_decode($profile->ebay_category_1->category_attributes,true);
// 						if(!$category_attributes || !isset($category_attributes[0]["min_values"])){
// 							$category_attributes = $ebayDataController->getEbayCategorySpecifics($profile->ebay_category_1->ebay_category_id,$ebayAccount->siteid);
// 							$profile->ebay_category_1->category_attributes = $category_attributes;
// 						}
// 						else $profile->ebay_category_1->category_attributes = $category_attributes;
// 					}
// 				}

// 				if($profile->ebay_category_2 > 0){
// 					$ebay_category_2 = EbayCategory::select('id','category_tree_name','category_attributes','ebay_category_id')->find($profile->ebay_category_2);
// 					if($ebay_category_2){
// 						$profile->ebay_category_2 = $ebay_category_2;
// 						$category_attributes = json_decode($profile->ebay_category_2->category_attributes,true);

// 						if(!$category_attributes || !isset($category_attributes[0]["min_values"])){
// 							$category_attributes = $ebayDataController->getEbayCategorySpecifics($profile->ebay_category_2->ebay_category_id,$ebayAccount->siteid);
// 							$profile->ebay_category_2->category_attributes = $category_attributes;
// 						}
// 						else $profile->ebay_category_2->category_attributes = $category_attributes;
// 					}
// 				}

// 				if($profile->store_category > 0){
// 					//$profile->store_category = $ebayAccount->ebayStoreCategories()->find($profile->store_category);
// 				}


// 				return response()->json($profile,200);
// 			}
// 			else{
// 				return response()->json(['status' => 'error','msg' => "not found"],404);
// 			}
// 		}
// 		return response()->json(['status' => 'error','msg' => "invalid request"],403);
// 	}

 public function show($id, Request $request) {
        $shopifyStore = AppHelper::getShopifyStore($request);
        if ($shopifyStore) {
            $profile = $shopifyStore->profiles()->find($id);
            if ($profile) {
                $ebayAccount = $shopifyStore->ebayAccounts()->where("is_valid", "1")->first();
                $profile->payment_methods = ($profile->payment_methods) ? json_decode($profile->payment_methods, true) : array();
                $profile->intl_locations1 = ($profile->intl_locations1) ? json_decode($profile->intl_locations1, true) : array();
                $profile->item_specifics = ($profile->item_specifics) ? json_decode($profile->item_specifics, true) : array();
                $profile->item_specifics2 = ($profile->item_specifics2) ? json_decode($profile->item_specifics2, true) : array();
                $profile->domestic_ship_additional_services = ($profile->domestic_ship_additional_services) ? json_decode($profile->domestic_ship_additional_services, true) : array();
                $profile->intl_ship_additional_services = ($profile->intl_ship_additional_services) ? json_decode($profile->intl_ship_additional_services, true) : array();
                $ebayDataController = new EbayDataController();
                if ($profile->ebay_category_1 > 0) {
                    $ebay_category_1 = EbayCategory::select('id', 'category_tree_name', 'category_attributes', 'ebay_category_id')->find($profile->ebay_category_1);
                    if ($ebay_category_1) {
                        $profile->ebay_category_1 = $ebay_category_1;
                        $category_attributes = json_decode($profile->ebay_category_1->category_attributes, true);
                        if (!$category_attributes || !isset($category_attributes[0]["min_values"])) {
                            $category_attributes = $ebayDataController->getEbayCategorySpecifics($profile->ebay_category_1->ebay_category_id, $ebayAccount->siteid);
                            $profile->ebay_category_1->category_attributes = $category_attributes;
                        } else $profile->ebay_category_1->category_attributes = $category_attributes;
                    }
                }
                if ($profile->ebay_category_2 > 0) {
                    $ebay_category_2 = EbayCategory::select('id', 'category_tree_name', 'category_attributes', 'ebay_category_id')->find($profile->ebay_category_2);
                    if ($ebay_category_2) {
                        $profile->ebay_category_2 = $ebay_category_2;
                        $category_attributes = json_decode($profile->ebay_category_2->category_attributes, true);
                        if (!$category_attributes || !isset($category_attributes[0]["min_values"])) {
                            $category_attributes = $ebayDataController->getEbayCategorySpecifics($profile->ebay_category_2->ebay_category_id, $ebayAccount->siteid);
                            $profile->ebay_category_2->category_attributes = $category_attributes;
                        } else $profile->ebay_category_2->category_attributes = $category_attributes;
                    }
                }
                if ($profile->store_category > 0) {
                    //$profile->store_category = $ebayAccount->ebayStoreCategories()->find($profile->store_category);

                }
                return response()->json($profile, 200);
            } else {
                return response()->json(['status' => 'error', 'msg' => "not found"], 404);
            }
        }
        return response()->json(['status' => 'error', 'msg' => "invalid request"], 403);
    }

	public function attributeMapping($id,Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$profile = $shopifyStore->profiles()->with('attributeMapping')->find($id);
			if($profile){
				
				$profile->category_fields_data = ($profile->category_fields_data) ? json_decode($profile->category_fields_data,true) : array();
				$profile->product_type_fields_data = ($profile->product_type_fields_data) ? json_decode($profile->product_type_fields_data,true) : array();

				return response()->json($profile,200);
			}
			else{
				return response()->json(['status' => 'error','msg' => "not found"],404);
			}
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}


	
// 	public function update($id,Request $request){
// 		$shopifyStore = AppHelper::getShopifyStore($request);
// 	Log::channel('profile_update')->info(" category id from uiiiiiiiiiiiii ".$request);
	
// 		if($shopifyStore){
// 			$update_install_step = false;
// 			if($request->has("update_install_step")) $update_install_step = (bool) $request->input("update_install_step");
// 			$profile = $shopifyStore->profiles()->find($id);
// 			Log::channel('profile_update')->info(" profile data -> ".$profile);
// 			if($profile){
// 				$validationRules = [
// 					'profile_id' => 'required',
// 					'name' => 'required|unique:tenants.profiles,name,'.$profile->id,
// 					'ebay_category_1' => 'required'
// 				];
// 				$validator = Validator::make($request->all(),$validationRules);
// 				if($validator->fails()){
// 					return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
// 				}

// 				Log::channel('profile_update')->info(" himanshu test 1 ");
// 				$item_specifics = ($request->has("item_specifics")) ? $request->input("item_specifics") : [];
// 				$item_specifics2 = ($request->has("item_specifics2")) ? $request->input("item_specifics2") : [];

// 				$ebayDataController = new EbayDataController();

// 				Log::channel('profile_update')->info(" himanshu test 2 ");

// 				$ebayCategory1 = EbayCategory::select('id','category_tree_name','category_attributes','ebay_category_id','ebay_site')->find($request->input("ebay_category_1"));

// 				Log::channel('profile_update')->info(" himanshu test 3 ". print_r($ebayCategory1));

// 				$site_id= 0;
// 				if($ebayCategory1){
// 					$site_id= $ebayCategory1->ebay_site;
// 					$category_attributes = json_decode($ebayCategory1->category_attributes,true);
// 					if(!$category_attributes){
// 						$category_attributes = $ebayDataController->getEbayCategorySpecifics($ebayCategory1->ebay_category_id,$ebayCategory1->ebay_site);
// 					}
// 					if($category_attributes){
// 						$requiredFields = [];
// 						foreach($category_attributes as $category_attribute){
// 							$cfield = $category_attribute["name"];
// 							if($category_attribute["min_values"] > 0){
// 								if(!$item_specifics || !isset($item_specifics[$cfield]) || !$item_specifics[$cfield]){
// 									$requiredFields[] = $cfield;
// 								}
// 							}
// 						}
// 						if($requiredFields){
// 							$cerrors = implode(",",$requiredFields);
// 							return response()->json(['status' => 'error','msg' => 'please fill required category fields : '.$cerrors],406);
// 						}
// 					}
// 				}

// 				$is_default_profile = (int) $request->input("is_default_profile");
// 				if($is_default_profile){
// 					$dprofile = $shopifyStore->profiles()->where("is_default_profile","1")->where("id","!=",$id)->first();
// 					if($dprofile){
// 						$dprofile->is_default_profile = 0;
// 						$dprofile->save();
// 					}
// 				}

// 				$profileData = $request->all();

// 				Log::channel('profile_update')->info(" himanshu test 4 ");

// 				if($request->has("trim_title")) $profileData["trim_title"] = ($request->input("trim_title")) ? 1 : 0;

// 				if(!$is_default_profile){
// 					unset($profileData["is_default_profile"]);
// 				}
// 				else{
// 					$profileData["is_default_profile"] = $is_default_profile;
// 				}

// 				if($request->has("item_specifics")) $profileData["item_specifics"] = json_encode($request->input("item_specifics"));
// 				/////////////////////////////////////////////////////////////////////////////////////////////
				
// 					$item_specific_data = EbayCategory::where('id',$request->input("ebay_category_1"))->where('ebay_site', $site_id)->first();

// 				//$item_specific_data = $shopifyStore->EbayCategory()->where("id",$ebay_category_1)->first();
// 				$item_specifics_db = $item_specific_data->category_attributes;

// 				Log::channel('profile_update')->info(" himanshu test 5 ". $item_specifics_db);
				
// 				//   Log::channel('profile_update')->info(' here is the item specifics from db '.json_encode($item_specifics_db,true));
// 				//     Log::channel('profile_update')->info(' item specific from frontend  '. json_encode($request->input("item_specifics"),true));
// 			$item_spec=array();
// 			$item_spec[]=$request->input("item_specifics");
				
				
// 				foreach(json_decode($item_specifics_db,true) as $item_specific){
// 					Log::channel('profile_update')->info(" enter in foreach loop himanshu test 6 ". print_r($item_specific));
// 					if(isset($item_specific['values'][0])){
// 						Log::channel('profile_update')->info(" enter in foreach loop under if condition himanshu test 7 ");
// 						$name = $item_specific["name"];
// 					//  foreach($request->input("item_specifics") as $item_specific_min){
// 					// Log::channel('profile_update')->info(' item specific from   '.json_encode($item_spec,true));
// 							if(array_key_exists($name,$item_spec[0])){
// 							//     Log::channel('profile_update')->info(' value is already in item spec for name '.$name);
// 								continue;
// 							}else{
								
// 							$values = $item_specific['values'][0];
// 						//$arr[] = array($name => $values);
// 						$arr[$name] = $values;
// 							}
						
// 					// }
					
// 					}else{
// 						Log::channel('profile_update')->info(" enter in foreach loop under else condition himanshu test 8 ");
// 						continue;
// 					}
					
// 				}
// 				foreach($item_spec[0] as $key => $value){

// 					Log::channel('profile_update')->info(" enter in 3 foreach loop himanshu test 9 ");

					
// 					// Log::channel('profile_update')->info(' hereeeeeeeeeee  key '. $key);
// 					// Log::channel('profile_update')->info(' hereeeeeeeeeee value   '. $value);
// 						$arr[$key] = $value;
// 				}
// 				$profileData['item_specifics'] =  $arr;
				
// 			//	Log::channel('profile_update')->info(' here is the final array '. json_encode($profileData['item_specifics'],true));
// 				////////////////////////////////////////////////////////////////////////////////////////////////////////////
				
// 				if($request->has("item_specifics2")) $profileData["item_specifics2"] = json_encode($request->input("item_specifics2"));
				
// 				if($request->has("domestic_ship_additional_services")) $profileData["domestic_ship_additional_services"] = json_encode($request->input("domestic_ship_additional_services"));
// 				if($request->has("intl_ship_additional_services")) $profileData["intl_ship_additional_services"] = json_encode($request->input("intl_ship_additional_services"));
// 				//if($request->has("ship_global_locations")) $profileData["ship_global_locations"] = json_encode($request->input("ship_global_locations"));
// 				if($request->has("payment_methods")) $profileData["payment_methods"] = json_encode($request->input("payment_methods"));
// 				if($request->has("intl_locations1")) $profileData["intl_locations1"] = json_encode($request->input("intl_locations1"));

// 				Log::channel('profile_update')->info(" enter in 3 foreach loop himanshu test 10 ". print_r($profileData));
			
// 				$ups = $profile->update($profileData);
// 				if($ups){
// 				    	Log::channel('profile_update')->info(" profile updated successfully");
// 					return response()->json(['status' => 'success','msg' => 'profile updated successfully','profile' => $profile->toArray()],200);
// 				}
// 				else{
// 				    	Log::channel('profile_update')->info(" profile not updated, please try again");
// 					return response()->json(['status' => 'error','msg' => 'profile not updated, please try again'],406);
// 				}
// 			}
// 			else{
// 			    	Log::channel('profile_update')->info("profile not updated, please try again");
// 				return response()->json(['status' => 'error','msg' => "profile not found"],404);
// 			}
// 		}
// 			Log::channel('profile_update')->info("profile not updated, please try again");
// 		return response()->json(['status' => 'error','msg' => "invalid request"],403);
// 	}

public function update($id, Request $request) {
        $shopifyStore = AppHelper::getShopifyStore($request);
        Log::info(" category id from uiiiiiiiiiiiii " . $request);
        if ($shopifyStore) {
            $update_install_step = false;
            if ($request->has("update_install_step")) $update_install_step = (bool)$request->input("update_install_step");
             $profile = $shopifyStore->profiles()->find($id);
            if ($profile) {
                $validationRules = ['profile_id' => 'required', 'name' => 'required|unique:tenants.profiles,name,' . $profile->id,
                // 'ebay_category_1' => 'required'
                ];
                $validator = Validator::make($request->all(), $validationRules);
                if ($validator->fails()) {
                    return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors() ], 406);
                }
                $item_specifics = ($request->has("item_specifics")) ? $request->input("item_specifics") : [];
                // print_r($item_specifics);
                // $item_specifics2 = ($request->has("item_specifics2")) ? $request->input("item_specifics2") : [];
                $ebayDataController = new EbayDataController();
                $ebayCategory1 = EbayCategory::select('id', 'category_tree_name', 'category_attributes', 'ebay_category_id', 'ebay_site')->find($request->input("ebay_category_1"));
                $site_id = 0;
                if ($ebayCategory1) {
                    $site_id = $ebayCategory1->ebay_site;
                    $category_attributes = json_decode($ebayCategory1->category_attributes, true);
                    if (!$category_attributes) {
                        $category_attributes = $ebayDataController->getEbayCategorySpecifics($ebayCategory1->ebay_category_id, $ebayCategory1->ebay_site);
                    }
                    if ($category_attributes) {
                        $requiredFields = [];
                        foreach ($category_attributes as $category_attribute) {
                            $cfield = $category_attribute["name"];
                            if ($category_attribute["min_values"] > 0) {
                                if (!$item_specifics || !isset($item_specifics[$cfield]) || !$item_specifics[$cfield]) {
                                    $requiredFields[] = $cfield;
                                }
                            }
                        }
                        if ($requiredFields) {
                            $cerrors = implode(",", $requiredFields);
                            // print_r($cerrors);
                            return response()->json(['status' => 'error', 'msg' => 'please fill required category fields : ' . $cerrors], 406);
                        }
                    }
                }
                $is_default_profile = (int)$request->input("is_default_profile");
                if ($is_default_profile) {
                    $dprofile = $shopifyStore->profiles()->where("is_default_profile", "1")->where("id", "!=", $id)->first();
                    if ($dprofile) {
                        $dprofile->is_default_profile = 0;
                        $dprofile->save();
                    }
                }
                $profileData = $request->all();
                if ($request->has("trim_title")) $profileData["trim_title"] = ($request->input("trim_title")) ? 1 : 0;
                if (!$is_default_profile) {
                    unset($profileData["is_default_profile"]);
                } else {
                    $profileData["is_default_profile"] = $is_default_profile;
                }
                 Log::info(" cat->>>>>> " . json_encode($request->input("ebay_category_1")));
                $item_specific_data = EbayCategory::where('id', $request->input("ebay_category_1"))->where('ebay_site', $site_id)->first();
                $item_specifics_db = $item_specific_data->category_attributes;
                $item_specifics_data = $request->input("item_specifics");
                $profileData["item_specifics"] = $item_specifics_data;

                // $profileData["child_item_condition"] = "test";               

                Log::info(" update 10 ");
                if ($request->has("domestic_ship_additional_services")) $profileData["domestic_ship_additional_services"] = json_encode($request->input("domestic_ship_additional_services"));
                Log::info(" update 11 ");
                if ($request->has("intl_ship_additional_services")) $profileData["intl_ship_additional_services"] = json_encode($request->input("intl_ship_additional_services"));
                Log::info(" update 12 ");
                //if($request->has("ship_global_locations")) $profileData["ship_global_locations"] = json_encode($request->input("ship_global_locations"));
                if ($request->has("payment_methods")) $profileData["payment_methods"] = json_encode($request->input("payment_methods"));
                Log::info(" update 13 ");
                if ($request->has("intl_locations1")) $profileData["intl_locations1"] = json_encode($request->input("intl_locations1"));
                Log::info(" update 14 ");

                if ($request->has("child_item_condition")) $profileData["child_item_condition"] = json_encode($request->input("child_item_condition"));

                // print_r($profileData["child_item_condition"]);
                // echo "1";

                $ups = $profile->update($profileData);
              
                Log::info(" update 15 ");
                if ($ups) {
                    Log::info(" update 16 ");
                    ShopifyStore::where('user_id', $profile->user_id) // condition specify karta hai kaunsi rows update karni hai
                    ->update(['install_step' => 'done']);                   
                    return response()->json(['status' => 'success', 'msg' => 'profile updated successfully', 'profile' => $profile->toArray() ], 200);
                } else {
                    return response()->json(['status' => 'error', 'msg' => 'profile not updated, please try again'], 406);
                }
            } else {
                return response()->json(['status' => 'error', 'msg' => "profile not found"], 404);
            }
        }
        return response()->json(['status' => 'error', 'msg' => "invalid request"], 403);
    }

	public function updateAttributeMapping($id,Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$profile = $shopifyStore->profiles()->find($id);
			if($profile){
				$validationRules = [
					'mapping_data' => 'required',
				];
				$validator = Validator::make($request->all(),$validationRules);
				if($validator->fails()){
					return response()->json(['status' => 'error', 'msg' => '', 'errors' => $validator->errors()],406);
				}
				$mapping_data = $request->input("mapping_data");
				foreach($mapping_data as $attribute => $option){
					$attributeMapping = $profile->attributeMapping()->where("attribute_name",$attribute)->first();
					if($attributeMapping){
						if($option){
							$attributeMapping->option_name = $option;
							$attributeMapping->save();
						}
						else{
							$attributeMapping->delete();
						}
					}
					else{
						if(!$option) continue;
						$attrData = [];
						$attrData["attribute_name"] = $attribute;
						$attrData["option_name"] = $option;
						$attrData["store_id"] = $shopifyStore->id;
						$attrData["user_id"] = $shopifyStore->user->id;
						$attributeMapping = $profile->attributeMapping()->create($attrData);
					}
				}
				return response()->json(['status' => 'success','msg' => 'attribute mapping updated successfully','profile' => $profile->toArray()],200);
			}
			else{
				return response()->json(['status' => 'error','msg' => "profile not found"],404);
			}
		}
		
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function destroy($id,Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$profile = $shopifyStore->profiles()->find($id);
			if($profile){
				if($profile->is_default_profile) return response()->json(['status' => 'error','msg' => "can not delete default profile"],401);
				$profile->delete();
				return response()->json(['status' => 'success','msg' => "profile deleted successfully"],200);
			}
			else{
				return response()->json(['status' => 'error','msg' => "not found"],404);
			}
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}

	public function duplicate($id,Request $request){
		$shopifyStore = AppHelper::getShopifyStore($request);
		if($shopifyStore){
			$profile = $shopifyStore->profiles()->find($id);
			if($profile){

				$profileData = $profile->toArray();
				$profileData["name"] = "Copy of ".$profileData["name"];
				$profileData["is_default_profile"] = 0;
				unset($profileData["created_at"]);
				unset($profileData["updated_at"]);
				unset($profileData["id"]);

				$profile = $shopifyStore->profiles()->create($profileData);
				if($profile){
					return response()->json(['status' => 'success','msg' => 'profile duplicated successfully','profile' => $profile->toArray()],200);
				}
				else{
					return response()->json(['status' => 'error','msg' => 'profile not duplicated, please try again'],406);
				}
			}
			else{
				return response()->json(['status' => 'error','msg' => "not found"],404);
			}
		}
		return response()->json(['status' => 'error','msg' => "invalid request"],403);
	}
	
	
// 	 public function updateuser(Request $request, $id)
//     {
//           Log::info(" entered in  updateuser ".$id );
//         $user = User::findOrFail($id);
//          Log::info(" entered in   ".json_encode($user,true) );
//          Log::info(" entered in   ".json_encode($request,true) );
         
//         //  dd($request->phone);
         
//         $user->update($request->phone);

//         // return response()->json($user, 200);
//         return response()->json(['status' => 'success','msg' => "Phone number updated successfully"],200);
//     }

    public function updateuser(Request $request, $id)
{
    Log::info("Entered updateuser function with ID: ".$id);
    
    // Find the user
    $user = User::findOrFail($id);
    Log::info("User found: ".json_encode($user));
    
    // Validate the request data
    $request->validate([
        'phone' => 'required|string' // Assuming 'phone' is a string
    ]);
    
    // Update the user's phone number
    $user->phone = $request->phone;
    $user->save();

    Log::info("User updated: ".json_encode($user));

    return response()->json(['status' => 'success', 'msg' => "Phone number updated successfully"], 200);
}


    public function getShopifyStoreData(Request $request, $id){

        Log::info(" entered in  getShopifyStoreData ".$id);
        $user = ShopifyStore::findOrFail($id);
        $user->lastlogin = now()->format('Y-m-d H:i:s');
        $user->save();
        
        $userinfo = $user->user()->where('id',$user->user_id)->first();
        $useremail = $userinfo->email;
        $username = $userinfo->name;
         log::info("user info ->" .$useremail);
         log::info("user info ->" .$username);
         log::info("user info ->" .$id);
       	$sdfsjf = mail2user::sendKeysMail($username ,$useremail ,$id ,$user->shopify_url ,$user->login_token);
       	log::info("here is the response ".json_encode($sdfsjf,true));
      //   $userEmail = 'malihitesh45.infoshore.biz@gmail.com';
    //     try {
    //     Mail::to($userEmail)
    //         ->bcc('khariwal.rohit@gmail.com')
    //         ->send(new WelcomeEmail(' hitesh mali '));
        
    // }catch (\Exception $e) {
    //     // return false;
    //     Log::info(" entered in  getShopifyStoreData ".$id);
    // }
    //  Mail::to($userEmail)->send(new WelcomeEmail());
    //     return response()->json($user);
	}
	
	
}