<?php namespace App\Jobs\SAP;

use App\Mail\AlertNotification;
use App\Models\Order;
use App\SAP\SAPService;
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\Mail;
use Osiset\ShopifyApp\Objects\Values\ShopDomain;
use RuntimeException;
use stdClass;
use Throwable;

class CreateSapOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $backoff = 3;

    /**
     * The order model
     *
     * @var Order
     */
    protected $order;

    /**
     * Create a new job instance.
     *
     * @param stdClass $data
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(SAPService $sapService)
    {
        \Log::info('Create SAP order JOB for order ID: ' . $this->order->id);
        $sapService->createSapOrder($this->order);
    }

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