<?php

namespace App\Traits;

use App\Models\Wishlist;

trait ProductFormattingTrait
{
    /**
     * Format product response with image_profile and image_gallery.
     */
    protected function formatProductResponse($product, $userId = null): array
    {
        $productArray = $product->toArray();

        // Get images array
        $images = $product->images ?? [];

        // Set image_profile (first image) and image_gallery (remaining images)
        $productArray['image_profile'] = ! empty($images) ? public_asset_url($images[0]) : null;
        $productArray['image_gallery'] = array_map(function ($img) {
            return public_asset_url($img);
        }, count($images) > 1 ? array_slice($images, 1) : []);

        // Remove raw images array
        unset($productArray['images']);

        // Ensure category_id is always included
        if (! isset($productArray['category_id'])) {
            $productArray['category_id'] = $product->category_id ?? null;
        }

        // Remove the auto-generated category_relation key
        unset($productArray['category_relation']);

        // Add category and subcategory data if relationship is loaded
        if ($product->relationLoaded('categoryRelation') && $product->categoryRelation) {
            $category = $product->categoryRelation;

            if ($category->isSubcategory()) {
                if (! $category->relationLoaded('parent')) {
                    $category->load('parent');
                }

                if ($category->parent) {
                    $productArray['subcategory_data'] = $category->toArray();
                    $productArray['category_data'] = $category->parent->toArray();
                } else {
                    $productArray['category_data'] = $category->toArray();
                }
            } else {
                $productArray['category_data'] = $category->toArray();
            }
        }

        // Add is_wishlist flag if userId is provided
        if ($userId) {
            $productArray['is_wishlist'] = Wishlist::where('user_id', $userId)
                ->where('product_id', $product->id)
                ->exists();
        } else {
            $productArray['is_wishlist'] = false;
        }

        return $productArray;
    }

    /**
     * Format paginated products response.
     */
    protected function formatPaginatedResponse($paginatedProducts, $userId = null)
    {
        $formattedData = $paginatedProducts->getCollection()->map(function ($product) use ($userId) {
            return $this->formatProductResponse($product, $userId);
        })->values()->toArray();

        $result = [
            'current_page' => $paginatedProducts->currentPage(),
            'data' => $formattedData,
            'first_page_url' => $paginatedProducts->url(1),
            'from' => $paginatedProducts->firstItem(),
            'last_page' => $paginatedProducts->lastPage(),
            'last_page_url' => $paginatedProducts->url($paginatedProducts->lastPage()),
            'links' => $paginatedProducts->linkCollection(),
            'next_page_url' => $paginatedProducts->nextPageUrl(),
            'path' => $paginatedProducts->path(),
            'per_page' => $paginatedProducts->perPage(),
            'prev_page_url' => $paginatedProducts->previousPageUrl(),
            'to' => $paginatedProducts->lastItem(),
            'total' => $paginatedProducts->total(),
        ];

        foreach ($formattedData as $index => $item) {
            $result[$index] = $item;
        }

        return $result;
    }
}
