<?php
namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\BrandProduct;
use App\Models\CategoryModel;
use App\Models\CategoryProduct;
use App\Models\IndustryProduct;
use App\Models\ProductAttributeModel;
use App\Models\ProductBrandModel;
use App\Models\ProductIndustryModel;
use App\Models\ProductModel;
use App\Models\ProductTypeModel;
use App\Models\SizeModel;
use App\Models\SizeProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;

class ProductController extends Controller
{
    public function products()
    {
        $records = ProductModel::with('category')->get();
        //$records   =  ProductModel::orderBy('id', 'ASC')->get();
        // dd($records);
        return view('backend.products.list', compact('records'));
    }

    public function addProduct($id = '')
    {
        $categoryData = CategoryModel::Where('status', 1)->get();
        $sizeData     = SizeModel::Where('status', 1)->get();
        $industryData = ProductIndustryModel::Where('status', 1)->get();
        $typeData     = ProductTypeModel::Where('status', 1)->get();
        $brandData    = ProductBrandModel::Where('status', 1)->get();
        if ($id > 0) {
            $record       = ProductModel::Where('id', $id)->first();
            $productItems = ProductAttributeModel::Where('product_id', $id)->get();
            $sizeAr       = SizeProduct::Where('product_id', $id)->pluck('size_id')->toArray();
            $brandAr      = BrandProduct::Where('product_id', $id)->pluck('brand_id')->toArray();
            $indusAr      = IndustryProduct::Where('product_id', $id)->pluck('industry_id')->toArray();
            $categoryAr   = CategoryProduct::Where('product_id', $id)->pluck('category_id')->toArray();

            return view('backend.products.edit', compact('brandAr', 'indusAr', 'categoryAr', 'sizeAr', 'record', 'productItems', 'categoryData', 'sizeData', 'brandData', 'typeData', 'industryData'));
        } else {
            return view('backend.products.add', compact('categoryData', 'sizeData', 'typeData', 'brandData', 'industryData'));
        }
    }

    public function uploadProducts(Request $request)
    {
        $file = $request->file('products');
        if (! $file || ! $file->isValid()) {
            return back()->with('error', 'Invalid file');
        }

        if ($file->isValid()) {
            $filename = $file->getRealPath();
            $handle   = fopen($filename, 'r');
            // if (($handle = fopen($filename, 'r')) !== false) {
            fgetcsv($handle);

            while (($importData = fgetcsv($handle, 10000, ",")) !== false) {
                if ($importData[0] !== 'S.NO') {
                    $name     = stripslashes($importData[1]);
                    $category = stripslashes($importData[2]);
                    $industry = array_map(fn($v) => trim($v), explode("/", stripslashes(trim($importData[3]))));
                    $brand    = array_map(fn($v) => trim($v), explode("/", stripslashes($importData[4])));
                    $size     = array_map(fn($v) => trim($v), explode("/", stripslashes($importData[5])));
                    DB::enableQueryLog();
                    $sizeId     = SizeModel::WhereIn('size', $size)->pluck('id')->toArray();
                    $industryId = ProductIndustryModel::WhereIn('industry', $industry)->pluck('id')->toArray();
                    $brandId    = ProductBrandModel::WhereIn('brand', $brand)->pluck('id')->toArray();
                    $categoryId = CategoryModel::Where('category_name', trim($category))->value('id');

                    $insertArr = [
                        'product_name' => $name,
                    ];
                    $insert = ProductModel::create($insertArr);
                    if ($insert['id'] > 0) {

                        $cateAr = [
                            'product_id'  => $insert['id'],
                            'category_id' => $categoryId,
                        ];
                        CategoryProduct::create($cateAr);

                        foreach ($industryId as $val) {
                            $indusarr = [
                                'product_id'  => $insert['id'],
                                'industry_id' => $val,
                            ];
                            IndustryProduct::create($indusarr);
                        }

                        foreach ($brandId as $val) {
                            $brandarr = [
                                'product_id' => $insert['id'],
                                'brand_id'   => $val,
                            ];
                            BrandProduct::create($brandarr);
                        }

                        foreach ($sizeId as $val) {
                            $sizearr = [
                                'product_id' => $insert['id'],
                                'size_id'    => $val,
                            ];
                            SizeProduct::create($sizearr);
                        }
                    }
                }

            }
            fclose($handle);
            // }
        }
    }

    public function storeUpdateproducts(Request $request)
    {
        $input               = $request->all();
        $id                  = $input['id'];
        $product_name        = isset($input['product_name']) ? $input['product_name'] : '';
        $category_id         = isset($input['category_id']) ? $input['category_id'] : '';
        $industry_id         = isset($input['industry_id']) ? $input['industry_id'] : '';
        $brand_id            = isset($input['brand_id']) ? $input['brand_id'] : '';
        $type_id             = isset($input['type_id']) ? $input['type_id'] : '';
        $product_description = isset($input['product_description']) ? $input['product_description'] : '';
        $size_type           = isset($input['size_type']) ? $input['size_type'] : '';
        $product_size        = isset($input['size']) ? $input['size'] : '';
        $item_id             = isset($input['item_id']) ? $input['item_id'] : '';
        $product_image       = isset($input['product_image']) ? $input['product_image'] : '';
        $broucher            = isset($input['broucher']) ? $input['broucher'] : '';

        if ($id == "") {
            /* Insert */
            $insertArr = [
                'product_name'        => $product_name,
                'category_id'         => $category_id,
                //   'industry_id'    => implode(",", $industry_id),
                //   'brand_id'    => implode(",", $brand_id),
                //  'type_id'    => $type_id,
                //   'size_type' => $size_type,
                'product_description' => $product_description,
            ];

            if ($request->hasFile('broucher')) {
                $broucher     = $request->file('broucher');
                $broucherName = 'broucher' . time() . '_' . str_replace(' ', '_', $broucher->getClientOriginalName());
                $broucher->move(public_path('/uploads/broucher/'), $broucherName);
                $broucherUrl           = URL::to('/') . '/uploads/broucher/' . $broucherName;
                $insertArr['broucher'] = $broucherUrl;
            }

            $insert = ProductModel::create($insertArr);
            if ($insert['id'] > 0) {

                // foreach ($category_id as $val) {
                //     $cateAr = array(
                //         'product_id'   => $insert['id'],
                //         'category_id'   => $val
                //     );
                //     CategoryProduct::create($cateAr);
                // }
                if (isset($industry_id) && count($industry_id) > 0) {
                    foreach ($industry_id as $val) {
                        $indusarr = [
                            'product_id'  => $insert['id'],
                            'industry_id' => $val,
                        ];
                        IndustryProduct::create($indusarr);
                    }
                }

                if (isset($brand_id) && count($brand_id) > 0) {
                    foreach ($brand_id as $val) {
                        $brandarr = [
                            'product_id' => $insert['id'],
                            'brand_id'   => $val,
                        ];
                        BrandProduct::create($brandarr);
                    }
                }

                if (isset($product_size) && count($product_size) > 0) {
                    foreach ($product_size as $val) {
                        $sizearr = [
                            'product_id' => $insert['id'],
                            'size_id'    => $val,
                        ];
                        SizeProduct::create($sizearr);
                    }
                }

            }

            foreach ($request->file('product_image') as $k => $image) {
                $insertAr = [
                    'product_id' => $insert['id'],
                ];
                if (isset($request->file('product_image')[$k])) {
                    $image     = $request->file('product_image')[$k];
                    $imageName = 'product_image' . time() . '_' . str_replace(' ', '_', $image->getClientOriginalName());
                    $image->move(public_path('/uploads/product_image/'), $imageName);
                    $imageUrl                  = URL::to('/') . '/uploads/product_image/' . $imageName;
                    $insertAr['product_image'] = $imageUrl;
                }
                ProductAttributeModel::create($insertAr);
            }
            return redirect()->route('products')->with('success', 'Pages Saved Successfully');
        } else {
            $insertArr = [
                'product_name'        => $product_name,
                'category_id'         => $category_id,
                // 'type_id'         => $type_id,
                //  'size_type'         => $size_type,
                'product_description' => $product_description,
            ];
            if ($request->hasFile('broucher') != '') {
                $broucher     = $request->file('broucher');
                $broucherName = 'broucher' . time() . '_' . str_replace(' ', '_', $broucher->getClientOriginalName());
                $broucher->move(public_path('/uploads/broucher/'), $broucherName);
                $broucherUrl           = URL::to('/') . '/uploads/broucher/' . $broucherName;
                $insertArr['broucher'] = $broucherUrl;
            }
            $update = ProductModel::Where('id', $id)->update($insertArr);

            CategoryProduct::Where('product_id', $id)->delete();

            // foreach ($category_id as $val) {
            //     $cateAr = array(
            //         'product_id'   => $id,
            //         'category_id'   => $val
            //     );
            //     CategoryProduct::create($cateAr);
            // }

            if (isset($industry_id) && count($industry_id) > 0) {
                IndustryProduct::Where('product_id', $id)->delete();
                foreach ($industry_id as $val) {
                    $indusarr = [
                        'product_id'  => $id,
                        'industry_id' => $val,
                    ];
                    IndustryProduct::create($indusarr);
                }
            }

            if (isset($brand_id) && count($brand_id) > 0) {
                BrandProduct::Where('product_id', $id)->delete();
                foreach ($brand_id as $val) {
                    $brandarr = [
                        'product_id' => $id,
                        'brand_id'   => $val,
                    ];
                    BrandProduct::create($brandarr);
                }
            }

            if (isset($product_size) && count($product_size) > 0) {
                foreach ($product_size as $val) {
                    SizeProduct::Where('product_id', $id)->delete();
                    $sizearr = [
                        'product_id' => $id,
                        'size_id'    => $val,
                    ];
                    SizeProduct::create($sizearr);
                }
            }

            foreach ($item_id as $k => $val) {
                if ($val == '' || $val == 0) {
                    /** if id is not new list will insert */
                    foreach ($request->file('product_image') as $k => $image) {
                        $insertA = [
                            'product_id' => $id,
                        ];
                        if (isset($request->file('product_image')[$k])) {
                            $image     = $request->file('product_image')[$k];
                            $imageName = 'product_image' . time() . '_' . str_replace(' ', '_', $image->getClientOriginalName());
                            $image->move(public_path('/uploads/product_image/'), $imageName);
                            $imageUrl                 = URL::to('/') . '/uploads/product_image/' . $imageName;
                            $insertA['product_image'] = $imageUrl;
                        }
                        ProductAttributeModel::create($insertA);
                    }
                } else {
                    /** if id is available new list will update */
                    if (isset($request->file('product_image')[$k])) {
                        $image     = $request->file('product_image')[$k];
                        $imageName = 'product_image' . time() . '_' . str_replace(' ', '_', $image->getClientOriginalName());
                        $image->move(public_path('/uploads/product_image/'), $imageName);
                        $imageUrl                  = URL::to('/') . '/uploads/product_image/' . $imageName;
                        $updateAr['product_image'] = $imageUrl;
                        ProductAttributeModel::Where('product_id', $id)->Where('id', $val)->update($updateAr);
                    }
                }
            }
            return redirect()->route('products')->with('success', 'Product Updated Successfully');
        }
    }
}
