<?php

namespace App\Modules\Bookings;

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

class BuildConfirmed
{
    /**
     * 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('BuildConfirmed', 'App\Modules\Bookings\BuildConfirmed@fire');
    }

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

        foreach ($build->planned_components()->get() as $component) {
            if ($component->unlimited) {
                $this->createTransaction($component, $component->pivot->quantity);
            } else {
                $this->processNormalFlow($component);
            }
        }

        $build->planned_components()->detach();
    }

    /**
     * Update the stock quantity and the quantity to order.
     *
     * @return bool
     */
    protected function processNormalFlow(Stock $component)
    {
        $stock_available = $component->quantity_available();

        // Require the stock needed
        if ($stock_available < $this->build->quantity * $component->pivot->quantity) {
            $quantity_needed = $this->build->quantity * $component->pivot->quantity - $stock_available;
            $this->build->ordered_components()->attach([$component->id => ['quantity' => $quantity_needed]]);
                            Event::dispatch('StockRequested', [$component, $quantity_needed]);

            if ($stock_available > 0) {
                $this->createTransaction($component, $stock_available);
            }
        } 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;
    }
}
