<?php

namespace App\Modules\Stock;

use Illuminate\Support\Facades\View;
use App\Http\Controllers\BaseController;

class StockController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    private function prepareSelect($list, $id = 'id', $value = 'value')
    {
        $results = ['' => ''];

        foreach ($list as $item) {
            $results[$item[$id]] = $item[$value];
        }

        return $results;
    }

    public function getIndex()
    {
        $data = [
            'categories'        => $this->prepareSelect(StockGroup::all()->toArray(), 'id', 'name'),
            'suppliers'         => $this->prepareSelect(Supplier::all()->toArray(), 'id', 'name'),
            'types'             => ['stock' => 'Stock', 'non_stock' => 'Non Stock', 'service' => 'Service', 'second_hand' => 'Second Hand'],
            'total_items'       => StockItem::query()->join('stock', 'stock_items.stock_id', '=', 'stock.id')->select('stock_items.*')->where('stock.type', 'stock')->count(),
            'out_of_stock'      => StockItem::query()->where('quantity', 0)->count(),
            'discontinued'      => Stock::query()->where('discontinued', 1)->count(),
            'products_to_order' => Stock::query()->where('quantity_to_order', '>', 0)->count(),
        ];
        $this->layout->content = View::make('stock::index', $data);
    }

    /**
     * Display the barcode page for a stock product.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function getBarcode($id)
    {
        $stock = Stock::findOrFail($id);

        return View::make('stock::barcode', compact('stock'));
    }
}
