<?php

namespace App\Modules\Bookings;

use App\Modules\Stock\StockTransaction;
use Exception;
use Illuminate\Support\Facades\Event;

class PartCreating
{
    /**
     * The part that was updated.
     *
     * @var \App\Modules\Bookings\Part
     */
    protected $part;

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

    /**
     * Fire the event.
     *
     * @param  \App\Modules\Bookings\Part $part
     *
     * @return bool
     */
    public function fire($part)
    {
        $this->part = $part;

        if ($part->stock->unlimited) {
            return $this->createTransaction();
        }

        // Check if quantity exists in stock
        return $this->processNormalFlow();
    }

    /**
     * Update the stock quantity and the quantity to order.
     *
     * @return bool
     */
    protected function processNormalFlow()
    {

        // Require the stock needed
        if ($this->part->quantity_on_order > 0) {
            Event::dispatch('StockRequested', [$this->part->stock, $this->part->quantity_on_order]);
        }

        // Creates a transaction to put back the items used in stock
        if ($this->part->quantity > $this->part->quantity_on_order) {
            $this->createTransaction();
        }

        return true;
    }

    /**
     * Create a stock transaction that will
     * automatically update the stock.
     *
     * @return bool
     */
    protected function createTransaction()
    {
        $quantity = $this->part->quantity - $this->part->quantity_on_order;

        $transaction = StockTransaction::create([
            'stock_id'     => $this->part->stock_id,
            'related_type' => $this->part->related_type,
            'related_id'   => $this->part->related_id,
            'quantity'     => -$quantity,
        ]);

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

        return true;
    }
}
