<?php

namespace Velis\Mail\Protocol\Smtp;

use Velis\App;
use Exception;

/**
 * Overriden connection handling
 */
trait ConnectionTrait
{
    /**
     * Connect to the server using the supplied transport and target
     *
     * An example $remote string may be 'tcp://mail.example.com:25' or 'ssh://hostname.com:2222'
     *
     * @param  string $remote Remote
     * @throws Exception\RuntimeException
     * @return bool
     */
    protected function _connect($remote)
    {
        $errorNum = 0;
        $errorStr = '';

        $context  = null;

        if (App::$config->notifications->ignoreCertIssues) {
            $context = stream_context_create([
                'ssl' => [
                    // set some SSL/TLS specific options
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true
                ]
            ]);

            $this->socket = stream_socket_client(
                $remote,
                $errorNum,
                $errorStr,
                self::TIMEOUT_CONNECTION,
                STREAM_CLIENT_CONNECT,
                $context
            );
        } else {
            $this->socket = stream_socket_client(
                $remote,
                $errorNum,
                $errorStr,
                self::TIMEOUT_CONNECTION
            );
        }

        if ($this->socket === false) {
            if ($errorNum == 0) {
                $errorStr = 'Could not open socket';
            }
            throw new Exception($errorStr);
        }

        if (($result = stream_set_timeout($this->socket, self::TIMEOUT_CONNECTION)) === false) {
            throw new Exception('Could not set stream timeout');
        }

        return $result;
    }


    /**
     * Disconnect from remote host and free resource
     */
    protected function _disconnect()
    {
        try {
            parent::_disconnect();
        } catch (Exception $e) {
            // We ignore any disconnect errors because the connection won't be used anymore
        }
    }
}
