<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationLog;
use App\Models\Setting;
use Illuminate\Http\Request;

class NotificationSettingsController extends Controller
{
    /**
     * Show the notification settings panel.
     */
    public function index()
    {
        $toggles = [
            ['key' => 'notify_welcome',          'label' => 'Welcome Email',            'description' => 'Sent after a new member verifies their email address.'],
            ['key' => 'notify_points_credited',   'label' => 'Points Credited',           'description' => 'Sent when points are added to a member\'s account.'],
            ['key' => 'notify_points_debited',    'label' => 'Points Debited',            'description' => 'Sent when points are deducted from a member\'s account.'],
            ['key' => 'notify_tier_upgraded',      'label' => 'Tier Upgraded',             'description' => 'Sent when a member is promoted to a higher tier.'],
            ['key' => 'notify_tier_downgraded',    'label' => 'Tier Downgraded',           'description' => 'Sent when a member is moved to a lower tier.'],
            ['key' => 'notify_expiry_reminder',    'label' => 'Points Expiry Reminder',    'description' => 'Sent X days before a member\'s points anniversary.'],
        ];

        foreach ($toggles as &$toggle) {
            $toggle['enabled'] = Setting::get($toggle['key'], true);
        }

        $reminderDays = Setting::get('points_expiry_reminder_days', 30);

        $recentLogs = NotificationLog::with('user')
            ->latest('sent_at')
            ->take(25)
            ->get();

        return view('admin.settings.notifications', compact('toggles', 'reminderDays', 'recentLogs'));
    }

    /**
     * Update notification settings.
     */
    public function update(Request $request)
    {
        $keys = [
            'notify_welcome',
            'notify_points_credited',
            'notify_points_debited',
            'notify_tier_upgraded',
            'notify_tier_downgraded',
            'notify_expiry_reminder',
        ];

        foreach ($keys as $key) {
            Setting::updateOrCreate(
                ['key' => $key],
                [
                    'value' => $request->boolean($key) ? 'true' : 'false',
                    'type'  => 'boolean',
                    'label' => str_replace('notify_', '', $key),
                ]
            );
        }

        // Reminder days
        $days = $request->validate(['points_expiry_reminder_days' => 'required|integer|min:1|max:90']);
        Setting::set('points_expiry_reminder_days', $days['points_expiry_reminder_days']);

        return redirect()->route('admin.settings.notifications')
            ->with('success', 'Notification settings updated.');
    }
}
