<?php

namespace Sarga\API\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Webkul\Customer\Repositories\CustomerRepository;
use Illuminate\Support\Str;
use Webkul\Marketplace\Http\Controllers\Shop\Account\ProductController as SellerProductController;
use Webkul\Product\Models\ProductFlat;
use Webkul\Product\Models\ProductInventory;
use Webkul\Product\Models\Product;
use Webkul\Product\Repositories\ProductRepository;
use Webkul\Marketplace\Repositories\SellerRepository;
use Webkul\Marketplace\Models\Product as SellerProductModel;
use Webkul\Marketplace\Models\Order as SellerOrderModel;
use Webkul\Marketplace\Models\OrderItem as SellerOrderItemModel;

class SellerProduct extends SellerProductController
{
    /**
     * Product repository instance.
     *
     * @var \Webkul\Product\Repositories\ProductRepository
     */
    protected $productRepository;
    /**
     * SellerRepository object
     *
     * @var Object
     */
    protected $sellerRepository;
    /**
     * Method to store user's sign up form data to DB.
     *
     * @return \Illuminate\Http\Response
     */


    /**
     * Create a new controller instance.
     *           $categoryRepository
     * @param  \Webkul\Product\Repositories\ProductRepository        $productAttributeValueRepository
     * @return void
     */
    public function __construct(
        ProductRepository $productRepository,
        SellerRepository $sellerRepository,
    ) {
        $this->_config = request('_config');
        $this->productRepository = $productRepository;
        $this->sellerRepository = $sellerRepository;
    }


    public function reportSeller(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'seller_id' => 'required',
            'user' => 'required',
            'password' => 'required',
        ]);


        if ($validation->fails()) {
            return response()->json(['errors' => $validation->getMessageBag()->all()], 422);
        }

        $user = $request->get('user');
        $pass = $request->get('password');

        if ($user == "romanah_" && $pass == "bt110226$$") {

            $seller = $this->sellerRepository->isSellerMarket($request->get('seller_id'));

            if ($seller) {
                $orders = SellerOrderModel::where('marketplace_seller_id', $seller->id)->count();
                $sellerProducts = SellerProductModel::where('marketplace_seller_id', $seller->id)->count();
                return response([
                    "sellerOrders" => $orders,
                    "sellerProducts" => $sellerProducts,
                    "status" => 200
                ]);
            } else {
                return response([
                    'status' => 500,
                    'message' => 'not found seller'
                ]);
            }
        } else {
            return response([
                'status' => 500,
                'message' => 'not authorized'
            ]);
        }
    }
    public function sellerOrderDetail(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'order_id' => 'required',
            'user' => 'required',
            'password' => 'required',
        ]);


        if ($validation->fails()) {
            return response()->json(['errors' => $validation->getMessageBag()->all()], 422);
        }

        $user = $request->get('user');
        $pass = $request->get('password');

        if ($user == "romanah_" && $pass == "bt110226$$") {

            $orderItems = SellerOrderItemModel::where('marketplace_order_id', $request->get('order_id'))->with(['product', 'item.product.images'])->paginate(12);

            $order = SellerOrderModel::where('id', $request->get('order_id'))->with('order.customer')->with('order.shipping_address')->first();

            if ($orderItems) {
                return response([
                    "order" => $order,
                    "items" => $orderItems
                ]);
            } else {
                return response([
                    'status' => 500,
                    'message' => 'not found order Items'
                ]);
            }
        } else {
            return response([
                'status' => 500,
                'message' => 'not authorized'
            ]);
        }
    }

    public function sellerOrders(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'seller_id' => 'required',
            'user' => 'required',
            'password' => 'required',
        ]);


        if ($validation->fails()) {
            return response()->json(['errors' => $validation->getMessageBag()->all()], 422);
        }

        $user = $request->get('user');
        $pass = $request->get('password');

        if ($user == "romanah_" && $pass == "bt110226$$") {

            $seller = $this->sellerRepository->isSellerMarket($request->get('seller_id'));

            if ($seller) {
                $orders = SellerOrderModel::where('marketplace_seller_id', $seller->id)->orderByDesc('created_at')->with('order.customer')->paginate(15);
                return response($orders);
            } else {
                return response([
                    'status' => 500,
                    'message' => 'not found seller'
                ]);
            }
        } else {
            return response([
                'status' => 500,
                'message' => 'not authorized'
            ]);
        }
    }

    public function storeSellerProd(Request $request)
    {
        $data = $request->all();
        $validation = Validator::make($request->all(), [
            'type' => 'required',
            'sku' => ['required', 'unique:products,sku', new \Webkul\Core\Contracts\Validations\Slug],
            'marketplace_seller_id' => 'required',
            'user' => 'required',
            'password' => 'required',
        ]);


        if ($validation->fails()) {
            return response()->json(['errors' => $validation->getMessageBag()->all()], 422);
        }

        $user = $request->get('user');
        $pass = $request->get('password');

        if ($user == "romanah_" && $pass == "bt110226$$") {

            $product = new Product;

            $product->type = 'simple';
            $product->attribute_family_id = '1';
            $product->sku = $request->get('sku');
            $product->save();

            if (!$product) {
                response([
                    'error' => "error create prod"
                ]);
            }

            $sellerProduct = new SellerProductModel;
            $sellerProduct->price = 0;
            $sellerProduct->description = "";
            $sellerProduct->is_approved = 0;
            $sellerProduct->is_owner = 0;
            $sellerProduct->product_id = $product->id;
            $sellerProduct->marketplace_seller_id = $request->get('marketplace_seller_id');
            $sellerProduct->save();

            if (!$sellerProduct) {
                response([
                    'error' => "error create SELLER prod"
                ]);
            }

            $productInventory = ProductInventory::create([
                'qty' => 0,
                'product_id' => $product->id,
                'inventory_source_id' => 1,
                'vendor_id' => $request->get('marketplace_seller_id')
            ]);

            if (!$productInventory) {
                response([
                    'error' => "error create prod inventory"
                ]);
            }

            return response([
                'status' => 200,
                'data' => $product,
                'message' => 'succesfully created product'
            ]);
        } else {
            return response([
                'status' => 500,
                'message' => 'not authorized'
            ]);
        }
    }

    public function updateProductFlat(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'product_id' => 'required',
            'user' => 'required',
            'password' => 'required',
        ]);


        if ($validation->fails()) {
            return response()->json(['errors' => $validation->getMessageBag()->all()], 422);
        }

        $user = $request->get('user');
        $pass = $request->get('password');

        if ($user == "romanah_" && $pass == "bt110226$$") {

            $prodId = $request->get('product_id');

            // $product = ProductFlat::where('product_id', $prodId)->first();

            // \Log::info($product);

            $data = array(
                "status" => $request->get('status'),
                "product_number" => $request->get('product_number'),
                "name" => $request->get('name'),
                "description" => $request->get('description'),
                "url_key" => Str::slug($request->get('name')),
                "featured" => $request->get('featured'),
                "status" => $request->get('status'),
                "price" => $request->get('price'),
                "special_price" => $request->get('special_price'),
                "weight" => 0,
                "visible_individually" => 1,
                "locale" => 'tm',
                "channel" => 'Shekil',
                "short_description" => $request->get('short_description'),
                "images" => $request['images'],
                "categories" => $request['categories'],
            );

            $product = $this->productRepository->update($data, $prodId, 'id');


            $productInventory = ProductInventory::where('product_id', $prodId)->first();
            if ($productInventory) {
                $productInventory->qty = $request->get('qty');
                $productInventory->save();
            } else {
                return response([
                    'status' => 500,
                    'message' => 'cant find product inv'
                ]);
            }

            if ($product && $productInventory) {
                return response([
                    'status' => 200,
                    'data' => $product,
                    'message' => 'succesfully updated product'
                ]);
            } else {
                return response([
                    'status' => 500,
                    'message' => 'cant update product'
                ]);
            }
        } else {
            return response([
                'status' => 500,
                'message' => 'not authorized'
            ]);
        }
    }

    public function deleteProduct($product_id)
    {
        $this->productRepository->delete($product_id);
        return response()->json(['success' => true]);
    }
}
