<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API\Dashboard;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use App\Models\Point;
use Illuminate\Support\Str;

use App\Models\Notification;
use Illuminate\Http\Request;
use WebPConvert\WebPConvert;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\NotificationResource;

class NotificationController extends Controller
{
    public function send(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|integer|exists:users,id',
            'type' => 'required|string|max:255',
            'message' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'بيانات الإدخال غير صحيحة',
                'errors' => $validator->errors(),
            ], 400);
        }

        $user = User::find($request->user_id);
        if (!$user) {
            return response()->json([
                'message' => 'المستخدم غير موجود',
            ], 404);
        }

        $data = ['message' => $request->message];

        // Handle image upload and conversion to WebP if provided
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $inputPath = $image->getPathname();
            $outputPath = storage_path('app/public/notifications/' . Str::uuid() . '.webp');

            // Ensure the storage directory exists
            if (!file_exists(dirname($outputPath))) {
                mkdir(dirname($outputPath), 0755, true);
            }

            // Convert image to WebP
            try {
                WebPConvert::convert($inputPath, $outputPath, ['quality' => 80]);
                $data['image_path'] = 'notifications/' . basename($outputPath);
            } catch (\Exception $e) {
                return response()->json([
                    'message' => 'فشل تحويل الصورة إلى WebP',
                    'error' => $e->getMessage(),
                ], 500);
            }
        }

        // Create and save the notification
        $notification = new Notification([
            'id' => Str::uuid(),
            'type' => $request->type,
            'notifiable_type' => User::class,
            'notifiable_id' => $user->id,
            'data' => $data,
            'is_active' => true,
        ]);
        $notification->save();

        return response()->json([
            'message' => 'تم إرسال الإشعار بنجاح',
            'notification' => new NotificationResource($notification),
        ], 201);
    }

    /**
     * Get all notifications for a user, with optional filtering by date or status.
     *
     * @param Request $request
     * @param int $userId
     * @return \Illuminate\Http\JsonResponse
     */
    public function client(Request $request, $userId)
    {
        $user = User::find($userId);

        if (!$user) {
            return response()->json([
                'message' => 'المستخدم غير موجود',
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'date' => 'nullable|date_format:m/d/Y',
            'is_active' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'بيانات الإدخال غير صحيحة',
                'errors' => $validator->errors(),
            ], 400);
        }

        $query = $user->notifications()->with('notifiable');

        // Filter by date if provided
        if ($request->has('date')) {
            $formattedDate = Carbon::createFromFormat('m/d/Y', $request->date)->format('Y-m-d');
            $query->whereDate('created_at', $formattedDate);
        }

        // Filter by is_active if provided
        if ($request->has('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        $notifications = $query->latest()->paginate(10);

        return response()->json([
            'message' => 'تم استرجاع الإشعارات بنجاح',
            'notifications' => NotificationResource::collection($notifications),
            'pagination' => [
                'current_page' => $notifications->currentPage(),
                'total_pages' => $notifications->lastPage(),
                'total' => $notifications->total(),
                'per_page' => $notifications->perPage(),
            ],
        ], 200);
    }



    public function getLastMessage(Request $request)
    {
        // Validate input
        $validator = Validator::make($request->all(), [
            'date' => 'nullable|date_format:m/d/Y',
            'is_active' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'بيانات الإدخال غير صحيحة',
                'errors' => $validator->errors(),
            ], 400);
        }

        // Base query for users with notifications
        $query = User::select('users.*')
            ->selectRaw('(SELECT COUNT(*) FROM notifications AS n 
                      WHERE n.notifiable_id = users.id 
                      AND n.notifiable_type = ? 
                      AND n.read_at IS NULL) AS unread_count', [User::class])
            ->with([
                'notifications' => function ($query) use ($request) {
                    // Subquery to get the latest notification
                    $query->where('notifiable_type', User::class)
                        ->orderBy('created_at', 'desc')
                        ->limit(1);

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

                    if ($request->has('is_active')) {
                        $isActive = $request->is_active;
                        $query->whereNull('read_at', 'and', $isActive ? false : true);
                    }
                }
            ])
            ->has('notifications'); // Only include users with notifications

        // Paginate users
        $perPage = $request->input('per_page', 10);
        $users = $query->paginate($perPage);

        // Calculate order and point counts for each user
        $users->getCollection()->transform(function ($user) {
            $user->count_order = Order::where('user_id', $user->id)->count();
            $user->points_count = Point::where('model_id', $user->id)->count('point_x');
            $user->points_value = Point::where('model_id', $user->id)->count('point_y');
            return $user;
        });

        return response()->json([
            'message' => 'تم استرجاع بيانات المستخدمين وآخر إشعار لكل مستخدم بنجاح',
            'users' => UserResource::collection($users),
            'pagination' => [
                'current_page' => $users->currentPage(),
                'total_pages' => $users->lastPage(),
                'total' => $users->total(),
                'per_page' => $users->perPage(),
            ],
        ], 200);
    }
    public function destroy($id)
    {
        try {
            $note = Notification::findOrFail($id);
            $note->delete();

            return response()->json([
                'message' => 'تم حذف الإشعار بنجاح',
            ], 200); // كود 200 أنسب من 201 لحالة الحذف
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'message' => 'الإشعار غير موجود',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'حدث خطأ أثناء الحذف',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}