<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductImage;
use App\Models\ProductVideo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProductController extends Controller
{
    /**
     * List all products (admin).
     */
    public function index(Request $request)
    {
        $query = Product::with(['weights.weightUnit', 'images', 'category:id,name_ar,name_en'])
            ->withTrashed();

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name_ar', 'like', "%{$search}%")
                    ->orWhere('name_en', 'like', "%{$search}%")
                    ->orWhere('sku', 'like', "%{$search}%");
            });
        }

        // Filter by category
        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        // Filter active/inactive
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        // Filter featured
        if ($request->filled('is_featured')) {
            $query->where('is_featured', $request->boolean('is_featured'));
        }

        // Sort
        $sortField = $request->get('sort', 'created_at');
        $sortDirection = $request->get('direction', 'desc');
        $allowedSorts = ['created_at', 'name_ar', 'name_en', 'base_price', 'sales_count', 'views_count', 'avg_rating'];
        if (in_array($sortField, $allowedSorts)) {
            $query->orderBy($sortField, $sortDirection === 'asc' ? 'asc' : 'desc');
        }

        return response()->json($query->paginate($request->get('per_page', 20)));
    }

    /**
     * Create a new product.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:products,slug',
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'short_description_ar' => 'nullable|string|max:500',
            'short_description_en' => 'nullable|string|max:500',
            'category_id' => 'required|exists:categories,id',
            'sku' => 'nullable|string|max:100|unique:products,sku',
            'base_price' => 'required|numeric|min:0',
            'cost_price' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'is_new' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:500',
            'weights' => 'nullable|array',
            'weights.*.weight_unit_id' => 'required_with:weights|exists:weight_units,id',
            'weights.*.weight_value' => 'required_with:weights|numeric|min:0',
            'weights.*.price' => 'required_with:weights|numeric|min:0',
            'weights.*.compare_price' => 'nullable|numeric|min:0',
            'weights.*.cost_price' => 'nullable|numeric|min:0',
            'weights.*.stock' => 'integer|min:0',
            'weights.*.sku' => 'nullable|string|max:100',
            'weights.*.barcode' => 'nullable|string|max:100',
            'weights.*.is_default' => 'boolean',
            'images' => 'nullable|array',
            'images.*' => 'image|max:5120',
            'videos' => 'nullable|array',
            'videos.*' => 'file|mimes:mp4,mov,avi|max:51200',
        ]);

        return DB::transaction(function () use ($request) {
            $slug = $request->slug ?? Str::slug($request->name_en ?: $request->name_ar);

            // Ensure unique slug
            $originalSlug = $slug;
            $counter = 1;
            while (Product::where('slug', $slug)->exists()) {
                $slug = $originalSlug . '-' . $counter++;
            }

            $product = Product::create([
                'name_ar' => $request->name_ar,
                'name_en' => $request->name_en,
                'slug' => $slug,
                'description_ar' => $request->description_ar,
                'description_en' => $request->description_en,
                'short_description_ar' => $request->short_description_ar,
                'short_description_en' => $request->short_description_en,
                'category_id' => $request->category_id,
                'sku' => $request->sku,
                'base_price' => $request->base_price,
                'cost_price' => $request->cost_price,
                'is_active' => $request->boolean('is_active', true),
                'is_featured' => $request->boolean('is_featured', false),
                'is_new' => $request->boolean('is_new', false),
                'meta_title' => $request->meta_title,
                'meta_description' => $request->meta_description,
                'meta_keywords' => $request->meta_keywords,
            ]);

            // Create weights
            if ($request->has('weights')) {
                foreach ($request->weights as $index => $weightData) {
                    $product->weights()->create([
                        'weight_unit_id' => $weightData['weight_unit_id'],
                        'weight_value' => $weightData['weight_value'],
                        'price' => $weightData['price'],
                        'compare_price' => $weightData['compare_price'] ?? null,
                        'cost_price' => $weightData['cost_price'] ?? null,
                        'stock' => $weightData['stock'] ?? 0,
                        'sku' => $weightData['sku'] ?? null,
                        'barcode' => $weightData['barcode'] ?? null,
                        'is_default' => $weightData['is_default'] ?? ($index === 0),
                        'sort_order' => $index,
                    ]);
                }
            }

            // Upload images
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $index => $image) {
                    $path = $image->store('products/images', 'public');
                    ProductImage::create([
                        'product_id' => $product->id,
                        'image_path' => $path,
                        'alt_text' => $product->name_ar,
                        'sort_order' => $index,
                        'is_primary' => $index === 0,
                    ]);
                }
            }

            // Upload videos
            if ($request->hasFile('videos')) {
                foreach ($request->file('videos') as $index => $video) {
                    $path = $video->store('products/videos', 'public');
                    ProductVideo::create([
                        'product_id' => $product->id,
                        'video_path' => $path,
                        'sort_order' => $index,
                    ]);
                }
            }

            $product->load(['weights.weightUnit', 'images', 'videos', 'category']);

            return response()->json([
                'message' => 'تم إنشاء المنتج بنجاح',
                'data' => $product,
            ], 201);
        });
    }

    /**
     * Show single product (admin).
     */
    public function show(Product $product)
    {
        $product->load(['weights.weightUnit', 'images', 'videos', 'category', 'reviews.customer']);

        return response()->json(['data' => $product]);
    }

    /**
     * Update product.
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name_ar' => 'sometimes|required|string|max:255',
            'name_en' => 'sometimes|required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:products,slug,' . $product->id,
            'description_ar' => 'nullable|string',
            'description_en' => 'nullable|string',
            'short_description_ar' => 'nullable|string|max:500',
            'short_description_en' => 'nullable|string|max:500',
            'category_id' => 'sometimes|required|exists:categories,id',
            'sku' => 'nullable|string|max:100|unique:products,sku,' . $product->id,
            'base_price' => 'sometimes|required|numeric|min:0',
            'cost_price' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'is_new' => 'boolean',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:500',
            'weights' => 'nullable|array',
            'new_images' => 'nullable|array',
            'new_images.*' => 'image|max:5120',
            'new_videos' => 'nullable|array',
            'new_videos.*' => 'file|mimes:mp4,mov,avi|max:51200',
            'remove_images' => 'nullable|array',
            'remove_images.*' => 'integer|exists:product_images,id',
            'remove_videos' => 'nullable|array',
            'remove_videos.*' => 'integer|exists:product_videos,id',
        ]);

        return DB::transaction(function () use ($request, $product) {
            $product->update($request->only([
                'name_ar', 'name_en', 'slug', 'description_ar', 'description_en',
                'short_description_ar', 'short_description_en', 'category_id',
                'sku', 'base_price', 'cost_price', 'is_active', 'is_featured',
                'is_new', 'meta_title', 'meta_description', 'meta_keywords',
            ]));

            // Update weights if provided
            if ($request->has('weights')) {
                $product->weights()->delete();
                foreach ($request->weights as $index => $weightData) {
                    $product->weights()->create([
                        'weight_unit_id' => $weightData['weight_unit_id'],
                        'weight_value' => $weightData['weight_value'],
                        'price' => $weightData['price'],
                        'compare_price' => $weightData['compare_price'] ?? null,
                        'cost_price' => $weightData['cost_price'] ?? null,
                        'stock' => $weightData['stock'] ?? 0,
                        'sku' => $weightData['sku'] ?? null,
                        'barcode' => $weightData['barcode'] ?? null,
                        'is_default' => $weightData['is_default'] ?? ($index === 0),
                        'sort_order' => $index,
                    ]);
                }
            }

            // Remove specified images
            if ($request->has('remove_images')) {
                $imagesToRemove = ProductImage::whereIn('id', $request->remove_images)
                    ->where('product_id', $product->id)
                    ->get();
                foreach ($imagesToRemove as $img) {
                    Storage::disk('public')->delete($img->image_path);
                    $img->delete();
                }
            }

            // Remove specified videos
            if ($request->has('remove_videos')) {
                $videosToRemove = ProductVideo::whereIn('id', $request->remove_videos)
                    ->where('product_id', $product->id)
                    ->get();
                foreach ($videosToRemove as $vid) {
                    if ($vid->video_path) {
                        Storage::disk('public')->delete($vid->video_path);
                    }
                    $vid->delete();
                }
            }

            // Upload new images
            if ($request->hasFile('new_images')) {
                $maxSort = $product->images()->max('sort_order') ?? -1;
                foreach ($request->file('new_images') as $index => $image) {
                    $path = $image->store('products/images', 'public');
                    ProductImage::create([
                        'product_id' => $product->id,
                        'image_path' => $path,
                        'alt_text' => $product->name_ar,
                        'sort_order' => $maxSort + $index + 1,
                        'is_primary' => false,
                    ]);
                }
            }

            // Upload new videos
            if ($request->hasFile('new_videos')) {
                $maxSort = $product->videos()->max('sort_order') ?? -1;
                foreach ($request->file('new_videos') as $index => $video) {
                    $path = $video->store('products/videos', 'public');
                    ProductVideo::create([
                        'product_id' => $product->id,
                        'video_path' => $path,
                        'sort_order' => $maxSort + $index + 1,
                    ]);
                }
            }

            $product->load(['weights.weightUnit', 'images', 'videos', 'category']);

            return response()->json([
                'message' => 'تم تحديث المنتج بنجاح',
                'data' => $product,
            ]);
        });
    }

    /**
     * Delete product (soft delete).
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return response()->json([
            'message' => 'تم حذف المنتج بنجاح',
        ]);
    }

    /**
     * Toggle product active status.
     */
    public function toggleActive(Product $product)
    {
        $product->update(['is_active' => !$product->is_active]);

        return response()->json([
            'message' => $product->is_active ? 'تم تفعيل المنتج' : 'تم تعطيل المنتج',
            'data' => $product,
        ]);
    }

    /**
     * Restore soft-deleted product.
     */
    public function restore(int $id)
    {
        $product = Product::withTrashed()->findOrFail($id);
        $product->restore();

        return response()->json([
            'message' => 'تم استعادة المنتج بنجاح',
            'data' => $product,
        ]);
    }
}
