<?php

namespace MoneyTransfer\Core\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use MoneyTransfer\Core\Models\Notification;
use Illuminate\Support\Facades\Validator;

class NotificationController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $perPage = $request->get('per_page', 15);
        $type = $request->get('type');
        $status = $request->get('status'); // read, unread

        $query = Notification::byUser($userId);

        if ($type) {
            $query->byType($type);
        }

        if ($status === 'unread') {
            $query->unread();
        } elseif ($status === 'read') {
            $query->where('is_read', true);
        }

        $notifications = $query->active()
                              ->orderBy('created_at', 'desc')
                              ->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $notifications,
            'message' => 'Notifications retrieved successfully'
        ]);
    }

    public function markAsRead(Request $request, $id): JsonResponse
    {
        $userId = auth()->id();
        
        $notification = Notification::byUser($userId)->find($id);

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

        $notification->markAsRead();

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

    public function markAllAsRead(Request $request): JsonResponse
    {
        $userId = auth()->id();
        
        $count = Notification::byUser($userId)
                           ->unread()
                           ->update([
                               'is_read' => true,
                               'read_at' => now(),
                           ]);

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

    public function destroy($id): JsonResponse
    {
        $userId = auth()->id();
        
        $notification = Notification::byUser($userId)->find($id);

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

        $notification->delete();

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

    public function getPreferences(Request $request): JsonResponse
    {
        $userId = auth()->id();
        
        // In a real application, you might have a separate UserPreferences model
        // For now, we'll return default preferences
        $preferences = [
            'email_notifications' => true,
            'push_notifications' => true,
            'sms_notifications' => false,
            'quiet_hours_enabled' => false,
            'quiet_hours_start' => '22:00',
            'quiet_hours_end' => '08:00',
            'notification_frequency' => 'immediate', // immediate, daily, weekly
            'language' => 'en',
            'types' => [
                'transfer' => true,
                'rate_alert' => true,
                'system' => true,
                'security' => true,
            ],
        ];

        return response()->json([
            'success' => true,
            'data' => $preferences,
            'message' => 'Notification preferences retrieved successfully'
        ]);
    }

    public function updatePreferences(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'email_notifications' => 'boolean',
            'push_notifications' => 'boolean',
            'sms_notifications' => 'boolean',
            'quiet_hours_enabled' => 'boolean',
            'quiet_hours_start' => 'date_format:H:i',
            'quiet_hours_end' => 'date_format:H:i',
            'notification_frequency' => 'in:immediate,daily,weekly',
            'language' => 'string|max:5',
            'types' => 'array',
            'types.*' => 'boolean',
        ]);

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

        $userId = auth()->id();
        
        // In a real application, you would save these to a UserPreferences model
        // For now, we'll just return success
        
        $preferences = $request->all();
        
        return response()->json([
            'success' => true,
            'data' => $preferences,
            'message' => 'Notification preferences updated successfully'
        ]);
    }

    public function getUnreadCount(Request $request): JsonResponse
    {
        $userId = auth()->id();
        
        $count = Notification::byUser($userId)
                           ->unread()
                           ->count();

        return response()->json([
            'success' => true,
            'data' => [
                'unread_count' => $count,
            ],
            'message' => 'Unread count retrieved successfully'
        ]);
    }

    public function getNotificationStats(Request $request): JsonResponse
    {
        $userId = auth()->id();
        
        $stats = [
            'total' => Notification::byUser($userId)->count(),
            'unread' => Notification::byUser($userId)->unread()->count(),
            'read' => Notification::byUser($userId)->where('is_read', true)->count(),
            'by_type' => Notification::byUser($userId)
                                  ->selectRaw('type, COUNT(*) as count')
                                  ->groupBy('type')
                                  ->get(),
            'by_priority' => Notification::byUser($userId)
                                       ->selectRaw('priority, COUNT(*) as count')
                                       ->groupBy('priority')
                                       ->get(),
        ];

        return response()->json([
            'success' => true,
            'data' => $stats,
            'message' => 'Notification statistics retrieved successfully'
        ]);
    }
} 