<?php

namespace  App\Http\Repositories;

use App\Models\Product;
use App\Models\Category;
use App\Models\ProductCategory;
use App\Models\ProductAddon;
use App\Models\Shop;
use Image;
use Illuminate\Support\Str;
use DB;
use File;

class CatalogProductRepository{

    public function get($request)
    {
        $column = ['id', 'name', 'slug', 'position', 'updated_at', 'id'];
        $searchColumns = ['name', 'slug', 'position', 'updated_at', 'id'];
        $search = $request['search'];
        $order = $request['orderedColumn'];
        $orderBy = $request['orderBy'];

        // Query
        $query = Product::distinct();

        // search
        if ($search != '') {
            $query->where(function ($q) use ($search, $searchColumns) {
                foreach ($searchColumns as $key => $value) {
                    ($key == 0) ? $q->where($value, 'LIKE', '%' . $search . '%') : $q->orWhere($value, 'LIKE', '%' . $search . '%');
                }
            });
        }

        // sorting
        ($order == '') ? $query->orderByDesc('id') : $query->orderBy($order, $orderBy);

        return $query->paginate(isset($request['perPage']) ? $request['perPage'] : 15);
    }

    public function store($request)
    {
        $data = $request->validated();

        $doc=$request->file("image");
        if (!empty($doc)) {
            if(explode("/",$doc->getClientMimeType())[0] == "image"){
                $data["image"]=$this->imageUpload($doc,'catalog/product/images/');
            }else{
                $data["image"]=$this->documentUpload($doc,'catalog/product/images/');
            }
        }

        $error = 0;
        if(Product::create($data)){
            $last_inserted_id=DB::getPdo()->lastInsertId();
            if($request->category_id){
                if(!ProductCategory::create(["product_id"=>$last_inserted_id,"category_id"=>$request->category_id])){
                    $error++;
                }
            }
            if($request->byProducts){
                foreach($request->byProducts as $byProduct){
                    $product_addon =  new ProductAddon();
                    $product_addon->product_id = $last_inserted_id;
                    $product_addon->addon_id = $byProduct['value'];
                    if(!$product_addon->save()){
                        $error++;
                    }
                }
            }
            if($error>0){
                Product::where("id",$last_inserted_id)->delete();
                ProductAddon::where("product_id",$last_inserted_id)->delete();
                ProductCategory::where("product_id",$last_inserted_id)->delete();
            }
        }

        return true;
    }

    public function update($request,$product)
    {
        $data = $request->validated();
        $doc=$request->file("image");
        if (!empty($doc)) {
            if(explode("/",$doc->getClientMimeType())[0] == "image"){
                $data["image"]=$this->imageUpload($doc,'catalog/product/images/');
            }else{
                $data["image"]=$this->documentUpload($doc,'catalog/product/images/');
            }
        }

        $error = 0;
        if($product->update($data)){
            if($request->category_id){
                ProductCategory::where("product_id",$product->id)->delete();
                if(!ProductCategory::create(["product_id"=>$product->id,"category_id"=>$request->category_id])){
                    $error++;
                }
            }
            if($request->byProducts){
                ProductAddon::where("product_id",$product->id)->delete();
                foreach($request->byProducts as $byProduct){
                    $product_addon =  new ProductAddon();
                    $product_addon->product_id = $product->id;
                    $product_addon->addon_id = $byProduct['value'];
                    if(!$product_addon->save()){
                        $error++;
                    }
                }
            }
            if($error>0){
                Product::where("id",$product->id)->delete();
                ProductAddon::where("product_id",$product->id)->delete();
                ProductCategory::where("product_id",$product->id)->delete();
            }
        }

        return true;
    }

    // public function destroy($additive): bool
    // {
    //     try {
    //         $additive = Additive::find($additive);
    //         $additive->delete();
    //         return true;
    //     } catch (\Throwable $th) {
    //         return false;
    //     }
    // }

    //Image Upload
    public function imageUpload($image,$folder)
    {
        $path = [];
        $x = 10;
        if (isset($image) && !empty($image)) {
            $imageName = Str::random($length = 10) . time() . '.' . $image->extension();
            $path = $folder. $imageName;
            if (!is_dir(storage_path('app/public/'.$folder))) mkdir(storage_path('app/public/'.$folder), 0777, TRUE);
            // if(!File::isDirectory(storage_path('app/public/'.$folder))){
            //     File::makeDirectory(storage_path('app/public/'.$folder));
            // }
            $img = Image::make($image->getRealPath());
            $img->save(storage_path('app/public/'.$path), $x);
        }
        return $path;
    }

    // document upload
    public function documentUpload($document,$folder)
    {
        $path = [];
        if (isset($document)) {
            $documentName = Str::random($length = 10) . time() . '.' . $document->extension();
            $path =$folder.$documentName;
            if (!is_dir(storage_path('app/public/'.$folder))) mkdir(storage_path('app/public/'.$folder), 0777, TRUE);
            $document->move(storage_path('app/public/'.$folder), $documentName);
        }
        return $path;
    }

    public function dropdown_shops()
    {
        return Shop::where("status",1)->select("id as value","name as label")->orderBy("name","asc")->get();
    }

    public function dropdown_products()
    {
        return Product::where("status",1)->select("id as value","name as label","image")->orderBy("name","asc")->get();
    }

    public function dropdown_categories()
    {
        return Category::where("status",1)->select("id as value","name as label")->orderBy("name","asc")->get();
    }

}
