<?php namespace App\Jobs\Shopify;

use App\Services\Shopify\OrdersService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Throwable;

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

    /**
     * Shop's myshopify domain
     *
     * @var ShopDomain|string
     */
    public $shopDomain;

    /**
     * The webhook data
     *
     * @var object
     */
    public $data;

    /**
     * Create a new job instance.
     *
     * @param string   $shopDomain The shop's myshopify domain.
     * @param stdClass $data       The webhook data (JSON decoded).
     *
     * @return void
     */
    public function __construct($shopDomain, $data)
    {
        $this->shopDomain = $shopDomain;
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(OrdersService $service)
    {
        Log::info('Running Orders Paid Job (Shopify webhook)');
        if (config('shopify-app.order_integration_moment') != 'orders-paid') {
            Log::info('Order integration moment is not set to orders-paid, skipping...');
            return;
        }
        Log::info(json_encode($this->data));
        $service->createOrder($this->data);
    }

    /**
     * Handle a job failure.
     *
     * @param  \Throwable  $exception
     * @return void
     */
    public function failed(Throwable $exception)
    {
        //Mail::to(config('mail.alerts_to'))->send(new AlertNotification('Job Failed: OrdersPaidJob<br><br>' . nl2br($exception->getTraceAsString())));
    }
}
