<?php
// app/Http/Controllers/NotificationController.php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();

            $query = Notification::where('notifiable_id', $user->user_id)
                                ->where('notifiable_type', 'App\Models\User')
                                ->orderBy('created_at', 'desc');

            // Filter by read status
            if ($request->has('read')) {
                if ($request->boolean('read')) {
                    $query->read();
                } else {
                    $query->unread();
                }
            }

            // Pagination
            $perPage = $request->get('per_page', 15);
            $notifications = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $notifications->items(),
                'unread_count' => $this->getUnreadCount($user->user_id),
                'pagination' => [
                    'current_page' => $notifications->currentPage(),
                    'per_page' => $notifications->perPage(),
                    'total' => $notifications->total(),
                    'last_page' => $notifications->lastPage(),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch notifications',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get unread notifications count
     */
    public function getUnreadCount($userId = null): JsonResponse
    {
        try {
            $userId = $userId ?? Auth::id();

            $count = Notification::where('notifiable_id', $userId)
                                ->where('notifiable_type', 'App\Models\User')
                                ->unread()
                                ->count();

            return response()->json([
                'success' => true,
                'data' => [
                    'unread_count' => $count
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get unread count',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Mark notification as read
     */
    public function markAsRead(string $id): JsonResponse
    {
        try {
            $user = Auth::user();

            $notification = Notification::where('id', $id)
                                      ->where('notifiable_id', $user->user_id)
                                      ->where('notifiable_type', 'App\Models\User')
                                      ->first();

            if (!$notification) {
                return response()->json([
                    'success' => false,
                    'message' => 'Notification not found'
                ], 404);
            }

            $notification->markAsRead();

            return response()->json([
                'success' => true,
                'message' => 'Notification marked as read',
                'data' => $notification
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to mark notification as read',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Mark notification as unread
     */
    public function markAsUnread(string $id): JsonResponse
    {
        try {
            $user = Auth::user();

            $notification = Notification::where('id', $id)
                                      ->where('notifiable_id', $user->user_id)
                                      ->where('notifiable_type', 'App\Models\User')
                                      ->first();

            if (!$notification) {
                return response()->json([
                    'success' => false,
                    'message' => 'Notification not found'
                ], 404);
            }

            $notification->markAsUnread();

            return response()->json([
                'success' => true,
                'message' => 'Notification marked as unread',
                'data' => $notification
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to mark notification as unread',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Mark all notifications as read
     */
    public function markAllAsRead(): JsonResponse
    {
        try {
            $user = Auth::user();

            $updated = Notification::where('notifiable_id', $user->user_id)
                                 ->where('notifiable_type', 'App\Models\User')
                                 ->unread()
                                 ->update(['read_at' => now()]);

            return response()->json([
                'success' => true,
                'message' => "{$updated} notifications marked as read",
                'data' => [
                    'marked_read_count' => $updated
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to mark all notifications as read',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Delete a notification
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $user = Auth::user();

            $notification = Notification::where('id', $id)
                                      ->where('notifiable_id', $user->user_id)
                                      ->where('notifiable_type', 'App\Models\User')
                                      ->first();

            if (!$notification) {
                return response()->json([
                    'success' => false,
                    'message' => 'Notification not found'
                ], 404);
            }

            $notification->delete();

            return response()->json([
                'success' => true,
                'message' => 'Notification deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete notification',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Clear all notifications
     */
    public function clearAll(): JsonResponse
    {
        try {
            $user = Auth::user();

            $deleted = Notification::where('notifiable_id', $user->user_id)
                                 ->where('notifiable_type', 'App\Models\User')
                                 ->delete();

            return response()->json([
                'success' => true,
                'message' => "{$deleted} notifications cleared",
                'data' => [
                    'deleted_count' => $deleted
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to clear notifications',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get notification statistics
     */
    public function getStats(): JsonResponse
    {
        try {
            $user = Auth::user();

            $total = Notification::where('notifiable_id', $user->user_id)
                               ->where('notifiable_type', 'App\Models\User')
                               ->count();

            $unread = Notification::where('notifiable_id', $user->user_id)
                                ->where('notifiable_type', 'App\Models\User')
                                ->unread()
                                ->count();

            $read = $total - $unread;

            return response()->json([
                'success' => true,
                'data' => [
                    'total_notifications' => $total,
                    'unread_count' => $unread,
                    'read_count' => $read,
                    'unread_percentage' => $total > 0 ? round(($unread / $total) * 100, 2) : 0
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get notification statistics',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    
}
