<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\ProductRequest;
use App\Models\ProductManagement\Category;
use App\Models\Polymorphs\Media;
use App\Models\ProductManagement\Product;
use App\Models\ProductManagement\Tag;
use App\Services\CartTempDeletion;
use App\Services\ImageService;
use App\Traits\ImageUploadTrait;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;

class ProductController extends Controller{
    use ImageUploadTrait;


    public function __construct(){

        $this->middleware('permission:product-list')
            ->only(["index"]);

        $this->middleware('permission:product-show')
            ->only(["show"]);

        $this->middleware('permission:product-create')
            ->only(["store","create"]);

        $this->middleware('permission:product-update')
            ->only(['update',"edit"]);

        $this->middleware('permission:product-delete')
            ->only(['destroy',"removeImage"]);

    }

    public function index(){
        if (request()->ajax()){
           return Product::with([
                            "tags" => fn ($query) => $query->select("name")
                           ])
                          ->active()
                          ->get();
        }
        $products = Product::with('category', 'tags')
                            ->when(request()->keyword != null, function ($query) {
                                $query->search(request()->keyword);
                            })
                            ->when(request()->active != null, function ($query) {
                                $query->whereStatus(request()->active);
                            })
                            ->orderBy(request()->sortBy ?? 'id', request()->orderBy ?? 'desc')
                            ->paginate(request()->limitBy ?? 10);

        return view('backend.products.index', compact('products'));
    }

    public function create(): View{
        $categories = Category::active()->get(['id', 'name']);
        $tags = Tag::active()->get(['id', 'name']);

        return view('backend.products.create', compact('categories', 'tags'));
    }

    public function store(ProductRequest $request): RedirectResponse{
        DB::beginTransaction();
        try {
            if ($request->validated()){
                $product = Product::create($request->except('tags', 'images', '_token',"quantity","multiselect"));
                $product->tags()->attach($request->tags);

                $options = ["resize" => ["width" => 500, "height" => null,]];

                /**
                 * @var bool
                 */
                $upload = $product->uploadFiles($request->images ?? [],$options);

                //[$success] = (new CartTempDeletion)->processToDeleteMedias($product);

                clear_cache();
                DB::commit();

                return redirect()->route('admin.products.index')->with([
                    'message' => action_message("create"),
                    'alert-type' => 'success'
                ]);
            }

        }catch (\Exception $exception){
            DB::rollBack();
            write_log("products/create",$exception,"error");
        }

        return back()->with([
            'message' => action_message("create",false),
            'alert-type' => 'error'
        ]);
    }

    public function show(Product $product): View{
        return view('backend.products.show', compact('product'));
    }

    public function edit(Product $product): View{
        $categories = Category::active()->get(['id', 'name']);
        $tags = Tag::active()->get(['id', 'name']);

        return view('backend.products.edit', compact('product', 'categories', 'tags'));
    }

    /**
     * @throws Throwable
     */
    public function update(ProductRequest $request, Product $product,CartTempDeletion $cartTempDeletion): RedirectResponse{
        if ($request->validated()) {
            $product->update($request->except('tags', 'images', '_token',"quantity","multiselect"));
            $product->tags()->sync($request->tags);

            $options = ["resize" => ["width" => 500, "height" => null,]];

            /**
             * @var bool
             */
            $upload = $product->uploadFiles($request->images ?? [],$options);

            clear_cache();

            return redirect()->route('admin.products.index')->with([
                'message' => action_message("update"),
                'alert-type' => 'success'
            ]);
        }

        return back()->with([
            'message' => action_message("update",false),
            'alert-type' => 'error'
        ]);
    }

    public function destroy(Product $product): RedirectResponse{
        $product->delete();

        clear_cache();
        return redirect()->route('admin.products.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }

    public function removeImage(Request $request){
        $media = Media::find($request->mediaId) ;

        write_log("media",$media);
        if ($media){
            $media->delete();
        }
        clear_cache();

       // return response()->json(['success' => true]);

        return response()->json(['success' => true, 'message' => 'Image supprimée.']);

    }
}
