<?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)
            ->get()
            ->keyBy('event_type');

        foreach ($this->eventTypes as $type => $label) {
            if (isset($existing[$type])) {
                $row = $existing[$type];
                $this->preferences[$type] = [
                    'email' => (bool) $row->channel_email,
                    'sms' => (bool) $row->channel_sms,
                    'in_app' => (bool) $row->channel_in_app,
                ];
            } else {
                $this->preferences[$type] = ['email' => true, 'sms' => true, 'in_app' => true];
            }
        }
    }

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

        foreach ($this->preferences as $eventType => $channels) {
            DB::table('notification_preferences')
                ->updateOrInsert(
                    ['user_id' => $userId, 'event_type' => $eventType],
                    [
                        'channel_email' => $channels['email'] ?? true,
                        'channel_sms' => $channels['sms'] ?? true,
                        'channel_in_app' => true,
                        'updated_at' => now(),
                    ]
                );
        }

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

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