<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\NotificationLog;
use App\Models\Rental;
use App\Services\NotificationService;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function __construct(protected NotificationService $notificationService) {}

    public function index(Request $request)
    {
        $logs = NotificationLog::with(['client', 'rental'])
            ->latest()
            ->paginate($request->get('per_page', 20));

        return response()->json($logs);
    }

    public function markRead(int $id)
    {
        // For in-app notifications (future implementation)
        return response()->json(['message' => 'Marked as read.']);
    }

    public function markAllRead()
    {
        return response()->json(['message' => 'All notifications marked as read.']);
    }

    /**
     * POST /api/notifications/send-reminder/{rental}
     */
    public function sendReminder(Request $request, Rental $rental)
    {
        $request->validate([
            'channels' => 'required|array',
            'channels.*' => 'in:email,sms,whatsapp',
        ]);

        $results = $this->notificationService->sendExpiryReminder($rental, $request->channels);

        return response()->json(['message' => 'Reminders sent.', 'results' => $results]);
    }

    /**
     * POST /api/notifications/send-bulk-reminders
     */
    public function sendBulkReminders(Request $request)
    {
        $request->validate([
            'days'     => 'required|integer|min:1',
            'channels' => 'required|array',
        ]);

        $rentals = Rental::expiring($request->days)->with('client')->get();
        $count   = 0;

        foreach ($rentals as $rental) {
            $this->notificationService->sendExpiryReminder($rental, $request->channels);
            $count++;
        }

        return response()->json(['message' => "Reminders sent to {$count} clients."]);
    }
}
