<?php

namespace App\Http\Controllers\Api;

use App\Enums\HttpCodesEnum;
use App\Enums\NotificationTypesEnum;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Http\Resources\ProductsResource;
use App\Http\Resources\ShopResource;
use App\Models\FirebaseNotification;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductsController extends Controller
{
    public function shopProducts($categoryId, $shopId)
    {
        $shop = User::query()->where('id', $shopId)->first();
        $products = Product::query()
            ->where('category_id', $categoryId)
            ->where('user_id', $shopId)
            ->where('is_active', 1)
            ->where('is_approved', 1)
            ->paginate(env('PerPage'), '*', 'products_page');

        return response()->json([
                'shop' => new ShopResource($shop),
                'products' => ProductsResource::collection($products),
            ] + PaginateAttributes($products, 'products'));
    }

    public function showProduct(Request $request)
    {
        $product = Product::query()
            ->where('id', $request->input('product_id'))
            ->where('is_active', 1)
            // ->where('is_approved', 1)
            ->withCount('favorite')
            ->firstOrFail();

        return response()->json([
            'shop' => new ShopResource($product->shop),
            'product' => new ProductsResource($product),
        ]);
    }

    public function store(StoreProductRequest $request)
    {
        $product_count = Product::query()
                ->where('user_id', $request->user()->id)
                ->where('is_active', 1)
                ->count() >= 40;

        if ($product_count) {
            return response()->json([
                'message' => trans('global.max_products_limit'),
            ], 403);
        }
        $product = Product::query()->create([
            'user_id' => $request->user()->id,
            'category_id' => $request->input('category_id'),
            'name_ar' => $request->input('name_ar'),
            'name_en' => $request->input('name_en'),
            'ar_description' => $request->input('ar_description'),
            'en_description' => $request->input('en_description'),
            'price' => $request->input('price'),
            // 'price_after_discount'  =>  $request->input('price_after_discount')
        ]);

        uploadProductImages($product, $request);

        return response()->json([
            'products_limit_reached' => $product_count,
            'products_limit_message' => $product_count ? trans('global.max_products_limit') : null,
            'product' => new ProductsResource($product),
        ]);
    }

    public function updateProduct(UpdateProductRequest $request)
    {
        $product_count = Product::query()
                ->where('user_id', $request->user()->id)
                ->where('is_active', 1)
                ->count() >= 40;

        if ($product_count) {
            return response()->json([
                'message' => trans('global.max_products_limit'),
            ], 403);
        }

        $product = Product::query()
            ->where('user_id', $request->user()->id)
            ->where('id', $request->input('product_id'))
            ->first();
        $product->update([
            'category_id' => $request->input('category_id'),
            'name_ar' => $request->input('name_ar'),
            'name_en' => $request->input('name_en'),
            'ar_description' => $request->input('ar_description'),
            'en_description' => $request->input('en_description'),
            'price' => $request->input('price'),
            // 'price_after_discount'  =>  $request->input('price_after_discount')
        ]);
        deleteProductImages($product, $request);
        uploadProductImages($product, $request);

        return response()->json([
            'products_limit_reached' => $product_count,
            'products_limit_message' => $product_count ? trans('global.max_products_limit') : null,
            'product' => new ProductsResource($product),
        ]);
    }

    public function myProducts()
    {
        $product_count = Product::query()
                ->where('user_id', request()->user()->id)
                ->where('is_active', 1)
                ->count() >= 40;

        $products = Product::query()
            ->where('user_id', \request()->user()->id)
            ->paginate(env('PerPage'), '*', 'products_page');

        return response()->json([
                'products_limit_reached' => $product_count,
                'products_limit_message' => $product_count ? trans('global.max_products_limit') : null,
                'products' => ProductsResource::collection($products),
            ] + PaginateAttributes($products, 'products'));
    }

    public function toggleProductStatus(Request $request)
    {
        $product_count = Product::query()
                ->where('user_id', $request->user()->id)
                ->where('is_active', 1)
                ->count() >= 40;

        $product = Product::query()
            ->where('user_id', \request()->user()->id)
            ->where('id', \request()->input('product_id'))
            ->first();
        if ($product) {
            if (!$product->is_active) {
                if ($product_count) {
                    return response()->json([
                        'products_limit_reached' => $product_count,
                        'products_limit_message' => $product_count ? trans('global.max_products_limit') : null,
                    ], 403);
                }
                $title_en = trans('global.product_notification_title', [], 'en');
                $body_en = trans('global.product_notification_body', [
                    'product_name' => $product->id,
                ], 'en');
                FirebaseNotification::query()->create([
                    'user_id' => $product->user_id,
                    'title' => $title_en,
                    'body' => $body_en,
                    'lang'      =>  'en',
                    'type' => NotificationTypesEnum::Product
                ]);
                $title_ar = trans('global.product_notification_title', [], 'ar');
                $body_ar = trans('global.product_notification_body', [
                    'product_name' => $product->id,
                ], 'ar');
                FirebaseNotification::query()->create([
                    'user_id' => $product->user_id,
                    'title' => $title_ar,
                    'body' => $body_ar,
                    'lang'      =>  'ar',
                    'type' => NotificationTypesEnum::Product
                ]);

                $title=$title_en."\n".$title_ar;
                $body =$body_en ."\n".$body_ar;
                fcm()
                    ->toTopic("user-$product->user_id")
                    ->priority('normal')
                    ->timeToLive(0)
                    ->notification([
                        'title' => $title,
                        'body' =>$body,
                    ])->data([
                        'title' =>$title,
                        'body' =>$body,
                    ])
                    ->send();
            }

            $product->update(['is_active' => !$product->is_active]);

            $product_count = Product::query()
                    ->where('user_id', $request->user()->id)
                    ->where('is_active', 1)
                    ->count() >= 40;

            return response()->json([
                'products_limit_reached' => $product_count,
                'products_limit_message' => $product_count ? trans('global.max_products_limit') : null,
                'message' => trans('global.product_status_changed_successfully')
            ]);
        }
        return response()->json([
            'message' => trans('global.product_not_exists')],
            HttpCodesEnum::ValidationError);
    }
}
