<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponse;
use App\Models\EcaNotification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    // ─────────────────────────────────
    // GET ALL NOTIFICATIONS
    // GET /api/notifications
    // ─────────────────────────────────
    public function getNotifications()
    {
        $user          = auth()->user();
        $notifications = EcaNotification::where(
            'user_id', $user->id
        )->latest()->take(50)->get();

        $data = $notifications->map(function ($n) {
            return [
                'id'         => (string) $n->id,
                'title'      => $n->title,
                'message'    => $n->message,
                'type'       => $n->type,
                'is_read'    => (bool) $n->is_read,
                'created_at' => $n->created_at
                    ->format('d M Y h:i A'),
                'time_ago'   => $n->created_at
                    ->diffForHumans(),
            ];
        });

        return ApiResponse::success(
            $data,
            'Notifications fetched successfully'
        );
    }

    // ─────────────────────────────────
    // MARK ONE AS READ
    // POST /api/notifications/read
    // ─────────────────────────────────
    public function markAsRead(Request $request)
    {
        $request->validate([
            'notification_id' => 'required|exists:notifications,id',
        ]);

        $notification = EcaNotification::where(
            'id', $request->notification_id
        )->where('user_id', auth()->id())->first();

        if (!$notification) {
            return ApiResponse::error(
                'Notification not found.', 404
            );
        }

        $notification->update(['is_read' => true]);

        return ApiResponse::success(
            null,
            'Notification marked as read.'
        );
    }

    // ─────────────────────────────────
    // MARK ALL AS READ
    // POST /api/notifications/read-all
    // ─────────────────────────────────
    public function markAllAsRead()
    {
        EcaNotification::where('user_id', auth()->id())
            ->where('is_read', false)
            ->update(['is_read' => true]);

        return ApiResponse::success(
            null,
            'All notifications marked as read.'
        );
    }

    // ─────────────────────────────────
    // UNREAD COUNT
    // GET /api/notifications/unread-count
    // ─────────────────────────────────
    public function unreadCount()
    {
        $count = EcaNotification::where(
            'user_id', auth()->id()
        )->where('is_read', false)->count();

        return ApiResponse::success(
            ['count' => $count],
            'Unread count fetched'
        );
    }
}