<?php
/**
 * Created by PhpStorm.
 * User: ali
 * Date: 8/29/2020
 * Time: 8:38 PM
 */

namespace Mamad\Product\Http\Controllers;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Mamad\Brand\Repositories\BrandRepository;
use Mamad\Category\Repositories\CategoryRepository;
use Mamad\Comment\Repository\CommentRepository;
use Mamad\PostMeta\Repository\PostMetaRepository;
use Mamad\Product\Http\Requests\AddProductRequest;
use Mamad\Product\Http\Requests\EditProductRequest;
use Mamad\Product\Models\Product;
use Mamad\Product\Repository\ProductRepository;
use Mamad\Product\Repository\ProductVariationRepository;
use Mamad\ProductAttr\Models\Attribute;
use Mamad\ProductAttr\Repository\ProductAttrRepository;

class ProductController extends Controller
{
    // theme functions
    public function index($slug){
        $product=ProductRepository::find_by_slug($slug);
        $in_stock=ProductRepository::in_stock($product);
        $comments=CommentRepository::get_approve_comment($product);
        $gallery=ProductRepository::get_gallery_image($product);
        $table_variations=false;
        $in_stock_variations=[];
        if($product->type== $product->type_variable){
            $variations=ProductVariationRepository::get_product_variation($product);
            foreach ($variations as $variation) {
                if(ProductRepository::in_stock($product,1,$variation["id"])){
                    $in_stock_variations[]=$variation;
                }
            }

            $table_variations=[];
            foreach ($in_stock_variations as $variation){
                foreach ($variation["variations"] as $variation_id=>$variation_item) {
                    if(isset($table_variations[$variation_id])){

                        $duplicate_variation=true;

                        foreach ($table_variations[$variation_id]["item"] as $item) {
                            if(isset($item["id"])){
                                if($item["id"] == $variation_item[0]["id"]){
                                    $duplicate_variation=false;
                                }
                            }

                        }
                        if($duplicate_variation) $table_variations[$variation_id]["item"][]=$variation_item[0];

                    } else{
                        $table_variations[$variation_id]["item"]=[$variation_item[0]];
                        $table_variations[$variation_id]["parentName"]=$variation_item["parentName"]["name"];
                    }
                }

            }


        }
        $related_products=ProductRepository::get_related_product_by_category($product);

        $attributes=ProductRepository::get_use_for_product_attribute($product);

        return view("Front::product",compact("product","in_stock","comments","gallery","related_products","in_stock_variations","table_variations","attributes"));
    }

    //admin functions
    public function product_excel(){
        return view("Product::Admin.product_excel");

    }
    public function product_excel_download(){
        return Storage::download("private/excel.xlsx");
    }
    public function product_excel_upload(Request $request){
        Storage::putFileAs("private",$request->file("excel_file"),"excel.xlsx");

        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load(storage_path("app/private/excel.xlsx"));
        $rows=$spreadsheet->getActiveSheet()->toArray();
        unset($rows[0]);
        foreach ($rows as $row) {
            // dd($row);
            $id=$row[0];
            $product_name=$row[1];
            $price=$row[2];
            $offer_price=$row[3];
            $product=ProductRepository::find_not_fail($id);
            if($product){
                ProductRepository::set_price($product,$price,$offer_price);
            }
        }
        toastMessage();
        return back();
    }
    public function product_list(Request $request)
    {
         $this->authorize("index",Product::class);
        $products=ProductRepository::order_product($request->orderBy,$request->name);

        return view("Product::Admin.product_list",["products"=>$products]);
    }

    public function product_add_form ()
    {
        $this->authorize("create",Product::class);
        $categories=CategoryRepository::get_by_type("product");
        $brands=BrandRepository::get_by_type("product");
        $attributes=ProductAttrRepository::get_all_parent_attr();

        return view("Product::Admin.product_add",["brands"=>$brands,"categories"=>$categories,"attributes"=>$attributes]);
    }

    public function product_add(AddProductRequest $request)
    {
        $this->authorize("create",Product::class);
        $slug=make_slug_for_data($request->title,$request->slug);
        $request->request->add(["slug"=>$slug]);

        $product=ProductRepository::create($request);
        PostMetaRepository::update_meta_tag($product,$request);
        ProductRepository::detachAttr($product);
        ProductRepository::add_attr_to_product($product,$request);

        PostMetaRepository::update($product,"type",$request->type);
        PostMetaRepository::update($product,"affiliate_percent",$request->affiliate_percent);

        PostMetaRepository::update($product,"gallery",serialize($request->gallery_image));

        if($request->product_cat){
            ProductRepository::create_product_category($product,$request->product_cat);
        }
        if($request->product_brand){
            ProductRepository::create_product_brand($product,$request->product_brand);
        }


        if($request->type!="variable"){
            PostMetaRepository::update($product,"sku",$request->sku);
            ProductRepository::set_price($product,$request->price,$request->offer_price);
            PostMetaRepository::update($product,"manage_stock",$request->manage_stock == null ? "off" : "on" );
            if($request->manage_stock == "on"){
                PostMetaRepository::update($product,"stock_number",$request->stock_number);
                PostMetaRepository::update($product,"low_stock_amount",$request->low_stock_amount);
            }else{
                PostMetaRepository::update($product,"stock_number",null);
                PostMetaRepository::update($product,"low_stock_amount",null);
            }
        }

        if($request->type=="variable" && !empty($request->attribute_select)){
            ProductVariationRepository::create_product_variation($product,$request);
        }
        return redirect()->route("admin_product_edit",["id"=>$product->id]);
    }

    public function product_edit_form($id)
    {
        $this->authorize("edit",Product::class);
        $categories=CategoryRepository::get_by_type("product");
        $brands=BrandRepository::get_by_type("product");
        $product=ProductRepository::find($id);
        $gallery=ProductRepository::get_gallery_image($product);
        $productCat=ProductRepository::get_product_cats($product);
        $productBrands=ProductRepository::get_product_brands($product);
        $attributes=ProductAttrRepository::get_all_parent_attr();
        $productVariations=ProductVariationRepository::get_product_variation($product);
        $attributes_for_variation=ProductRepository::get_use_for_variable_attribute($product);
        return view("Product::Admin.product_edit",["productBrands"=>$productBrands,"brands"=>$brands,"categories"=>$categories,"product"=>$product,"productCatId"=>$productCat,"gallery"=>$gallery,"attributes"=>$attributes,"productVariations"=>$productVariations,"attributes_for_variation"=>$attributes_for_variation]);
    }

    public function product_edit(EditProductRequest $request)
    {
        $this->authorize("update",Product::class);
        $slug=make_slug_for_data($request->title,$request->slug);

        $request->request->add(["slug"=>$slug]);

        $product=ProductRepository::find($request->id);
        PostMetaRepository::update_meta_tag($product,$request);
        ProductRepository::update($product,$request);

        ProductRepository::add_attr_to_product($product,$request);

        PostMetaRepository::update($product,"type",$request->type);
        PostMetaRepository::update($product,"affiliate_percent",$request->affiliate_percent);
        PostMetaRepository::update($product,"gallery",serialize($request->gallery_image));
        if($request->type !="variable") {


            PostMetaRepository::update($product, "manage_stock", $request->manage_stock == null ? "off" : "on");
            ProductRepository::set_price($product,$request->price,$request->offer_price);
            PostMetaRepository::update($product, "sku", $request->sku);
            if ($request->manage_stock == "on") {
                PostMetaRepository::update($product, "stock_number", $request->stock_number);
                PostMetaRepository::update($product, "low_stock_amount", $request->low_stock_amount);
            } else {
                PostMetaRepository::update($product, "stock_number", null);
                PostMetaRepository::update($product, "low_stock_amount", null);
            }
        }


        if($product->category){
            ProductRepository::delete_product_cats($product);
        }
        if($product->brand){
            ProductRepository::delete_product_brands($product);
        }

        if($request->product_cat){
            ProductRepository::create_product_category($product,$request->product_cat);
        }
        if($request->product_brand){
            ProductRepository::create_product_brand($product,$request->product_brand);
        }

        if($request->type=="variable" && !empty($request->attribute_select)){
            ProductVariationRepository::create_product_variation($product,$request);
        }


        return back();
    }

    public function product_delete($id)
    {
        $this->authorize("delete",Product::class);
        $product=ProductRepository::find($id);

        if($product->category){
            ProductRepository::delete_product_cats($product);
        }
        if($product->brand){
            ProductRepository::delete_product_brands($product);
        }

        ProductRepository::destroy($id);
        return back();
    }

    public function product_get_attr(Request $request)
    {
        $this->authorize("create",Product::class);
        $this->authorize("edit",Product::class);

        $attr=ProductAttrRepository::find($request->attribute_id);
        $attr_value=$attr->sub_attr()->pluck("id","name");
        return $attr_value;
    }

    public function get_product_attribute_use_for_variable(Request $request,$product=null)
    {
        $this->authorize("create",Product::class);
        $this->authorize("edit",Product::class);
        if($product){
            $product=$product;
        } else{
            $product=$request->product_id;
        }
        $attributes=ProductRepository::get_use_for_variable_attribute($product);
        return $attributes;
    }

    public function save_product_attribute(Request $request)
    {
        $this->authorize("create",Product::class);
        $this->authorize("edit",Product::class);
        $product=ProductRepository::find2($request->product_id);
       if($product){
           $result=ProductRepository::add_attr_to_product($product,$request);
       } else{
           $result=ProductRepository::add_attr_to_product((object) ["id"=>$request->product_id],$request);
        }
       return $result;
    }

    public  function attribute_delete(Request $request,$id=null){
        if(!is_null($id)){
        ProductAttrRepository::delete_product_attr($request->attribute_id,$id);
        }
        return true;
    }

    public function variation_delete(Request $request)
    {
        ProductVariationRepository::delete_product_one_variation($request->variation_id);

    }
}
