<?php

namespace App\Services;

use App\Enums\UserRole;
use App\Models\Listing;
use App\Models\Reservation;
use App\Models\SupportTicket;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class AdminNotificationService
{
    protected TelegramService $telegram;
    protected OneSignalService $oneSignal;

    public function __construct()
    {
        $this->telegram = new TelegramService();
        $this->oneSignal = new OneSignalService();
    }

    public function notifyNewUser(User $user): void
    {
        $roleLabel = $user->role instanceof UserRole ? $user->role->label() : 'Müşteri';

        $telegramText = "<b>👤 Yeni Üye Kaydı</b>\n\n"
            . "<b>Ad:</b> {$user->name}\n"
            . "<b>E-posta:</b> {$user->email}\n"
            . "<b>Telefon:</b> " . ($user->phone ?: '-') . "\n"
            . "<b>Rol:</b> {$roleLabel}\n"
            . "<b>Tarih:</b> " . now()->format('d.m.Y H:i');

        $this->send(
            $telegramText,
            "Yeni Üye: {$user->name}",
            "{$roleLabel} olarak kayıt oldu"
        );
    }

    public function notifyNewListing(Listing $listing): void
    {
        $listing->loadMissing(['owner', 'listingType']);

        $ownerName = $listing->owner?->name ?? '-';
        $typeName = $listing->listingType?->name ?? '-';

        $telegramText = "<b>🚢 Yeni İlan Eklendi</b>\n\n"
            . "<b>Başlık:</b> {$listing->title}\n"
            . "<b>Kaptan:</b> {$ownerName}\n"
            . "<b>Tür:</b> {$typeName}\n"
            . "<b>Fiyat:</b> ₺" . number_format($listing->price, 0, ',', '.') . "\n"
            . "<b>Durum:</b> {$listing->status->value}\n"
            . "<b>Tarih:</b> " . now()->format('d.m.Y H:i');

        $this->send(
            $telegramText,
            "Yeni İlan: {$listing->title}",
            "{$ownerName} tarafından eklendi"
        );
    }

    public function notifyNewReservation(Reservation $reservation): void
    {
        $reservation->loadMissing(['customer', 'listing']);

        $customerName = $reservation->customer?->name ?? '-';
        $listingTitle = $reservation->listing?->title ?? '-';

        $telegramText = "<b>📅 Yeni Rezervasyon</b>\n\n"
            . "<b>Kod:</b> {$reservation->reservation_code}\n"
            . "<b>İlan:</b> {$listingTitle}\n"
            . "<b>Müşteri:</b> {$customerName}\n"
            . "<b>Tarih:</b> " . date('d.m.Y', strtotime($reservation->reservation_date)) . "\n"
            . "<b>Kişi:</b> {$reservation->guest_count}\n"
            . "<b>Tutar:</b> ₺" . number_format($reservation->total_amount, 0, ',', '.') . "\n"
            . "<b>Oluşturulma:</b> " . now()->format('d.m.Y H:i');

        $this->send(
            $telegramText,
            "Yeni Rezervasyon: {$reservation->reservation_code}",
            "{$listingTitle} - ₺" . number_format($reservation->total_amount, 0, ',', '.')
        );
    }

    public function notifyNewTicket(SupportTicket $ticket): void
    {
        $ticket->loadMissing('user');

        $userName = $ticket->user?->name ?? '-';

        $telegramText = "<b>🎫 Yeni Destek Talebi</b>\n\n"
            . "<b>Konu:</b> {$ticket->subject}\n"
            . "<b>Kullanıcı:</b> {$userName}\n"
            . "<b>Öncelik:</b> " . ($ticket->priority ?? 'normal') . "\n"
            . "<b>Tarih:</b> " . now()->format('d.m.Y H:i');

        $this->send(
            $telegramText,
            "Yeni Destek Talebi: {$ticket->subject}",
            "{$userName} tarafından açıldı"
        );
    }

    public function notifyReservationStatusChange(Reservation $reservation, string $oldStatus): void
    {
        $reservation->loadMissing(['customer', 'listing']);

        $statusLabels = [
            'pending' => 'Beklemede',
            'approved' => 'Onaylandı',
            'rejected' => 'Reddedildi',
            'cancelled' => 'İptal Edildi',
            'completed' => 'Tamamlandı',
        ];

        $newStatus = $reservation->status->value ?? $reservation->status;
        $oldLabel = $statusLabels[$oldStatus] ?? $oldStatus;
        $newLabel = $statusLabels[$newStatus] ?? $newStatus;
        $customerName = $reservation->customer?->name ?? '-';

        $telegramText = "<b>🔄 Rezervasyon Durumu Değişti</b>\n\n"
            . "<b>Kod:</b> {$reservation->reservation_code}\n"
            . "<b>Müşteri:</b> {$customerName}\n"
            . "<b>Eski Durum:</b> {$oldLabel}\n"
            . "<b>Yeni Durum:</b> {$newLabel}\n"
            . "<b>Tarih:</b> " . now()->format('d.m.Y H:i');

        $this->send(
            $telegramText,
            "Rezervasyon: {$reservation->reservation_code}",
            "{$oldLabel} → {$newLabel}"
        );
    }

    protected function send(string $telegramText, string $pushTitle, string $pushMessage): void
    {
        try {
            $this->telegram->sendMessage($telegramText);
        } catch (\Throwable $e) {
            Log::error('Admin Telegram bildirimi gönderilemedi', ['error' => $e->getMessage()]);
        }

        try {
            $adminIds = User::where('role', UserRole::ADMIN)
                ->where(function ($q) {
                    $q->where('is_active', true)->orWhereNull('is_active');
                })
                ->pluck('id')
                ->toArray();

            if (!empty($adminIds)) {
                $this->oneSignal->sendToUsers($adminIds, $pushTitle, $pushMessage, [
                    'type' => 'admin_notification',
                ]);
            }
        } catch (\Throwable $e) {
            Log::error('Admin push bildirimi gönderilemedi', ['error' => $e->getMessage()]);
        }
    }
}
