<?php

namespace App\Jobs;


use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Yajny\Models\Store;


class SweetMerchant implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public $store;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Store $store)
    {
        //
		$this->store = $store;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
					
			
				$domain_name  = $this->store->domain_name;
				$client = new \GuzzleHttp\Client();
				$res = $client->request('GET', 'https://d.joinhoney.com/v2/stores/partials/find?domain='.$domain_name);
				 $info =  json_decode($res->getBody(),true);
				 $keys  = array_keys($info);
				
				 if( count($keys) > 0 )
				{
					$honey_store_id = $info[$keys[0]];
				}
				else 
				$honey_store_id = 0;

				if($honey_store_id > 0)
				{
					$resStore = $client->request('GET','https://d.joinhoney.com/stores/'.$honey_store_id);
					$honey_data = json_decode($resStore->getBody(),true);
					
					if($honey_data)
					{
						$meta = $honey_data['metadata'] ?? null;
						$ext_info = [];

						  $asis_copy = [
                'YJN_applyButtonAction' => 'pns_siteSelCartCodeSubmit',
                'YJN_removeButtonAction' => 'pns_siteRemoveCodeAction',
                'YJN_inputCouponID' => 'pns_siteSelCartCodeBox',
                'YJN_cartTotalPriceID' => 'pns_siteSelCartTotalPrice',
                'YJN_cartTotalPriceDataID' => null,
                'YJN_preApplyAction' => 'pns_sitePreApplyCodeAction',
                'YJN_appResponseMessageID' => null,
            ];



						foreach($asis_copy as $to => $from)
						$ext_info[ $to ] = $meta[$from] ?? null;
					
						$ext_info['YJN_applyButtonActionType'] = ( stripos($ext_info['YJN_applyButtonAction'],'event') ) ? 'event' : 'selector';
						
						$this->store->sweet_store_id = $honey_store_id;
					  $this->store->sweet_data = $resStore->getBody();
					  $this->store->ext_info = json_encode($ext_info);
					$this->store->save();

					}

				}
				
			

    }
}
