<?php

namespace App\Console\Commands;
 
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\ShopifyStore;
use App\Helpers\AppHelper;
use Artisan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class SubmitImportRequest extends Command{
	protected $signature = 'submitimportrequest:run {type}';
	protected $description = 'Submit Import Request';
	
	public function __construct(){
		parent::__construct();
	}

	public function handle(){

		$cronJob = AppHelper::getCronJob("submit_import_request");
		if(!$cronJob || $cronJob->flag == 1 || $cronJob->do_stop == 1) die();
		else{
			$cronJob->flag = 1;
			$cronJob->started_at = date("Y-m-d H:i:s");
			$cronJob->ended_at = NULL;
			$cronJob->last_updated_at = date("Y-m-d H:i:s");
			$cronJob->save();
		}

		$type = $this->argument('type');

		if($type == "shopify_products"){
		    Log::info('entereed in SubmitImportRequest');
			$shopifyStores = ShopifyStore::where('status','active')->get();
			if($shopifyStores){
			    Log::info('shopifystore found in SubmitImportRequest for shopify_products'.count($shopifyStores));
				foreach($shopifyStores as $shopifyStore){
				     Log::info('shopifystore is this '.$shopifyStore);
					if(!$shopifyStore->import_products){
					    Log::info('for this store import product is not 1 '.$shopifyStore);
						$shopifyStore->import_products = 1;
					Log::info('Here is the shopurl'.$shopifyStore->shopify_url);	
						$shopifyStore->save();
					}
				}
			}
		}
		else if($type == "ebay_products"){
			$shopifyStores = ShopifyStore::where('status','active')->get();
			if($shopifyStores){
				foreach($shopifyStores as $shopifyStore){
					$shopify_store_id = $shopifyStore->id;
					$store_database_name = config('config.store_db_prefix').$shopify_store_id;
					AppHelper::setConnection($store_database_name,$shopifyStore);

					$ebayAccounts = $shopifyStore->ebayAccounts()->where("is_valid",1)->get();
					if($ebayAccounts->count() > 0){
						foreach($ebayAccounts as $ebayAccount){
							$ebayAccount->import_products = 1;
							$ebayAccount->save();
						}
					}
				}
			}
		}

		$cronJob->flag = 0;
		$cronJob->ended_at = date("Y-m-d H:i:s");
		$cronJob->last_updated_at = date("Y-m-d H:i:s");
		$cronJob->save();
	}
}