<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use App\Models\ProductImage;
use App\Models\ProductVariant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AdminProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $products = Product::with(['category', 'images', 'primaryImage', 'variants'])
            ->orderBy('created_at', 'desc')
            ->paginate((int) $request->input('per_page', 20));

        return response()->json([
            'success' => true,
            'data' => ProductResource::collection($products),
            'meta' => [
                'current_page' => $products->currentPage(),
                'last_page' => $products->lastPage(),
                'total' => $products->total(),
            ]
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:categories,id',
            'name' => 'required|string|max:255',
            'sku' => 'required|string|unique:products,sku',
            'short_description' => 'nullable|string',
            'description' => 'nullable|string',
            'price' => 'nullable|numeric',
            'price_on_request' => 'boolean',
            'availability' => 'nullable|string',
            'stock_status' => 'nullable|string',
            'featured' => 'boolean',
            'new_arrival' => 'boolean',
            'best_seller' => 'boolean',
            'editor_pick' => 'boolean',
            'status' => 'nullable|string',
            'material' => 'nullable|string',
            'color' => 'nullable|string',
            'finish' => 'nullable|string',
            'dimensions' => 'nullable|string',
            'weight' => 'nullable|string',
            'care_instructions' => 'nullable|string',
            'shipping_information' => 'nullable|string',
            'seo_title' => 'nullable|string',
            'seo_description' => 'nullable|string',
            'images' => 'nullable|array',
            'variants' => 'nullable|array',
        ]);

        $validated['slug'] = Str::slug($validated['name']) . '-' . Str::random(4);

        $product = Product::create($validated);

        // Process images if provided
        if (!empty($validated['images'])) {
            foreach ($validated['images'] as $idx => $img) {
                ProductImage::create([
                    'product_id' => $product->id,
                    'image_path' => is_array($img) ? ($img['image_path'] ?? '') : $img,
                    'sort_order' => $idx + 1,
                    'is_primary' => $idx === 0,
                ]);
            }
        }

        // Process variants if provided
        if (!empty($validated['variants'])) {
            foreach ($validated['variants'] as $v) {
                ProductVariant::create([
                    'product_id' => $product->id,
                    'name' => $v['name'] ?? 'Variant',
                    'sku' => $v['sku'] ?? ($product->sku . '-V'),
                    'price' => $v['price'] ?? $product->price,
                    'stock_status' => $v['stock_status'] ?? 'in_stock',
                    'attributes' => $v['attributes'] ?? null,
                ]);
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Product created successfully',
            'data' => new ProductResource($product->load(['category', 'images', 'variants'])),
        ], 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $product = Product::findOrFail($id);

        $validated = $request->validate([
            'category_id' => 'sometimes|exists:categories,id',
            'name' => 'sometimes|string|max:255',
            'sku' => 'sometimes|string|unique:products,sku,' . $id,
            'short_description' => 'nullable|string',
            'description' => 'nullable|string',
            'price' => 'nullable|numeric',
            'price_on_request' => 'boolean',
            'availability' => 'nullable|string',
            'stock_status' => 'nullable|string',
            'featured' => 'boolean',
            'new_arrival' => 'boolean',
            'best_seller' => 'boolean',
            'editor_pick' => 'boolean',
            'status' => 'nullable|string',
            'material' => 'nullable|string',
            'color' => 'nullable|string',
            'finish' => 'nullable|string',
            'dimensions' => 'nullable|string',
            'weight' => 'nullable|string',
            'care_instructions' => 'nullable|string',
            'shipping_information' => 'nullable|string',
            'seo_title' => 'nullable|string',
            'seo_description' => 'nullable|string',
            'images' => 'nullable|array',
        ]);

        if (isset($validated['name']) && $validated['name'] !== $product->name) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        $product->update($validated);

        if ($request->has('images') && is_array($request->input('images'))) {
            ProductImage::where('product_id', $product->id)->delete();
            $imgs = $request->input('images');
            $hasPrimary = false;

            foreach ($imgs as $idx => $img) {
                $isPrimary = is_array($img) ? (!empty($img['is_primary'])) : ($idx === 0);
                if ($isPrimary) $hasPrimary = true;

                ProductImage::create([
                    'product_id' => $product->id,
                    'image_path' => is_array($img) ? ($img['image_path'] ?? '') : $img,
                    'sort_order' => $idx + 1,
                    'is_primary' => $isPrimary,
                ]);
            }

            // Fallback: Ensure at least one image is marked primary if none was selected
            if (!$hasPrimary) {
                $firstImg = ProductImage::where('product_id', $product->id)->first();
                if ($firstImg) {
                    $firstImg->update(['is_primary' => true]);
                }
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Product updated successfully',
            'data' => new ProductResource($product->fresh(['category', 'images', 'variants'])),
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $product = Product::findOrFail($id);
        $product->delete();

        return response()->json([
            'success' => true,
            'message' => 'Product deleted successfully',
        ]);
    }
}
