<?php

namespace App\Http\Controllers\Api\V1\Student;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Notification;

class NotificationController extends BaseController
{
    /**
     * Get list of notifications for the authenticated user.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();
            
            $query = Notification::where('user_id', $user->id)
                ->with('sender')
                ->orderBy('created_at', 'desc');
            
            // Filter by read status
            if ($request->has('is_read')) {
                $query->where('is_read', $request->is_read === 'true' || $request->is_read === true);
            }
            
            // Filter by type
            if ($request->has('type') && $request->type) {
                $query->where('type', $request->type);
            }
            
            $notifications = $query->paginate($request->get('per_page', 20));
            
            $data = $notifications->map(function($notification) {
                return [
                    'id' => $notification->id,
                    'title' => $notification->title,
                    'message' => $notification->message,
                    'type' => $notification->type,
                    'priority' => $notification->priority,
                    'is_read' => $notification->is_read,
                    'read_at' => $notification->read_at,
                    'sender' => $notification->sender ? [
                        'id' => $notification->sender->id,
                        'name' => $notification->sender->name,
                        'email' => $notification->sender->email,
                    ] : null,
                    'metadata' => $notification->metadata,
                    'created_at' => $notification->created_at,
                    'updated_at' => $notification->updated_at,
                ];
            });
            
            return $this->paginated($data, $notifications);
        } catch (\Exception $e) {
            Log::error('Student Notifications API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching notifications.', null, 500);
        }
    }
    
    /**
     * Get unread notifications count.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function unreadCount()
    {
        try {
            $user = Auth::user();
            $count = Notification::where('user_id', $user->id)
                ->where('is_read', false)
                ->count();
            
            return $this->success(['count' => $count]);
        } catch (\Exception $e) {
            Log::error('Student Notifications Count API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching unread count.', null, 500);
        }
    }
    
    /**
     * Get recent notifications.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recent(Request $request)
    {
        try {
            $user = Auth::user();
            $limit = $request->get('limit', 5);
            
            $notifications = Notification::where('user_id', $user->id)
                ->with('sender')
                ->orderBy('created_at', 'desc')
                ->limit($limit)
                ->get()
                ->map(function($notification) {
                    return [
                        'id' => $notification->id,
                        'title' => $notification->title,
                        'message' => \Str::limit($notification->message, 100),
                        'type' => $notification->type,
                        'priority' => $notification->priority,
                        'is_read' => $notification->is_read,
                        'created_at' => $notification->created_at,
                    ];
                });
            
            return $this->success($notifications);
        } catch (\Exception $e) {
            Log::error('Student Recent Notifications API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching recent notifications.', null, 500);
        }
    }
    
    /**
     * Mark notification as read.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAsRead($id)
    {
        try {
            $user = Auth::user();
            $notification = Notification::where('id', $id)
                ->where('user_id', $user->id)
                ->firstOrFail();
            
            $notification->markAsRead();
            
            return $this->success(null, 'Notification marked as read.');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Notification not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Mark Notification Read API error: ' . $e->getMessage());
            return $this->error('An error occurred while marking notification as read.', null, 500);
        }
    }
    
    /**
     * Mark all notifications as read.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAllAsRead()
    {
        try {
            $user = Auth::user();
            $updated = Notification::where('user_id', $user->id)
                ->where('is_read', false)
                ->update([
                    'is_read' => true,
                    'read_at' => now(),
                ]);
            
            return $this->success(['updated_count' => $updated], 'All notifications marked as read.');
        } catch (\Exception $e) {
            Log::error('Student Mark All Notifications Read API error: ' . $e->getMessage());
            return $this->error('An error occurred while marking all notifications as read.', null, 500);
        }
    }
    
    /**
     * Get notification details.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $user = Auth::user();
            $notification = Notification::where('id', $id)
                ->where('user_id', $user->id)
                ->with('sender')
                ->firstOrFail();
            
            // Mark as read when viewing
            $notification->markAsRead();
            
            return $this->success([
                'id' => $notification->id,
                'title' => $notification->title,
                'message' => $notification->message,
                'type' => $notification->type,
                'priority' => $notification->priority,
                'is_read' => $notification->is_read,
                'read_at' => $notification->read_at,
                'sender' => $notification->sender ? [
                    'id' => $notification->sender->id,
                    'name' => $notification->sender->name,
                    'email' => $notification->sender->email,
                ] : null,
                'metadata' => $notification->metadata,
                'created_at' => $notification->created_at,
                'updated_at' => $notification->updated_at,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Notification not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Notification Show API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching notification details.', null, 500);
        }
    }
    
    /**
     * Delete a notification.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        try {
            $user = Auth::user();
            $notification = Notification::where('id', $id)
                ->where('user_id', $user->id)
                ->firstOrFail();
            
            $notification->delete();
            
            return $this->success(null, 'Notification deleted successfully.');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Notification not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Notification Delete API error: ' . $e->getMessage());
            return $this->error('An error occurred while deleting notification.', null, 500);
        }
    }
}

