<?php

namespace App\Http\Controllers;

use App\Models\SmtpCredential;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;

class SmtpController extends Controller
{
    use ApiResponse;

    public function fetch_smtp_credential(Request $request)
    {
        $user = $request->user();

        $hasRead = $user->can('setting.smtp_credential.read');
        $hasOverride = $user->can('setting.smtp_credential.override');

        if (!$hasRead && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $smtpCredential = SmtpCredential::first();

        return $this->success('SMTP Credential fetched successfully', $smtpCredential);
    }

    public function update_smtp_credential(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'host' => ['required'],
            'port' => ['required'],
            'username' => ['required'],
            'password' => ['required'],
            'encryption' => ['required'],
            'email' => ['required'],
        ]);

        $smtp_credential = SmtpCredential::first();

        if($smtp_credential) {
            $smtp_credential->update([
                'host' => $request->host,
                'port' => $request->port,
                'username' => $request->username,
                'password' => $request->password,
                'encryption' => $request->encryption,
                'email' => $request->email,
                'updated_at' => now(),
            ]);
        } else {
            $smtp_credential = SmtpCredential::create([
                'host' => $request->host,
                'port' => $request->port,
                'username' => $request->username,
                'password' => $request->password,
                'encryption' => $request->encryption,
                'email' => $request->email,
                'created_by' => $user->id,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        activity('smtp_credential')
            ->causedBy($user)
            ->withProperties([
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("SMTP credential updated by {$user->name}");

        return $this->success('SMTP credential updated successfully', $smtp_credential);

    }
}
