<?php

namespace App\Http\Controllers;

use App\Product;
use App\ProductAttribute;
use Illuminate\Http\Request;
use App\Attribute;
use App\AttributeOption;
use App\ProductImage;
use Image;
use File;
use App\Cart;
use App\CartItem;
use App\AttributeGroup;
use App\Category;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::paginate(10);
        return view('admin.products.index',compact('products'));
    }

     /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $textFields = Attribute::where('type','text')->get();
        $textareaFields = Attribute::where('type','textarea')->get();
        $selectFields = Attribute::where('type','select')->get();
        $booleanFields = Attribute::where('type','boolean')->get();
        $colors = AttributeOption::where('attribute_id',23)->pluck('name','id');
        $mainAttributes = AttributeGroup::where('name','main_attributes')->first()->attributeGroupMappings;
        $categories = Category::where('parent_id',null)->get()->pluck('name','id');
        $attributeGroups = AttributeGroup::all()->pluck('name','id');

        return view('admin.products.create',compact('textFields','textareaFields','selectFields','booleanFields','colors','mainAttributes','categories','attributeGroups'));

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
            'sku' => 'required| unique:products',
        ];
        $messages = [
            'sku.required' => 'Polje sku je obavezno',
            'sku.unique' => 'Polje sku je jedinstveno'
        ];

        // validate form
        $post = $request->all();
        /* if (!$request->validate($rules, $messages)) {
            return Redirect::back()->withErrors();
        } */
        $request->validate($rules,$messages);
        $productModel = Product::insertGetId([
            'sku' => $request->sku,
            'type' => 'default',
        ]);
        foreach($request->except(['sku','type','_token','f_image','main_category_id','category_id','attributeGroup','items']) as $key => $attribute){
            if($key == 'url_key' && $attribute == ''){
               $attribute = $this->makeUrl($request->sku,$request->name);
            }
            if($attribute !== null){
               ProductAttribute::create([
                    'product_id' => $productModel,
                    'attribute_id' => $this->getAttribute($key),
                    'attribute_value' =>  $attribute,
                ]);
            }
        }
       return $this->uploadImage($request, $productModel);


    }

    private function makeUrl($sku,$name){
        return $sku.'-'.$name;
    }

    private function getAttribute($name){
        $attribute = Attribute::where('code',$name)->first();
        return $attribute->id;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $attributes = Product::where('id',$id)->first()->productAttributes;

        return view('admin.products.show',compact('attributes'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Products $product)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Products $product)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Products $product)
    {
        //
    }

    public function uploadImage(Request $request, $id)
    {
        //check if image
        if ($request->hasFile('f_image')) {

            $images = $request->file('f_image');
            //var_dump($images);
            //setting flag for condition
            $org_img = $thm_img = true;

            // create new directory for uploading image if doesn't exist
            if (!File::exists(public_path('/images/originals/'))) {
                $org_img = File::makeDirectory(public_path('/images/originals/'), 0777, true);
            }
            if (!File::exists(public_path('/images/thumbnails/'))) {
                $thm_img = File::makeDirectory(public_path('/images/thumbnails'), 0777, true);
            }

            // loop through each image to save and upload
            //foreach($images as $key => $image) {
            //print_r($image);
            //temp
            foreach($images as $image){
                //create new instance of Photo class
                $newPhoto = new ProductImage();

                //get file name of image  and concatenate with 4 random integer for unique
                $filename = rand(1111, 9999) . time() . '.' . $image->getClientOriginalExtension();
                //path of image for upload
                $org_path = 'images/originals/'.$filename;
                //$thm_path = '/images/thumbnails/' . $filename;

                $newPhoto->path = 'images/originals/'.$filename;
                //$newPhoto->thumbnail = '/images/thumbnails/'.$filename;

                // post id
                $newPhoto->product_id = $id;

                //don't upload file when unable to save name to database
                if (!$newPhoto->save()) {
                    return false;
                }
                // upload image to server
                if (($org_img && $thm_img) == true) {
                    Image::make($image)->save($org_path);
                }
            }


        }
        return redirect()->route('admin/products');
    }

    public function addToCart()
    {
        $id = request()->id;
        $product = Product::find($id);
        if (!$product) {

            abort(404);
        }
        // if cart is empty then this the first product
        if (!isset($_COOKIE['cartID'])) {

            $cart = [
                $id => [
                    "name" => $product->getName(),
                    "quantity" => 1,
                    "price" => $product->finalPrice(),
                    "photo" => $product->getImage()
                ]
            ];

            $cartID = $this->saveCartToDB();
            setcookie('cartID', $cartID, 0, '/' );

            $this->saveCartItem($id,$cartID);

            return redirect()->back()->with('success', 'Product added to cart successfully!');
        }

        $cartID = $_COOKIE['cartID'];
        // if cart not empty then check if this product exist then increment quantity
        if (CartItem::where('cart_id',$cartID)->where('product_id',$id)->first()) {

            $cart = CartItem::where('cart_id', $cartID)->where('product_id', $id)->first();
            $cart->quantity += 1;
            $cart->save();

            return redirect()->back()->with('success', 'Product added to cart successfully!');
        }

        // if item not exist in cart then add to cart with quantity = 1
        CartItem::insert([
            'product_id' => $id,
            "quantity" => 1,
            "cart_id" => $cartID

        ]);

        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

    public function cart()
    {
        if(isset($_COOKIE['cartID'])){
            $cart = Cart::where('id',$_COOKIE['cartID'])->first();
            return view('shop.cart', compact('cart'));
        }

        return false;
    }


    public function updateCart(Request $request)
    {
        if ($request->id & $request->quantity) {

            $cart = CartItem::where('id', $request->id)->first();
            $cart->update(['quantity' => $request->quantity]);

            session()->flash('success', 'Cart updated successfully');
        }
    }

    public function remove(Request $request)
    {
        if ($request->id) {

            CartItem::where('id',$request->id)->delete();

            session()->flash('success', 'Product removed successfully');
        }
    }

    /**
     * save cart juste once
     */
    private function saveCartToDB(){
       return Cart::insertGetId([
            'items_count' => countCartItems(),
            'grand_total' => getCartTotal()
       ]);
    }

    /**
     *  save each item into cart_item db
     */
    private function saveCartItem($id,$cartID){
        CartItem::create([
            'product_id' => $id,
            'cart_id' => $cartID,
            'quantity' => 1
        ]);
    }

    public function getAttributes($id){
        $group = AttributeGroup::find($id);
        $attributes = [];
        if($group){
            foreach($group->attributeGroupMappings as $item){
                array_push($attributes,$item->attribute);
            };
        }
        return $attributes;
    }

}
