<?php

namespace App\Modules\Core\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Core\Models\SystemSetting;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SystemSettingController extends Controller
{
    /**
     * 顯示系統設定頁面
     */
    public function index()
    {
        $settings = SystemSetting::all()->groupBy('group');
        
        return Inertia::render('Admin/Setting/Index', [
            'settings' => $settings,
        ]);
    }

    /**
     * 更新系統設定
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'settings' => 'required|array',
            'settings.*.key' => 'required|string|exists:system_settings,key',
            'settings.*.value' => 'nullable',
        ]);

        foreach ($validated['settings'] as $item) {
            SystemSetting::where('key', $item['key'])->update([
                'value' => $item['value']
            ]);
        }

        // 清除記憶體快取，確保後續讀取拿到最新值
        SystemSetting::clearCache();

        return redirect()->back()->with('success', '系統設定已更新');
    }

    /**
     * 測試發送通知信
     */
    public function testNotification(Request $request)
    {
        $validated = $request->validate([
            'settings' => 'required|array',
            'settings.*.key' => 'required|string',
            'settings.*.value' => 'nullable|string',
        ]);

        $settings = collect($validated['settings'])->pluck('value', 'key');
        
        $senderEmail = $settings['notification.utility_fee_sender_email'] ?? null;
        $senderPassword = $settings['notification.utility_fee_sender_password'] ?? null;
        $recipientEmailsStr = $settings['notification.utility_fee_recipient_emails'] ?? null;

        if (empty($senderEmail) || empty($senderPassword) || empty($recipientEmailsStr)) {
            return back()->with('error', '請先填寫完整發信帳號、密碼及收件者信箱。');
        }

        // 動態覆寫應用程式名稱與 SMTP Config
        $tenantName = tenant('name') ?? config('app.name');
        config([
            'app.name' => $tenantName,
            'mail.mailers.smtp.username' => $senderEmail,
            'mail.mailers.smtp.password' => $senderPassword,
            'mail.from.address' => $senderEmail,
            'mail.from.name' => $tenantName . ' (系統通知)'
        ]);

        // 清理原先可能的 Mailer 實例，確保使用新的 Config
        \Illuminate\Support\Facades\Mail::purge();

        // 解析收件者
        $recipients = array_map('trim', explode(',', $recipientEmailsStr));
        $validRecipients = array_filter($recipients, fn($e) => filter_var($e, FILTER_VALIDATE_EMAIL));
        
        if (empty($validRecipients)) {
            return back()->with('error', '無效的收件者 Email 格式。');
        }

        try {
            \Illuminate\Support\Facades\Mail::to($validRecipients)->send(new \App\Mail\TestNotificationMail());
            return back()->with('success', '測試信件已成功發送，請檢查收件匣。');
        } catch (\Exception $e) {
            return back()->with('error', '測試發信失敗: ' . $e->getMessage());
        }
    }
}

