<?php namespace App\Jobs;

use App\Mail\AlertNotification;
use App\Models\Order;
use App\Shopify\ShopifyService;
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 stdClass;
use Throwable;

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

    /**
     * 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(ShopifyService $service)
    {
        \Log::info('Update order status JOB for order ID: ' . $this->order->id);
        if (!$service->orderStatusUpdate($this->order)) {
            throw new \RuntimeException('Error Updating order status (' . $this->order->id . ')');
        }
    }

    /**
     * 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: UpdateOrderStatusJob<br><br>' . nl2br($exception->getTraceAsString())));
    }
}
