<?php

namespace App\Repositories;

use App\Models\SMTPMails;

class SMTPRepository
{

    public function create($data)
    {
        SMTPMails::create($this->prepareData($data)->all());
    }


    public function updateOrCreate($data)
    {
        $this->setAllDefaultSMTPFalse();
        SMTPMails::updateOrcreate(
            [
                'smtp' => $data['smtp_server'],
                'port' => $data['smtp_port'],
                'username' => $data['username'],
                'smtp' => $data['smtp_server'],
            ],
            [
                'Password' => encrypt($data["password"]),
                'encryption' => $data["encryption"],
                'auth_mode' => $data["auth_mode"],
                'is_default' => true
            ]
        );
    }

    public function setAllDefaultSMTPFalse()
    {
        SMTPMails::defaultSmtpMail()->update([
            'is_default' => false
        ]);
    }

    public function getNumberOfServers()
    {
        return SMTPMails::count();
    }


    private function prepareData($data)
    {
        return collect([
            'smtp' => $data['smtp_server'],
            'port' => $data['smtp_port'],
            'username' => $data['username'],
            'Password' => encrypt($data['password']),
            'encryption' => $data['encryption'],
            'auth_mode' => $data['auth_mode'],
            'is_default' => 1
        ]);
    }
}
