<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API\Dashboard;

use Carbon\Carbon;
use App\Models\Tag;
use App\Models\Order;
use App\Models\Status;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\TagResource;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

use App\Http\Resources\CategoryResource;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\Dashboard\OrderResource;
use App\Http\Resources\Dashboard\ProductResource;
use App\Http\Resources\Dashboard\ProductDetailsResource;
use App\Http\Resources\Dashboard\ServiceDetailsResource;

class ServiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::where('type', 2)->with(['category', 'status', 'cartItems', 'discounts', 'orderItems', 'reviews', 'images', 'tags']);

        if ($period = $request->input('period')) {
            $validator = Validator::make(['period' => $period], [
                'period' => 'in:24_hours,7_days,30_days,12_months'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'قيمة الفترة غير صحيحة، استخدم 24_hours, 7_days, 30_days, أو 12_months'
                ], 400);
            }

            $startDate = match ($period) {
                '24_hours' => Carbon::now()->subHours(24),
                '7_days' => Carbon::now()->subDays(7),
                '30_days' => Carbon::now()->subDays(30),
                '12_months' => Carbon::now()->subMonths(12),
            };

            $query->where('created_at', '>=', $startDate);
        } elseif ($date = $request->input('date')) {
            $validator = Validator::make(['date' => $date], [
                'date' => 'date_format:m/d/Y'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'صيغة التاريخ غير صحيحة، استخدم mm/dd/yyyy'
                ], 400);
            }

            $formattedDate = Carbon::createFromFormat('m/d/Y', $date)->format('Y-m-d');
            $query->whereDate('created_at', $formattedDate);
        }

        if ($statusId = $request->input('status_id')) {
            $validator = Validator::make(['status_id' => $statusId], [
                'status_id' => 'integer|exists:statuses,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'رقم حالة المنتج غير صحيح أو غير موجود'
                ], 400);
            }

            $query->where('status_id', $statusId);
        }

        if ($productId = $request->input('product_id')) {
            $validator = Validator::make(['product_id' => $productId], [
                'product_id' => 'integer|exists:products,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'رقم المنتج غير صحيح أو غير موجود'
                ], 400);
            }

            $query->where('id', $productId);
        }

        $products = $query->paginate(10);

        return response()->json([
            'message' => 'تم استرجاع المنتجات بنجاح',
            'products' => ProductResource::collection($products),
            'total' => $products->total(),
            'current_page' => $products->currentPage(),
            'last_page' => $products->lastPage()
        ], 200);
    }

    public function show($id)
    {
        try {
            $product = Product::find($id);
            if (!$product) {
                return response()->json([
                    'status' => false,
                    'message' => 'المنتج غير موجود',
                    'error' => 'Product not found',
                ], 404, [], JSON_UNESCAPED_UNICODE);
            }

            $orders = Order::whereHas('order_items', function ($query) use ($id) {
                $query->where('product_id', $id);
            })
                ->with(['order_items.product', 'status', 'user'])
                ->whereIn('status_id', [8, 9, 10])
                ->get();

            return response()->json([
                'status' => true,
                'message' => 'تم استرجاع جميع الطلبات للمنتج بنجاح',
                'product' => new ServiceDetailsResource($product)

            ], 200, [], JSON_UNESCAPED_UNICODE);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'المنتج غير موجود',
                'error' => 'Product not found',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'حدث خطأ أثناء استرجاع الطلبات',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
    public function getCreateEditData()
    {
        try {
            $categories = Category::select('id', 'name')->get();
            $statuses = Status::select('id', 'name')->whereBetween('id', [1, 4])->get();
            $tags = Tag::select('id', 'name')->get();

            return response()->json([
                'message' => 'تم استرجاع بيانات المنتج بنجاح',
                'categories' => CategoryResource::collection($categories),
                'statuses' => $statuses,
                'tags' => TagResource::collection($tags)
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'category_id' => 'required|integer|exists:categories,id',
                'sku' => 'required|string|max:255|unique:products,sku',
                'status_id' => 'required|integer|exists:statuses,id',

                'name' => 'required|array',
                'name.ar' => 'required|string|max:255',
                'name.en' => 'required|string|max:255',

                'description' => 'nullable|array',
                'description.ar' => 'nullable|string',
                'description.en' => 'nullable|string',

                'short_description' => 'nullable|array',
                'short_description.ar' => 'nullable|string|max:500',
                'short_description.en' => 'nullable|string|max:500',

                'image' => 'required|file|image|mimes:jpg,jpeg,png|max:2048',
                'price' => 'required|numeric|min:0',
                'stock' => 'nullable|integer|min:0',
                'publish_at' => 'nullable|date',
                'visibility' => 'required|in:public,private,draft',
                'manufacturer_name' => 'nullable|string|max:255',
                'manufacturer_brand' => 'nullable|string|max:255',
                'label' => 'nullable|string|max:255',
                'gallery' => 'nullable|array',
                'gallery.*' => 'file|image|mimes:jpg,jpeg,png|max:2048',
                'tags' => 'nullable|array',
                'tags.*' => 'integer|exists:tags,id'
            ]);


            if ($validator->fails()) {
                return response()->json([
                    'message' => 'خطأ في التحقق من البيانات',
                    'errors' => $validator->errors()
                ], 422);
            }

            DB::beginTransaction();

            $product = Product::create([
                'category_id'        => $request->category_id,
                'sku'                => $request->sku,
                'status_id'          => $request->status_id,
                'name'               => json_encode($request->name, JSON_UNESCAPED_UNICODE),
                'description'        => $request->description ? json_encode($request->description, JSON_UNESCAPED_UNICODE) : null,
                'short_description'  => $request->short_description ? json_encode($request->short_description, JSON_UNESCAPED_UNICODE) : null,
                'price'              => $request->price,
                'stock'              => $request->stock ?? 0,
                'publish_at'         => $request->publish_at,
                'visibility'         => $request->visibility,
                'manufacturer_name'  => $request->manufacturer_name,
                'manufacturer_brand' => $request->manufacturer_brand,
                'label'              => $request->label,
                'type'              => 2,

            ]);


            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('products', 'public');
                $product->update([
                    'image' => $imagePath,
                ]);
            }

            // Store gallery images
            if ($request->hasFile('gallery')) {
                foreach ($request->file('gallery') as $galleryImage) {
                    $galleryPath = $galleryImage->store('products', 'public');
                    $product->images()->create([
                        'url' => $galleryPath,
                    ]);
                }
            }

            if ($request->has('tags')) {
                $product->tags()->sync($request->input('tags'));
            }

            DB::commit();

            return response()->json([
                'message' => 'تم إنشاء المنتج بنجاح',
                'product' => new ProductResource(
                    Product::with(['category', 'status', 'images', 'tags'])->findOrFail($product->id)
                )
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'category_id' => 'nullable|integer|exists:categories,id',
                'sku' => 'nullable|string|max:255|unique:products,sku,' . $id,
                'status_id' => 'nullable|integer|exists:statuses,id',

                'name' => 'nullable|array',
                'name.ar' => 'nullable|string|max:255',
                'name.en' => 'nullable|string|max:255',

                'description' => 'nullable|array',
                'description.ar' => 'nullable|string',
                'description.en' => 'nullable|string',

                'short_description' => 'nullable|array',
                'short_description.ar' => 'nullable|string|max:500',
                'short_description.en' => 'nullable|string|max:500',

                'image' => 'nullable',
                'price' => 'nullable|numeric|min:0',
                'stock' => 'nullable|integer|min:0',
                'publish_at' => 'nullable|date',
                'visibility' => 'nullable|in:public,private,draft',
                'manufacturer_name' => 'nullable|string|max:255',
                'manufacturer_brand' => 'nullable|string|max:255',
                'label' => 'nullable|string|max:255',
                'gallery' => 'nullable|array',
                'gallery.*' => 'nullable|max:2048',
                'tags' => 'nullable|array',
                'tags.*' => 'nullable|integer|exists:tags,id',
                'gallery_deleted'   => 'nullable|array',
                'gallery_deleted.*' => 'integer|exists:images,id',

            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'خطأ في التحقق من البيانات',
                    'errors' => $validator->errors(),
                ], 422);
            }

            $product = Product::findOrFail($id);

            DB::beginTransaction();

            // نجهز بيانات التحديث
            $updateData = [];

            if ($request->has('category_id')) $updateData['category_id'] = $request->category_id;
            if ($request->has('sku')) $updateData['sku'] = $request->sku;
            if ($request->has('status_id')) $updateData['status_id'] = $request->status_id;

            if ($request->has('name')) $updateData['name'] = json_encode($request->name, JSON_UNESCAPED_UNICODE);
            if ($request->has('description')) $updateData['description'] = json_encode($request->description, JSON_UNESCAPED_UNICODE);
            if ($request->has('short_description')) $updateData['short_description'] = json_encode($request->short_description, JSON_UNESCAPED_UNICODE);

            if ($request->has('price')) $updateData['price'] = $request->price;
            if ($request->has('stock')) $updateData['stock'] = $request->stock;
            if ($request->has('publish_at')) $updateData['publish_at'] = $request->publish_at;
            if ($request->has('visibility')) $updateData['visibility'] = $request->visibility;
            if ($request->has('manufacturer_name')) $updateData['manufacturer_name'] = $request->manufacturer_name;
            if ($request->has('manufacturer_brand')) $updateData['manufacturer_brand'] = $request->manufacturer_brand;
            if ($request->has('label')) $updateData['label'] = $request->label;

            if (!empty($updateData)) {
                $product->update($updateData);
            }

            // تحديث الصورة الرئيسية
            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                // لو رفع صورة جديدة
                if ($product->image && Storage::disk('public')->exists($product->image)) {
                    Storage::disk('public')->delete($product->image);
                }
                $imagePath = $request->file('image')->store('products', 'public');
                $product->update(['image' => $imagePath]);
            } elseif ($request->has('image') && ($request->image === null || $request->image === 'null' || $request->image === '')) {
                // لو بعت null أو نص "null" أو فاضي → احذف
                if ($product->image && Storage::disk('public')->exists($product->image)) {
                    Storage::disk('public')->delete($product->image);
                }
                $product->update(['image' => null]);
            }



            if ($request->has('gallery_deleted') && is_array($request->gallery_deleted)) {
                $deletedIds = $request->input('gallery_deleted', []);
                $imagesToDelete = $product->images()->whereIn('id', $deletedIds)->get();

                foreach ($imagesToDelete as $img) {
                    if ($img->url && Storage::disk('public')->exists($img->url)) {
                        Storage::disk('public')->delete($img->url);
                    }
                    $img->delete();
                }
            }


            if ($request->hasFile('gallery')) {
                foreach ($request->file('gallery') as $galleryImage) {
                    if ($galleryImage->isValid()) {
                        $galleryPath = $galleryImage->store('products', 'public');
                        $product->images()->create([
                            'url' => $galleryPath,
                        ]);
                    }
                }
            }

            if ($request->has('tags')) {
                $product->tags()->sync($request->input('tags', []));
            }

            DB::commit();

            return response()->json([
                'message' => 'تم تعديل المنتج بنجاح',
                'product' => new ProductResource(
                    Product::with(['category', 'status', 'images', 'tags'])->findOrFail($product->id)
                ),
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'حدث خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }
    public function destroy($id)
    {
        try {
            $validator = Validator::make(['id' => $id], [
                'id' => 'required|integer|exists:products,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'message' => 'رقم المنتج غير صحيح أو غير موجود'
                ], 400);
            }

            $product = Product::findOrFail($id);

            DB::beginTransaction();

            foreach ($product->images as $image) {
                Storage::disk('public')->delete($image->url);
                $image->delete();
            }

            $product->tags()->detach();

            $product->delete();

            DB::commit();

            return response()->json([
                'message' => 'تم حذف المنتج بنجاح'
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }
}
