<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Services\Admin\SettingsService;
use App\Mail\TestEmail;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;

class SettingsController extends Controller
{
    protected $settingsService;

    public function __construct(SettingsService $settingsService)
    {
        $this->settingsService = $settingsService;
    }

    public function getSmtp(): JsonResponse
    {
        $settings = $this->settingsService->getGroup('smtp');
        
        if (isset($settings['smtp_password'])) {
            $settings['smtp_password'] = ''; 
        }
        
        return response()->json($settings);
    }

    public function updateSmtp(Request $request): JsonResponse
    {
        $data = $request->validate([
            'smtp_host'       => 'required|string',
            'smtp_port'       => 'required|numeric',
            'smtp_username'   => 'nullable|string',
            'smtp_password'   => 'nullable|string', 
            'smtp_encryption' => 'nullable|in:tls,ssl,null',
            'smtp_from_address' => 'required|email',
            'smtp_from_name'    => 'required|string',
        ]);

        $this->settingsService->updateGroup('smtp', $data);

        return response()->json(['message' => 'SMTP Settings updated successfully.']);
    }

    public function sendTestEmail(Request $request): JsonResponse
    {
        $request->validate(['email' => 'required|email']);

        try {
            Mail::to($request->email)->send(new TestEmail());

            return response()->json([
                'success' => true,
                'message' => 'Test email sent successfully!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Mail Error: ' . $e->getMessage()
            ], 500);
        }
    }
}