<?php

use Webuccino\Install\Core\App;
use Webuccino\Install\Core\SMTP;
use Webuccino\Install\Core\Database;
use Webuccino\Install\Core\Session;
use Webuccino\Install\Http\Forms\SMTPForm;

$db = App::resolve(Database::class);

$form = SMTPForm::validate($attributes = [
  'smtp' => $_POST['smtp_host'],
  'port' => $_POST['smtp_port'],
  'username' => $_POST['smtp_username'],
  'Password' => $_POST['smtp_password'],
  'encryption' => $_POST['smtp_encryption'],
  'auth_mode' => $_POST['smtp_auth_mode'],
]);

if ($form) {
  echo json_encode([
    "msg" => "SMTP connection parameters cannot be left blank."
  ]);
  die;
}

$check_connection = (new SMTP(
  $attributes['smtp'],
  $attributes['port'],
  $attributes['username'],
  $attributes['Password'],
  $attributes['encryption'],
  $attributes['auth_mode']
))->checkConnection();


if ($check_connection["success"]) {

  $attributes['Password'] = encrypt_native($_POST['smtp_password']);

  $check_connection_exist = $db->checkExist('mail', [

    ['smtp', $attributes['smtp']],
    ['port', $attributes['port']],
    ['username', $attributes['username']],
    ['encryption', $attributes['encryption']],
    ['auth_mode', $attributes['auth_mode']],
    ['is_default', 1]

  ]);

  if (!$check_connection_exist && $db->countAllRecords('mail') > 0) {

    echo json_encode([
      "msg" => "confirm"
    ]);

    die;
  } else if (!$check_connection_exist && $db->countAllRecords('mail') == 0) {

    $db->create('mail', array_merge($attributes, ['is_default' => 1]));
  }

  Session::put('smtp-connection-success', true);

  echo json_encode([
    "msg" => $check_connection["msg"]
  ]);
} else {

  echo json_encode([
    "msg" => $check_connection["msg"]
  ]);
}
