<?php

namespace App\Modules\Bookings;

use App\Modules\Stock\StockTransaction;
use Exception;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use App\Seraph\Services\GlobalMailerService;

class BuildComponentReceived
{
    /**
     * The part that was updated.
     *
     * @var \App\Modules\Bookings\Build
     */
    protected $build;

    /**
     * Subscribe to events.
     *
     * @param  mixed $events
     *
     * @return null
     */
    public function subscribe($events)
    {
        $events->listen('BuildComponentReceived', 'App\Modules\Bookings\BuildComponentReceived@fire');
    }

    /**
     * Fire the event.
     *
     * @param  \App\Modules\Bookings\Build $build
     *
     * @return bool
     */
    public function fire(Build $build, \App\Modules\Stock\Stock $stock, $quantity)
    {
        $this->build = $build;
        $this->createTransaction($stock, $quantity);

        return $this->notifyUser($stock, $quantity);
    }

    /**
     * Send an email to the user to let them know the part was received.
     *
     * @return bool
     */
    protected function notifyUser(\App\Modules\Stock\Stock $stock, $quantity)
    {
        if ($this->build->related) {
            $send_to = $this->getUserToNotifyEmail();

            if ($send_to) {
                $build = $this->build;
                GlobalMailerService::send('emails.alerts.received_part_notification', ['part' => $build, 'stock' => $stock, 'quantity' => $quantity], function ($message) use ($build, $stock, $quantity, $send_to) {
                    // Configure the email options
                    $message->to($send_to)->subject('Received '.$stock->name.' for task '.$build->related_id);
                });
            }
        }
    }

    /**
     * Create a stock transaction that will
     * automatically update the stock.
     *
     * @return bool
     */
    protected function createTransaction(\App\Modules\Stock\Stock $stock, $quantity)
    {
        $transaction = StockTransaction::create([
            'stock_id'     => $stock->id,
            'related_type' => $this->build->related_type,
            'related_id'   => $this->build->related_id,
            'quantity'     => -$quantity,
        ]);

        if (! $transaction->exists) {
            throw new Exception('Failed to create stock transaction, '.json_encode($transaction->errors->all()));
        }

        return true;
    }

    /**
     * Get the email of the user the "Part Received" notification has to be sent to.  
     *
     * @return string | false
     */
    protected function getUserToNotifyEmail()
    {
        if ($this->build->related->user && $this->build->related->user->email) {
            return $this->build->related->user->email;
        }

        if ($this->build->related->type == 'order' && $this->build->related->creator && $this->build->related->creator->email) {
            return $this->build->related->creator->email;
        }

        return false;
    }
}
