<?php

namespace App\Services;

use App\Models\User;
use App\Models\ReminderLog;

class NotificationService
{
    protected $telegramService;

    public function __construct(TelegramService $telegramService)
    {
        $this->telegramService = $telegramService;
    }

    public function notifyAdmins($message, $type = 'info')
    {
        $admins = User::where('is_active', true)->get();

        foreach ($admins as $admin) {
            $settings = $admin->notificationSetting;

            // Email
            if (!$settings || $settings->email_enabled) {
                // Send email logic
            }

            // Telegram
            if ($admin->telegram_chat_id && (!$settings || $settings->telegram_enabled)) {
                $this->telegramService->sendReminder($admin->telegram_chat_id, $message);
            }
        }
    }

    public function logNotification($data)
    {
        return ReminderLog::create($data);
    }

    public function getFailedNotifications()
    {
        return ReminderLog::where('status', 'failed')
            ->where('created_at', '>=', now()->subDays(7))
            ->get();
    }

    public function retryFailedNotification(ReminderLog $log)
    {
        // Retry logic
        $log->update(['status' => 'pending']);

        // Re-send based on channel
        if ($log->channel === 'telegram') {
            $this->telegramService->sendReminder($log->recipient_id, $log->message);
        } else {
            // Re-send email logic
        }
    }
}
