<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Inertia\Inertia;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Artisan;

class SmtpSettingsController extends Controller
{
    public function index()
    {
        $settings = Setting::whereIn('key', [
            'smtp_host', 'smtp_port', 'smtp_username', 'smtp_password',
            'smtp_encryption', 'smtp_from_address', 'smtp_from_name'
        ])->pluck('value', 'key')->toArray();

        return Inertia::render('cp/Settings/Smtp', [
            'smtpSettings' => $settings
        ]);
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'smtp_host' => 'required|string',
            'smtp_port' => 'required|string',
            'smtp_username' => 'nullable|string',
            'smtp_password' => 'nullable|string',
            'smtp_encryption' => 'nullable|string',
            'smtp_from_address' => 'required|email',
            'smtp_from_name' => 'required|string',
        ]);

        $envMap = [
            'smtp_host' => 'MAIL_HOST',
            'smtp_port' => 'MAIL_PORT',
            'smtp_username' => 'MAIL_USERNAME',
            'smtp_password' => 'MAIL_PASSWORD',
            'smtp_encryption' => 'MAIL_ENCRYPTION',
            'smtp_from_address' => 'MAIL_FROM_ADDRESS',
            'smtp_from_name' => 'MAIL_FROM_NAME',
        ];

        // FORCE MAILER TO SMTP WHEN SAVED VIA ADMIN PANEL
        $this->updateEnv('MAIL_MAILER', 'smtp');

        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
            
            if (isset($envMap[$key])) {
                $envValue = preg_match('/\s/', $value) ? '"' . $value . '"' : $value;
                $this->updateEnv($envMap[$key], $envValue);
            }
        }

        Artisan::call('config:clear');

        return back()->with('success', 'SMTP Configuration saved successfully. System is now using SMTP.');
    }

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

        config([
            'mail.default' => 'smtp',
            'mail.mailers.smtp.host' => Setting::where('key', 'smtp_host')->value('value'),
            'mail.mailers.smtp.port' => Setting::where('key', 'smtp_port')->value('value'),
            'mail.mailers.smtp.username' => Setting::where('key', 'smtp_username')->value('value'),
            'mail.mailers.smtp.password' => Setting::where('key', 'smtp_password')->value('value'),
            'mail.mailers.smtp.encryption' => Setting::where('key', 'smtp_encryption')->value('value'),
            'mail.from.address' => Setting::where('key', 'smtp_from_address')->value('value'),
            'mail.from.name' => Setting::where('key', 'smtp_from_name')->value('value'),
        ]);

        try {
            Mail::raw('Hello! If you are reading this, your SMTP settings are configured correctly.', function ($message) use ($request) {
                $message->to($request->email)
                        ->subject('SMTP Test Connection Success - ' . config('app.name'));
            });

            return response()->json(['message' => 'Test email sent successfully! Check your inbox.']);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

    private function updateEnv($key, $value)
    {
        $path = base_path('.env');
        if (file_exists($path)) {
            $oldContent = file_get_contents($path);
            if (preg_match('/^' . $key . '=/m', $oldContent)) {
                $newContent = preg_replace('/^' . $key . '=.*/m', $key . '=' . $value, $oldContent);
            } else {
                $newContent = $oldContent . PHP_EOL . $key . '=' . $value;
            }
            file_put_contents($path, $newContent);
        }
    }
}