<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Config;
use App\Mail\TestMail;
use Illuminate\Support\Facades\File;

class TestMailController extends Controller
{
    public function test()
    {
        // 1. Capture current config
        $config = [
            'default' => Config::get('mail.default'),
            'mailers' => [
                'smtp' => [
                    'host' => Config::get('mail.mailers.smtp.host'),
                    'port' => Config::get('mail.mailers.smtp.port'),
                    'username' => Config::get('mail.mailers.smtp.username'),
                    // Mask password
                    'password' => Config::get('mail.mailers.smtp.password') ? '***' : null,
                    'encryption' => Config::get('mail.mailers.smtp.encryption'),
                ],
                'from' => Config::get('mail.from'),
            ]
        ];

        // 2. Attempt to send email
        $status = 'Success';
        $error = null;
        $toEmail = 'test@example.com'; // Default test email

        try {
            Mail::to($toEmail)->send(new TestMail());
        } catch (\Exception $e) {
            $status = 'Failed';
            $error = $e->getMessage();
        }

        // 3. Log to file
        $logEntry = "=================================================\n";
        $logEntry .= "MAIL TEST EXECUTION [" . now()->toDateTimeString() . "]\n";
        $logEntry .= "=================================================\n";
        $logEntry .= "Status: " . $status . "\n";
        if ($error) {
            $logEntry .= "Error: " . $error . "\n";
        }
        $logEntry .= "Recipient: " . $toEmail . "\n";
        $logEntry .= "Configuration Used:\n";
        $logEntry .= json_encode($config, JSON_PRETTY_PRINT) . "\n";
        $logEntry .= "-------------------------------------------------\n\n";

        $filePath = base_path('mail_test_log.txt');
        File::append($filePath, $logEntry);

        return response()->json([
            'message' => 'Mail test executed.',
            'status' => $status,
            'log_file' => $filePath,
            'error' => $error
        ]);
    }
}
