<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\App;
use App\Modules\Stock\Stock;

class PartRequester
{
    /**
     * A reference to the Monolog.
     *
     * @var \Illuminate\Log\Writer
     */
    private $log;

    public function __construct(Log $log)
    {
        $this->log = $log;
    }

    /**
     * Create a new task to ask to the client about the previous one.
     *
     * @param  App\Modules\Bookings\Task $task
     *
     * @return string | false
     */
    public function request($data)
    {
        return DB::transaction(function () use (&$data) {
            // Determine if this is a new part
            if (! isset($data['stock_id'])) {
                $stockData['name'] = $data['name'];
                $stockData['severity_id'] = $data['severity_id'];
                $stockData['notes'] = $data['notes'];
                $stockData['type'] = 'non_stock';
                $stockData['approval_required'] = 1;
                $stockData['price_excluding_vat'] = isset($data['price_vat_included'])
                                                ? number_format($data['price_excluding_vat'] / (1 + Config::get('settings.vat') / 100), 2, '.', '')
                                                : number_format($data['price_excluding_vat'], 2);
                $stock = Stock::create($stockData);

                if (! $stock->exists) {
                    throw new Exception(json_encode($stock->errors->all()));
                }
            } else {
                $stock = Stock::findOrFail($data['stock_id']);

                // Avoid to request a composite stock
                if ($stock->composite) {
                    throw new Exception('It is not possible to order a new buld. Create it insted in the new build widget.');
                }
            }

            // Now we should have the stock item
            // and we will create the part for the task
            $partData['related_id'] = $data['related_id'];
            $partData['related_type'] = $data['related_type'];
            $partData['stock_id'] = $stock->id;
            $partData['price'] = $stock->price_excluding_vat;
            $partData['quantity'] = isset($data['quantity']) ? $data['quantity'] : 1;
            $partData['vat'] = isset($data['vat']) ? $data['vat'] : Config::get('settings.vat');
            $partData['quantity_on_order'] = $partData['quantity'];

            $part = Part::create($partData);

            Event::dispatch('PartCreating', $part);

            if (! $part) {
                throw new Exception(json_encode($part->errors->all()));
            }

            $part->load('creator', 'stock', 'composite_items');

            return $part;
        });
    }
}
