<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Models\Store;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;

class AdminProductController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, User $user)
    {
        if ($request->search) {
            $products = Product::query()
                ->with(['category'])
                ->where('user_id', $user->id)
                ->where('name', 'like', '%' . $request->search . '%')
                ->latest()
                ->paginate(15)
                ->withQueryString();
        } else {
            $products = Product::query()
            ->with(['category'])
            ->where('user_id', $user->id)
            ->latest()
            ->paginate(15);
        }

        return inertia('Product/Admin/Index', [
            'products' => $products,
            'user' => $user,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(User $user)
    {
        return inertia('Product/Admin/Create', [
            'userId' => $user->id,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreProductRequest $request, $userId)
    {
        $store = Store::query()->where('user_id', $userId)->first();
        if (is_null($store)) {
            return Redirect::back()->with('error', 'Please create your store first, so you can add products to your store');
        }
        $productCount = Product::query()->where('store_id', $store->id)->count();

        if ($productCount >= $store->plan) {
            return Redirect::back()->with('error', 'Your have reached the plan, please upgrade your plan so you can add products');
        }

        $imageNames = [];

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $fileName = $image->hashName();
                $contents = file_get_contents($image);
                Storage::disk('public')->put("products/" . $fileName, $contents);
                $imageNames[] = $fileName;
            }
        }

        Product::create([
            'name' => $request->validated('name'),
            'description' => $request->validated('description'),
            'price' => $request->validated('price'),
            'user_id' => $userId,
            'store_id' => $store->id,
            'images' => $imageNames,
        ]);
        return to_route('admin.products.index', $userId)->with('success', 'Product Added successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Product $product, $userId)
    {

        return inertia('Product/Admin/Edit', [
            'product' => $product,
            'userId' => $userId,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateProductRequest $request, Product $product, $userId)
    {
        $store = Store::query()->where('user_id', $userId)->first();
        $productCount = Product::query()->where('store_id', $store->id)->count();

        if ($productCount >= $store->plan) {
            return Redirect::back()->with('error', 'Your have reached the plan, please upgrade your plan so you can add products');
        }

        $imageNames = [];

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $fileName = $image->hashName();
                $contents = file_get_contents($image);
                Storage::disk('public')->put("products/" . $fileName, $contents);
                $imageNames[] = $fileName;
            }
        }

        if ($request->hasFile('images')) {
            $product->update([
                'name' => $request->validated('name'),
                'description' => $request->validated('description'),
                'price' => $request->validated('price'),
                'user_id' => $userId,
                'store_id' => $store->id,
                'images' => $imageNames,
            ]);
        } else {
            $product->update([
                'name' => $request->validated('name'),
                'description' => $request->validated('description'),
                'price' => $request->validated('price'),
                'user_id' => $userId,
                'store_id' => $store->id,
            ]);
        }


        return to_route('admin.products.index', $userId)->with('success', 'Product updated successfully.');
    }

    public function showAllProducts(Request $request)
    {
        if ($request->search) {
            $products = Product::query()
                ->with(['store', 'store.user','category'])
                ->where('name', 'like', '%' . $request->search . '%')
                ->orWhere('price', 'like', $request->search)
                ->orWhereHas('category', function($query) use($request){
                    $query->where('name', 'like', '%' . $request->search . '%');
                })
                ->latest()
                ->paginate(15);
        } else {
            $products = Product::query()->with(['store', 'store.user','category'])->latest()->paginate(15);
        }

        return inertia('Product/Admin/ProductLists', [
            'products' => $products,
        ]);
    }
}
