<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Payment;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    /**
     * Get notifications for the current user
     */
    public function index(Request $request): JsonResponse
    {
        $notifications = [];

        // Get recent invoices
        $recentInvoices = Invoice::where('status', '!=', 'paid')
            ->where('due_date', '<=', Carbon::now()->addDays(7))
            ->orderBy('due_date', 'asc')
            ->limit(5)
            ->get();

        foreach ($recentInvoices as $invoice) {
            $daysUntilDue = Carbon::now()->diffInDays($invoice->due_date, false);

            if ($daysUntilDue < 0) {
                $notifications[] = [
                    'id' => 'invoice-'.$invoice->id,
                    'title' => 'Overdue Invoice',
                    'message' => "Invoice {$invoice->invoice_number} is overdue by ".abs($daysUntilDue).' days',
                    'icon' => 'warning',
                    'time' => $invoice->due_date->diffForHumans(),
                    'url' => route('admin.invoices.show', $invoice),
                ];
            } elseif ($daysUntilDue <= 3) {
                $notifications[] = [
                    'id' => 'invoice-'.$invoice->id,
                    'title' => 'Invoice Due Soon',
                    'message' => "Invoice {$invoice->invoice_number} is due in {$daysUntilDue} days",
                    'icon' => 'schedule',
                    'time' => $invoice->due_date->diffForHumans(),
                    'url' => route('admin.invoices.show', $invoice),
                ];
            }
        }

        // Get recent payments
        $recentPayments = Payment::where('status', 'completed')
            ->orderBy('created_at', 'desc')
            ->limit(3)
            ->get();

        foreach ($recentPayments as $payment) {
            $notifications[] = [
                'id' => 'payment-'.$payment->id,
                'title' => 'Payment Received',
                'message' => 'Payment of '.number_format($payment->amount, 2)." received for Invoice {$payment->invoice->invoice_number}",
                'icon' => 'payments',
                'time' => $payment->created_at->diffForHumans(),
                'url' => route('admin.payments.show', $payment),
            ];
        }

        return response()->json([
            'notifications' => $notifications,
            'unread_count' => count($notifications),
        ]);
    }
}
