<?php

namespace App\Modules\Stock;

use Exception;
use Illuminate\Support\Facades\Event;

class StockReportCreated
{
    /**
     * The stock report created.
     *
     * @var \App\Modules\Stock\StockReport
     */
    protected $report;

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

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

        if ($report->old_quantity != $report->new_quantity) {
            $this->createTransaction($report->new_quantity - $report->old_quantity);
        }
    }

    protected function createTransaction($quantity)
    {
        $transaction = StockTransaction::create([
            'stock_id'     => $this->report->stock_id,
            'related_id'   => $this->report->id,
            'related_type' => 'stock_report',
            'quantity'     => $quantity,
        ]);

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

        return true;
    }
}
