<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    /**
     * Display notification dashboard
     */
    public function index()
    {
        $userId = Auth::id();

        $notifications = Notification::where('to_user_id', $userId)
            ->with('sender')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        $unreadCount = Notification::where('to_user_id', $userId)
            ->where('seen', false)
            ->count();

        return view('front_end.pages.notifications.index', compact(
            'notifications',
            'unreadCount'
        ));
    }

    /**
     * Mark a notification as seen
     */
    public function markAsSeen($id)
    {
        $notification = Notification::findOrFail($id);

        // Check if user owns this notification
        if ($notification->to_user_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'You do not have permission to perform this action.');
        }

        $notification->update(['seen' => true]);

        return redirect()->back()
            ->with('success', 'Notification marked as read.');
    }

    /**
     * Mark all notifications as seen
     */
    public function markAllAsSeen()
    {
        Notification::where('to_user_id', Auth::id())
            ->where('seen', false)
            ->update(['seen' => true]);

        return redirect()->back()
            ->with('success', 'All notifications marked as read.');
    }

    /**
     * Get unread notification count (for AJAX calls)
     */
    public function getUnreadCount()
    {
        $count = Notification::where('to_user_id', Auth::id())
            ->where('seen', false)
            ->count();

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

    /**
     * Send a notification to a user
     */
    public function send(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'to_user_id' => 'required|exists:users,id',
            'type' => 'required|string',
            'text' => 'required|string',
            'post_id' => 'nullable|exists:posts,id',
            'page_id' => 'nullable|exists:pages,id',
            'group_id' => 'nullable|exists:groups,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        // Don't allow sending notifications to yourself
        if (Auth::id() == $request->to_user_id) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot send a notification to yourself.'
            ], 422);
        }

        $notification = Notification::create([
            'from_user_id' => Auth::id(),
            'to_user_id' => $request->to_user_id,
            'type' => $request->type,
            'text' => $request->text,
            'post_id' => $request->post_id,
            'page_id' => $request->page_id,
            'group_id' => $request->group_id,
            'seen' => false,
            'is_reacted' => false,
        ]);

        // You could trigger a real-time notification here
        // broadcast(new NewNotification($notification))->toPrivate('user.' . $request->to_user_id);

        return response()->json([
            'success' => true,
            'notification' => $notification->load('sender')
        ]);
    }

    /**
     * Delete a notification
     */
    public function delete($id)
    {
        $notification = Notification::findOrFail($id);

        // Check if user owns this notification
        if ($notification->to_user_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'You do not have permission to perform this action.');
        }

        $notification->delete();

        return redirect()->back()
            ->with('success', 'Notification deleted successfully.');
    }

    /**
     * Handle notification reaction (for interactive notifications)
     */
    public function react($id)
    {
        $notification = Notification::findOrFail($id);

        // Check if user owns this notification
        if ($notification->to_user_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'You do not have permission to perform this action.');
        }

        $notification->update([
            'seen' => true,
            'is_reacted' => true
        ]);

        // Based on notification type, perform different actions
        switch ($notification->type) {
            case 'friend_request':
                // Accept friend request logic would go here
                return redirect()->route('social.friends.requests');

            case 'group_invite':
                // Handle group invite
                return redirect()->route('social.groups.show', $notification->group_id);

            case 'post_mention':
                // Go to the post where user was mentioned
                return redirect()->route('social.posts.show', $notification->post_id);

            default:
                return redirect()->back()
                    ->with('success', 'Notification acknowledged.');
        }
    }
    public function showUserNewNotifications(Request $request)
    {
        $user_id = $request->user()->id;
        $offset = (!empty($request->offset)) ? $request->offset : 0;
        $limit = (!empty($request->limit)) ? $request->limit : 10;
        $notifications = Notification::where(['to_user_id' => $user_id, 'seen' => 0])->where('from_user_id', '!=', $user_id)->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();

        return response()->json([
            'status' => 200,
            'message' => __('Api.notification_fetch_successfully'),
            'data' => NotificationResource::collection($notifications), // Use collection for multiple resources
        ], 200);
    }
    public function markAllAsRead(Request $request)
    {
        $user_id = $request->user()->id;
        Notification::where(['to_user_id' => $user_id,])->where('from_user_id', '!=', $user_id)->update(['seen' => 1]);
        return response()->json([
            'status' => 200,
            'message' => __('Api.notification_marked_as_read_successfully'),
        ], 200);
    }
    public function deleteAllNotification(Request $request)
    {
        $user_id = $request->user()->id;
        Notification::where(['to_user_id' => $user_id,])->where('from_user_id', '!=', $user_id)->update(['seen' => 1]);
        return response()->json([
            'status' => 200,
            'message' => __('Api.notification_marked_as_read_successfully'),
        ], 200);
    }

    /**
     * Get new notifications for web AJAX requests (uses session auth)
     */
    public function getNewNotifications(Request $request)
    {
        $user_id = Auth::id();
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);
        $onlyUnread = $request->get('unread_only', true); // Default to unread only
        
        $query = Notification::where('to_user_id', $user_id)
            ->where('from_user_id', '!=', $user_id)
            ->with('sender');
            
        if ($onlyUnread) {
            $query->where('seen', 0);
        }
        
        $notifications = $query->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        return response()->json([
            'status' => 200,
            'message' => 'Notifications fetched successfully',
            'data' => NotificationResource::collection($notifications),
        ], 200);
    }

    /**
     * Mark all notifications as read for web AJAX requests (uses session auth)
     */
    public function markAllAsReadAjax(Request $request)
    {
        $user_id = Auth::id();
        Notification::where('to_user_id', $user_id)
            ->where('from_user_id', '!=', $user_id)
            ->update(['seen' => 1]);
            
        return response()->json([
            'status' => 200,
            'message' => 'All notifications marked as read',
        ], 200);
    }
}
