<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use App\Models\NotificationPreference;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class NotificationController extends Controller
{
    /**
     * Get user notifications with pagination.
     */
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $type = $request->get('type');
        $is_read = $request->get('is_read');
        
        $query = Notification::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc');
        
        if ($type) {
            $query->where('type', $type);
        }
        
        if ($is_read !== null) {
            $query->where('is_read', $is_read === 'true' || $is_read === '1');
        }
        
        $notifications = $query->paginate($perPage);
        
        return response()->json([
            'success' => true,
            'data' => $notifications,
        ]);
    }

    /**
     * Get unread notifications count.
     */
    public function unreadCount(Request $request)
    {
        $count = Notification::where('user_id', $request->user()->id)
            ->unread()
            ->count();
        
        return response()->json([
            'success' => true,
            'count' => $count,
        ]);
    }

    /**
     * Mark notification as read.
     */
    public function markAsRead(Request $request, $id)
    {
        $notification = Notification::where('user_id', $request->user()->id)
            ->findOrFail($id);
        
        $notification->markAsRead();
        
        return response()->json([
            'success' => true,
            'message' => 'Notification marked as read',
            'data' => $notification,
        ]);
    }

    /**
     * Mark all notifications as read.
     */
    public function markAllAsRead(Request $request)
    {
        $updated = Notification::where('user_id', $request->user()->id)
            ->unread()
            ->update([
                'is_read' => true,
                'read_at' => now(),
            ]);
        
        return response()->json([
            'success' => true,
            'message' => "Marked {$updated} notifications as read",
            'count' => $updated,
        ]);
    }

    /**
     * Delete a notification.
     */
    public function destroy(Request $request, $id)
    {
        $notification = Notification::where('user_id', $request->user()->id)
            ->findOrFail($id);
        
        $notification->delete();
        
        return response()->json([
            'success' => true,
            'message' => 'Notification deleted',
        ]);
    }

    /**
     * Delete all read notifications.
     */
    public function deleteAllRead(Request $request)
    {
        $deleted = Notification::where('user_id', $request->user()->id)
            ->read()
            ->delete();
        
        return response()->json([
            'success' => true,
            'message' => "Deleted {$deleted} notifications",
            'count' => $deleted,
        ]);
    }

    /**
     * Get user notification preferences.
     */
    public function getPreferences(Request $request)
    {
        $preferences = NotificationPreference::getOrCreate($request->user()->id);
        
        return response()->json([
            'success' => true,
            'data' => $preferences,
        ]);
    }

    /**
     * Update user notification preferences.
     */
    public function updatePreferences(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email_enabled' => 'nullable|boolean',
            'push_enabled' => 'nullable|boolean',
            'subscription_reminders' => 'nullable|boolean',
            'payment_alerts' => 'nullable|boolean',
            'system_updates' => 'nullable|boolean',
            'marketing' => 'nullable|boolean',
        ]);

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

        $preferences = NotificationPreference::getOrCreate($request->user()->id);
        $preferences->update($request->only([
            'email_enabled',
            'push_enabled',
            'subscription_reminders',
            'payment_alerts',
            'system_updates',
            'marketing',
        ]));
        
        return response()->json([
            'success' => true,
            'message' => 'Preferences updated successfully',
            'data' => $preferences,
        ]);
    }

    /**
     * Create a notification (Admin only).
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:users,id',
            'type' => 'required|string|max:50',
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'action_url' => 'nullable|string|max:500',
            'priority' => 'nullable|in:low,medium,high,urgent',
        ]);

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

        $notification = Notification::create($request->all());
        
        return response()->json([
            'success' => true,
            'message' => 'Notification created successfully',
            'data' => $notification,
        ], 201);
    }

    /**
     * Broadcast notification to all users (Admin only).
     */
    public function broadcast(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|string|max:50',
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'action_url' => 'nullable|string|max:500',
            'priority' => 'nullable|in:low,medium,high,urgent',
            'user_ids' => 'nullable|array',
            'user_ids.*' => 'exists:users,id',
        ]);

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

        $userIds = $request->has('user_ids') 
            ? $request->user_ids 
            : \App\Models\User::pluck('id')->toArray();

        $notificationsData = [];
        foreach ($userIds as $userId) {
            $notificationsData[] = [
                'user_id' => $userId,
                'type' => $request->type,
                'title' => $request->title,
                'message' => $request->message,
                'action_url' => $request->action_url,
                'priority' => $request->priority ?? 'medium',
                'is_read' => false,
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        Notification::insert($notificationsData);
        
        return response()->json([
            'success' => true,
            'message' => 'Notification sent to ' . count($userIds) . ' users',
            'count' => count($userIds),
        ], 201);
    }
}
