<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\ProductDetail;
use App\ProductQuantity;
use App\Category;
use App\History;
use App\Settings;
use DataTables;
use App;
use Storage;
use Charts;
use Auth;
use Carbon\Carbon;
use App\Http\Services\Uploader; #custom class
class ManageProduct extends Controller
{
    public function index()
    {
    	return view('manage.product.index');
    }

    public function sold()
    {
        return view('manage.product.sold-outs');
    }

    public function create()
    {
        // $product = Product::make(['product_code', str_random(5)]);
        // $data['product'] = $product;
        // $data['code'] = $product->product_code;
        $data['code'] = str_random(5);
    	$data['categories'] = Category::all();
    	return view('manage.product.form')->with($data);
    }

    public function show($id)
    {
        Carbon::setLocale(app()->getLocale());
        $product = Product::findOrFail($id);
        $days = [];
        $lastWeekStock = [];
        $lastWeekSalesQuantity = [];
        $lastWeekSalesMargin = [];
        $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);
        }
        foreach (range(0,6) as $i) {
            $quantity = $product->quantities()
                ->where('is_sales', true)
                ->whereDate('created_at', '=', Carbon::now()->subDays($i)->toDateString())
                ->sum('quantity');
            array_push($lastWeekSalesQuantity, abs($quantity));
            array_push($lastWeekSalesMargin, abs($quantity * $product->product_price));
        }

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

        $chartSalesQuantity = Charts::multi('line', 'material')
        ->title("Last week sales in quantity")
        ->dimensions(0, 400)
        ->template("material")
        ->dataset('Sales in quantity', array_reverse($lastWeekSalesQuantity))
        ->labels($days);

        $chartSalesMargin = Charts::multi('line', 'material')
        ->title("Last week sales in margin")
        ->dimensions(0, 400)
        ->template("material")
        ->dataset('Sales in margin', array_reverse($lastWeekSalesMargin))
        ->labels($days);

        $data['chartStock'] = $chartStock;
        $data['chartSalesQuantity'] = $chartSalesQuantity;
        $data['chartSalesMargin'] = $chartSalesMargin;
        $data['product'] = Product::findOrFail($id);
        return view('manage.product.show')->with($data);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'name' => 'required',
            'category' => 'required',
            'weight' => 'required',
            'price' => 'required',
            'cost' => 'required',
            'minQuantity' => 'required',
        ]);

        $db = new Product;
        $db->product_code = $request->code;
        $db->product_weight = $request->weight;
        $db->product_category = $request->category;
        $db->product_price = $request->price;
        $db->product_cost = $request->cost;
        $db->product_min_quantity = $request->minQuantity;

        foreach (config('translatable.locales') as $key => $value) {
            $db->{'product_name:'.$key} = $request->name[$key];
            $db->{'product_content:'.$key} = $request->content[$key];
        }
        $db->save();

        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Add product - '.$db->category->category_name.' - '.$db->product_name
        ]);

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

    public function edit(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $data['code'] = $product->product_code;
    	$data['title'] = __('manage.update-product-information');
    	$data['product'] = $product;
    	$data['method'] = method_field('PUT');
    	$data['route'] = route('manage.product.update', $id);
    	$data['categories'] = Category::all();
    	return view('manage.product.form')->with($data);
    }

    public function update(Request $request, $id)
    {
    	$this->validate($request, [
            'code' => 'required',
            'name' => 'required',
            'category' => 'required',
            'weight' => 'required',
            'price' => 'required',
            'cost' => 'required',
            'minQuantity' => 'required',
    	]);
        $db = Product::findOrFail($id);
        $db->product_code = $request->code;
        $db->product_weight = $request->weight;
        $db->product_category = $request->category;
        $db->product_price = $request->price;
        $db->product_cost = $request->cost;
        $db->product_min_quantity = $request->minQuantity;

        foreach (config('translatable.locales') as $key => $value) {
            $db->{'product_name:'.$key} = $request->name[$key];
            $db->{'product_content:'.$key} = $request->content[$key];
        }
        $db->save();

        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Update product - '.$db->category->category_name.' - '.$db->product_name
        ]);

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

    public function destroy($id)
    {
        $db = Product::findOrFail($id);

        if (count($db->details)) {
            foreach ($db->details as $image) {
                if($image->detail_image!='' && $image->detail_code!=''){
                    Storage::delete('/img/products/'.$image->detail_code.'/'.$image->detail_image);
                }
                $image->delete();
            }
        }

        $db->deleteTranslations();

        History::create([
            'user_id' => Auth::user()->id,
            'operation' => 'Delete product - '.$db->category->category_name.' - '.$db->product_name
        ]);

        $db->delete();
        return response()->json(['message' => __('manage.msg_deleted')]);
    }

    public function addImage(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'image' => 'required'
        ]);

        $product = Product::where('product_code', $request->code)->first();
        if (!empty($product) && $product->details()->count() >= 3) {
            return response()->json(['message' => __('manage.you-cant-add-more-than-3-images'), 'status' => 0]);
        }

        # If new image uploaded
        if($request->image) {
            # Save uploaded image
            $imageName = Uploader::SaveImageWithThumb($request->image, 'product_', 'img/products/'.$request->code.'/');
        }

        $db = new ProductDetail;
        $db->detail_code = $request->code;
        $db->detail_image = $imageName['thumb'];
        $db->detail_image_big = $imageName['original'];
        $db->save();

        $newitem = '
            <div class="col-lg-4 thumbnail-card">
              <div class="card">
                <img src="'.asset(config('customvar.storage_url').'img/products/'.$db->detail_code.'/'.$db->detail_image).'" class="img-responsive">
                <a href="'.route('manage.product.delete-image', $db->id).'" class="btn-rounded ajax-delete">
                  <i class="fa fa-trash"></i>
                </a>
              </div>
            </div>
        ';

        return response()->json(['message' => 'Uploaded', 'newItem' => $newitem, 'status' => 1]);
    }

    public function deleteImage($id)
    {
        $image = ProductDetail::findOrFail($id);
        if($image->detail_image!='' && $image->detail_code!=''){
            Storage::delete('/img/products/'.$image->detail_code.'/'.$image->detail_image);
        }
        $image->delete();
        return response()->json(['message' => 'deleted']);
    }

    public function getProducts()
    {
    	$products = Product::latest()->get();
    	return Datatables::of($products)
	    	->addColumn('action', function($product) {
	    		return '
	    		<a href="'.route("manage.product.show", $product->id).'" class="btn btn-default btn-xs dt-info">
					<i class="fa fa-info"></i>
	    		</a>
	    		<a href="'.route("manage.product.edit", $product->id).'" class="btn btn-primary btn-xs dt-edit">
					<i class="fa fa-edit"></i>
	    		</a>
	         	<a href="'.route("manage.product.destroy", $product->id).'" class="btn btn-danger btn-xs dt-delete">
					<i class="fa fa-trash"></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);
    }

    public function getProductsSold()
    {
        $products = Product::whereRaw('product_stock < product_min_quantity')
            ->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.show", $product->id).'" class="btn btn-default btn-xs dt-info">
                    <i class="fa fa-info"></i>
                </a>';
            })
            ->addColumn('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('quantity', function($product) {
                return $product->product_stock;
            })
            ->addindexColumn()
            ->make(true);
    }
}
