<?php

namespace App\Http\Controllers\Frontend;

use App\Events\NotifyManagementEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProductRequest;
use App\Jobs\PostViewJob;
use App\Repositories\BrandRepository;
use App\Repositories\CategoryRepository;
use App\Repositories\ColorRepository;
use App\Repositories\ReviewRepository;
use App\Repositories\SearchKeyRepository;
use App\Repositories\SellingPostRepository;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class ProductController extends Controller
{


    public function index(Request $request, $category = null)
    {
        // Store search key only when actual search parameters exist
        if ($request->query()) {
            SearchKeyRepository::storeOrUpdate($request);
        }

        $products = SellingPostRepository::filterProducts($request, $category)
            ->paginate(9)
            ->withQueryString();

        $conditions = SellingPostRepository::getDistinctConditions();
        $locations = SellingPostRepository::getLocationsWithCount();
        $brands = SellingPostRepository::getBrandsWithCount();
        $DateFilters = SellingPostRepository::getDateFiltersWithCount();
        $allCategories = CategoryRepository::getAll();


        return view('web.products.index', compact(
            'products',
            'conditions',
            'locations',
            'brands',
            'DateFilters',
            'allCategories',
        ));
    }

    public function show($id)
    {
        $product = SellingPostRepository::query()->findOrFail($id);

        $location_name = getLocationName($product->latitude, $product->longitude);
        $relatedProducts = SellingPostRepository::getRelatedProducts($product);

        $user = UserRepository::query()->findOrFail($product->user_id);


        $reviewes = ReviewRepository::query()
            ->where('seller_id', $user->id)
            ->with('reviewer')
            ->get();

        $totalReviews = $reviewes->count();
        $averageRating = $totalReviews > 0 ? number_format($reviewes->avg('rating'), 1) : 0;

        // Dispatch view tracking to queue
        PostViewJob::dispatch($id, auth()->id(), request()->ip());

        return view('web.products.show', compact(
            'product',
            'location_name',
            'relatedProducts',
            'reviewes',
            'totalReviews',
            'averageRating',

        ));
    }


    //create
    public function productAd()
    {
        $colors = ColorRepository::getAll();
        $brands = BrandRepository::query()->active()->get();
        return view('web.products.products-ad', compact('colors', 'brands'));
    }

    public function store(ProductRequest $request)
    {

        if (!auth()->check()) {
            session(['url.intended' => url()->current()]);
            return redirect()->route('user.login')->with('login_required', true);
        }

        try {

            $post = SellingPostRepository::storeByRequest($request, auth()->id());

            $reviewersIds = ReviewRepository::query()->where('seller_id', auth()->id())->pluck('reviewer_id')->toArray(); //When Product will be created. Who will be Notify
            $receiverIds = [null, auth()->id()];
            if (!empty($reviewersIds)) {
                $receiverIds = array_merge($receiverIds, $reviewersIds);
            }

            $senderId = auth()->id();
            $subject = "New Selling Post Created";
            $body = "A new selling post ({$post->name}) has been created by " . auth()->user()->name;

            NotifyManagementEvent::dispatch(
                $receiverIds,
                $senderId,
                $subject,
                $body
            );

            return redirect('/')
                ->with('success', 'Selling post created successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error creating selling post: ' . $e->getMessage());
        }
    }


    public function edit($id)
    {
        $product = SellingPostRepository::findOrFail($id);
        $colors = ColorRepository::getAll();
        $brands = BrandRepository::getAll()->where('is_active', 1);
        $categories = CategoryRepository::getAll();

        // Get assigned categories (parent & child)
        $categoryIds = $product->categories()->pluck('id')->toArray();
        $mainCategoryId = null;
        $subCategoryId = null;
        foreach ($categoryIds as $catId) {
            $cat = $categories->firstWhere('id', $catId);
            if ($cat) {
                if (!$cat->parent_id) {
                    $mainCategoryId = $cat->id;
                } else {
                    $subCategoryId = $cat->id;
                }
            }
        }

        // Load existing thumbnails
        $thumbnail = $product->thumbnails()->where('default', true)->first();
        $additionalImages = $product->thumbnails()->where('default', false)->get();

        return view('web.products.edit', compact(
            'product',
            'colors',
            'brands',
            'categories',
            'thumbnail',
            'additionalImages',
            'mainCategoryId',
            'subCategoryId'
        ));
    }

    public function update(Request $request, $id)
    {

        try {
            $post = SellingPostRepository::findOrFail($id);
            $post = SellingPostRepository::updateByRequest($post, $request);


            return redirect()->route('user.my-ads')
                ->with('success', 'Product updated successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error updating product: ' . $e->getMessage());
        }
    }

    public function makeCopy($id)
    {
        try {
            SellingPostRepository::makeCopypost($id);
            return redirect()->back()->with('success', 'Product copied successfully.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error copying product: ' . $e->getMessage());
        }
    }


    public function postdetails($id)
    {
        $products = SellingPostRepository::getByIdWithRelations($id);
        $location_name = getLocationName($products->latitude, $products->longitude);
        $relatedProducts = SellingPostRepository::getRelatedProducts($products);
        $productImg = SellingPostRepository::query()->findOrFail($id);
        $wishlistCount = SellingPostRepository::query()->findOrFail($id)->wishlistedBy()->count();

        return view('web.products.post-details', compact('products', 'location_name', 'relatedProducts', 'productImg', 'wishlistCount'));
    }
}
