<?php

namespace App\Modules\Bookings;

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

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

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

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

        if ($build->status == 'planning') {
            $build->planned_components()->detach();
        } elseif ($build->status == 'in_progress') {
            foreach ($build->stock->composite_items()->get() as $component) {
                if ($component->unlimited) {
                    $this->createTransaction($component, $component->pivot->quantity);
                } else {
                    $this->processNormalFlow($component);
                }
            }
        }
    }

    /**
     * Update the stock quantity and the quantity to order.
     *
     * @return bool
     */
    protected function processNormalFlow(Stock $component)
    {
        $ordered_component = $this->build->ordered_components()->where('stock_id', $component->id)->first();

        // Require the stock needed
        if ($ordered_component) {
            $this->build->ordered_components()->detach($ordered_component);
                            Event::dispatch('CancelRequestedStock', [$component, $ordered_component->pivot->quantity]);

            if ($ordered_component->pivot->quantity < $component->pivot->quantity) {
                $this->createTransaction($component, $this->build->quantity * $component->pivot->quantity - $ordered_component->pivot->quantity);
            }
        } else {
            $this->createTransaction($component, $this->build->quantity * $component->pivot->quantity);
        }

        return true;
    }

    /**
     * Create a stock transaction that will
     * automatically update the stock.
     *
     * @return bool
     */
    protected function createTransaction(Stock $component, $quantity)
    {
        $transaction = StockTransaction::create([
            'stock_id'     => $component->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;
    }
}
