<?php

namespace App\Livewire\Profile;

use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفضيلات الإشعارات')]
class NotificationPreferences extends Component
{
    public array $preferences = [];

    private array $eventTypes = [
        'payment.received' => 'إيصال الدفع',
        'enrollment_expiring' => 'انتهاء التسجيل',
        'installment_due' => 'موعد القسط',
        'invoice_overdue_reminder' => 'تذكير فاتورة متأخرة',
        'daily_summary' => 'ملخص يومي',
        'birthday_greeting' => 'تهنئة عيد ميلاد',
        'low_stock_alert' => 'تنبيه نقص مخزون',
        'bulk_message' => 'رسائل جماعية',
    ];

    public function mount(): void
    {
        $userId = auth()->id();

        $existing = DB::table('notification_preferences')
            ->where('user_id', $userId)
            ->pluck('channels', 'event_type')
            ->toArray();

        foreach ($this->eventTypes as $type => $label) {
            $channels = isset($existing[$type]) ? json_decode($existing[$type], true) : ['email' => true, 'sms' => true, 'in_app' => true];
            $this->preferences[$type] = $channels;
        }
    }

    public function save(): void
    {
        $userId = auth()->id();

        foreach ($this->preferences as $eventType => $channels) {
            DB::table('notification_preferences')
                ->updateOrInsert(
                    ['user_id' => $userId, 'event_type' => $eventType],
                    ['channels' => json_encode($channels), 'updated_at' => now()]
                );
        }

        session()->flash('success', __('تم حفظ تفضيلات الإشعارات'));
    }

    public function render()
    {
        return view('livewire.profile.notification-preferences', [
            'eventTypes' => $this->eventTypes,
        ]);
    }
}
