<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    /**
     * API: Get notifications for authenticated user
     */
    public function apiIndex(Request $request)
    {
        $user = $request->user();
        
        $notifications = Notification::where('user_id', $user->id)
                                   ->orWhere('user_id', null) // Global notifications
                                   ->orderBy('is_persistent', 'desc')
                                   ->orderBy('created_at', 'desc')
                                   ->paginate(20);
        
        return response()->json($notifications);
    }
    
    /**
     * API: Create notification (Admin only)
     */
    public function apiStore(Request $request)
    {
        $user = $request->user();
        
        // Only admin can create notifications
        if (!$user->hasRole('Admin')) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'type' => 'required|in:info,warning,success,error,announcement',
            'is_persistent' => 'boolean',
            'user_id' => 'nullable|exists:users,id',
            'department_id' => 'nullable|exists:departments,id',
            'expires_at' => 'nullable|date|after:now',
        ]);
        
        // If department_id is provided, create notifications for all users in that department
        if (isset($validated['department_id'])) {
            $users = \App\Models\User::whereHas('staffProfile', function($q) use ($validated) {
                $q->where('department_id', $validated['department_id']);
            })->get();
            
            $notifications = [];
            foreach ($users as $departmentUser) {
                $notificationData = $validated;
                $notificationData['user_id'] = $departmentUser->id;
                unset($notificationData['department_id']);
                $notifications[] = Notification::create($notificationData);
            }
            
            return response()->json([
                'message' => 'Notifications created for department successfully.',
                'count' => count($notifications),
                'notifications' => $notifications
            ], 201);
        }
        
        // Create single notification
        $notification = Notification::create($validated);
        
        return response()->json([
            'message' => 'Notification created successfully.',
            'notification' => $notification
        ], 201);
    }
    
    /**
     * API: Mark notification as read (only dismissible notifications)
     */
    public function apiMarkAsRead(Request $request, $id)
    {
        $user = $request->user();
        $notification = Notification::findOrFail($id);
        
        // Check if user can access this notification
        if ($notification->user_id && $notification->user_id !== $user->id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        // Task persistent notifications cannot be dismissed by staff
        if ($notification->isTaskPersistent() && !$user->hasRole('Admin')) {
            return response()->json([
                'error' => 'Task persistent notifications cannot be dismissed',
                'message' => 'This notification requires admin action to remove'
            ], 422);
        }
        
        // Non-dismissible notifications cannot be marked as read by staff
        if (!$notification->isDismissible() && !$user->hasRole('Admin')) {
            return response()->json([
                'error' => 'This notification cannot be dismissed',
                'message' => 'Contact your administrator if this notification is no longer relevant'
            ], 422);
        }
        
        $notification->update(['read_at' => now()]);
        
        return response()->json([
            'message' => 'Notification marked as read.',
            'notification' => $notification
        ]);
    }
    
    /**
     * API: Delete notification (Admin only)
     */
    public function apiDestroy(Request $request, $id)
    {
        $user = $request->user();
        
        // Only admin can delete notifications
        if (!$user->hasRole('Admin')) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $notification = Notification::findOrFail($id);
        $notification->delete();
        
        return response()->json(['message' => 'Notification deleted successfully.']);
    }
    
    /**
     * API: Get unread notification count
     */
    public function apiUnreadCount(Request $request)
    {
        $user = $request->user();
        
        $count = Notification::where(function($query) use ($user) {
                                $query->where('user_id', $user->id)
                                      ->orWhere('user_id', null);
                            })
                            ->whereNull('read_at')
                            ->where(function($query) {
                                $query->whereNull('expires_at')
                                      ->orWhere('expires_at', '>', now());
                            })
                            ->count();
        
        return response()->json(['unread_count' => $count]);
    }
    
    /**
     * API: Get task persistent notifications
     */
    public function apiTaskPersistent(Request $request)
    {
        $user = $request->user();
        
        $notifications = Notification::where(function($query) use ($user) {
                                        $query->where('user_id', $user->id)
                                              ->orWhere('user_id', null);
                                    })
                                    ->taskPersistent()
                                    ->active()
                                    ->with('task')
                                    ->orderBy('priority_level', 'desc')
                                    ->orderBy('created_at', 'desc')
                                    ->get();
        
        return response()->json($notifications);
    }

    /**
     * API: Create task persistent notification (Admin only)
     */
    public function apiCreateTaskPersistent(Request $request)
    {
        $user = $request->user();
        
        // Only admin can create task persistent notifications
        if (!$user->hasRole('Admin')) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $validated = $request->validate([
            'task_id' => 'required|exists:tasks,id',
            'user_id' => 'nullable|exists:users,id',
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'priority_level' => 'required|in:low,medium,high,urgent',
            'expires_at' => 'nullable|date|after:now',
            'metadata' => 'nullable|array',
        ]);
        
        $notificationData = array_merge($validated, [
            'type' => 'info',
            'notification_category' => 'task_persistent',
            'is_persistent' => true,
            'is_dismissible' => false,
        ]);
        
        $notification = Notification::create($notificationData);
        
        return response()->json([
            'message' => 'Task persistent notification created successfully.',
            'notification' => $notification->load('task')
        ], 201);
    }

    /**
     * API: Remove task persistent notification (Admin only)
     */
    public function apiRemoveTaskPersistent(Request $request, $id)
    {
        $user = $request->user();
        
        // Only admin can remove task persistent notifications
        if (!$user->hasRole('Admin')) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $notification = Notification::where('id', $id)
                                  ->taskPersistent()
                                  ->firstOrFail();
        
        $notification->delete();
        
        return response()->json([
            'message' => 'Task persistent notification removed successfully.'
        ]);
    }

    /**
     * API: Get persistent notifications (cannot be dismissed by staff)
     */
    public function apiPersistent(Request $request)
    {
        $user = $request->user();
        
        $notifications = Notification::where(function($query) use ($user) {
                                        $query->where('user_id', $user->id)
                                              ->orWhere('user_id', null);
                                    })
                                    ->where('is_persistent', true)
                                    ->where(function($query) {
                                        $query->whereNull('expires_at')
                                              ->orWhere('expires_at', '>', now());
                                    })
                                    ->orderBy('created_at', 'desc')
                                    ->get();
        
        return response()->json($notifications);
    }
    
    /**
     * API: Broadcast notification to all staff (Admin only)
     */
    public function apiBroadcast(Request $request)
    {
        $user = $request->user();
        
        // Only admin can broadcast notifications
        if (!$user->hasRole('Admin')) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'type' => 'required|in:info,warning,success,error,announcement',
            'is_persistent' => 'boolean',
            'expires_at' => 'nullable|date|after:now',
        ]);
        
        // Create notification for all staff users
        $staffUsers = \App\Models\User::role('Staff')->get();
        $notifications = [];
        
        foreach ($staffUsers as $staff) {
            $notificationData = $validated;
            $notificationData['user_id'] = $staff->id;
            $notifications[] = Notification::create($notificationData);
        }
        
        return response()->json([
            'message' => 'Notification broadcasted to all staff successfully.',
            'count' => count($notifications),
            'notifications' => $notifications
        ], 201);
    }
}