<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\History;
use Auth;
use App;
use DataTables;
use App\Http\Services\Uploader; #custom class
class ManageCategory extends Controller
{
    public function create()
    {
    	return view('manage.category.form');
    }

    public function store(Request $request)
    {
        $rules = collect();
        foreach (config('translatable.locales') as $key => $value) {
          $rules->put('name.'.$key, 'required');
        }
    	$this->validate($request, $rules->toArray());

        $db = new Category;

        # If new image uploaded
        if($request->image1) {
            # Save uploaded image
            $db->category_image1 = Uploader::SaveImage($request->image1, 'category_img1_', 'img/products/category/');
        }
        if($request->image2) {
            # Save uploaded image
            $db->category_image2 = Uploader::SaveImage($request->image2, 'category_img2_', 'img/products/category/');
        }

        foreach (config('translatable.locales') as $key => $value) {
            $db->{'category_name:'.$key} = $request->name[$key];
            $db->{'category_alt:'.$key} = $request->alt[$key];
        }
        $db->save();
        
        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Add Category - '.$db->category_name
        ]);

        flash(__('manage.msg_added'))->success();
        return redirect(route('manage.product.index'));
    }

    public function getCategories()
    {
        $categories = Category::latest()->get();
        return Datatables::of($categories)
            ->addindexColumn()
            ->make(true);
    }
}
