<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\ProductQuantity;
use App\History;
use Carbon\Carbon;
use App\Category;
use App\Settings;
use DataTables;
use Charts;
use Auth;
class ManageQuantity extends Controller
{
    public function index()
    {
    	return view('manage.product.quantity');
    }

    public function quantityUp($id)
    {
        // return Carbon::now()->addDays(-1)->toDateString();
        Carbon::setLocale(app()->getLocale());
        $product = Product::findOrFail($id);
        $days = [];
        $lastWeekStock = [];
        $stock = $product->product_stock;
        foreach (range(0,6) as $i) {
            $quantity = $product->quantities()
                ->whereDate('created_at', '=', Carbon::now()->subDays($i-1)->toDateString())
                ->sum('quantity');
            $stock = $stock - $quantity;
            array_push($days, Carbon::now()->subDays($i)->formatLocalized('%A'));
            array_push($lastWeekStock, $stock);
        }

        $chartStock = Charts::multi('line', 'material')
        ->title(__('manage.last-week-quantity-in-stock'))
        ->dimensions(0, 400)
        ->template("material")
        ->dataset(__('manage.quantity-in-stock'), array_reverse($lastWeekStock))
        ->labels(array_reverse($days));

        $data['chartStock'] = $chartStock;
        $data['product'] = $product;
        $data['code'] = $product->product_code;
        $data['categories'] = Category::all();
        return view('manage.product.quantity-up')->with($data);
    }

    public function storeQuantityUp(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $product->product_stock = $product->product_stock + $request->inputUnit;
        $product->save();
        $product->quantities()->create([
            'quantity' => 0 + $request->inputUnit,
            'reason' => $request->reason
        ]);
        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Stock up - '.$product->category->category_name.' - '.$product->product_name .' ('. $request->inputUnit .')'
        ]);
        return redirect(route('manage.product.quantity'));
    }

    public function quantityDown($id)
    {
        Carbon::setLocale(app()->getLocale());
        $product = Product::findOrFail($id);
        $days = [];
        $lastWeekStock = [];
        $stock = $product->product_stock;
        foreach (range(0,6) as $i) {
            $quantity = $product->quantities()
                ->whereDate('created_at', '=', Carbon::now()->subDays($i-1)->toDateString())
                ->sum('quantity');
            $stock = $stock - $quantity;
            array_push($days, Carbon::now()->subDays($i)->formatLocalized('%A'));
            array_push($lastWeekStock, $stock);
        }

        $chartStock = Charts::multi('line', 'material')
        ->title(__('manage.last-week-quantity-in-stock'))
        ->dimensions(0, 400)
        ->template("material")
        ->dataset(__('manage.quantity-in-stock'), array_reverse($lastWeekStock))
        ->labels(array_reverse($days));

        $data['chartStock'] = $chartStock;
        $data['product'] = $product;
        $data['code'] = $product->product_code;
        $data['categories'] = Category::all();
        return view('manage.product.quantity-down')->with($data);
    }

    public function storeQuantityDown(Request $request, $id)
    {
        if ($request->reason=='manual') {
            $type = true;
        } else {
            $type = false;
        }
        $product = Product::findOrFail($id);
        $product->product_stock = $product->product_stock - $request->inputUnit;
        $product->save();
        $product->quantities()->create([
            'quantity' => 0 - $request->inputUnit,
            'reason' => $request->reason,
            'is_sales' => $type
        ]);
        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Stock down - '.$product->category->category_name.' - '.$product->product_name.' (-'. $request->inputUnit .')'
        ]);
        return redirect(route('manage.product.quantity'));
    }

    public function getQuantities()
    {
        $products = Product::latest()->get();
        return Datatables::of($products)
            ->addColumn('action', function($product) {
                return '
                <a href="'.route("manage.product.quantity.up", $product->id).'" class="btn btn-primary btn-xs">
                    <i class="fa fa-arrow-circle-up"></i>
                </a>
                <a href="'.route("manage.product.quantity.down", $product->id).'" class="btn btn-primary btn-xs">
                    <i class="fa fa-arrow-circle-down"></i>
                </a>
                <a href="'.route("manage.product.show", $product->id).'" class="btn btn-default btn-xs dt-info">
                    <i class="fa fa-info"></i>
                </a>
                ';
            })
            ->editColumn('product_category', function($product) {
                if (count($product->category)) {
                    return $product->category->category_name;
                }
            })
            ->editColumn('product_price', function($product) {
                $currency = Settings::where('setting_name','currency')->first();
                return $currency ? $currency->setting_value.' '.number_format($product->product_price, 0) : number_format($product->product_price, 0);
            })
            ->editColumn('product_margin', function($product) {
                if ($product->product_price && $product->product_cost) {
                  $margin = ($product->product_price - $product->product_cost) / $product->product_price;
                  return round($margin * 100). '%';
                } else {
                  return 0;
                }
            })
            ->addindexColumn()
            ->make(true);
    }
}
