<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Facades\Log;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class MailerController extends Controller {
  public function __construct() {}

  public function compose ($val, $form=false) {
    mb_language('japanese');
    mb_internal_encoding('UTF-8');

    $mail = new PHPMailer(true);

    try {
      // $mail->SMTPDebug = 2;
      $mail->isSMTP();
      $mail->Host = config('mail.mailers.smtp.host');
      $mail->Port = config('mail.mailers.smtp.port');
      $mail->SMTPSecure = config('mail.mailers.smtp.encryption');
      $mail->SMTPAuth = true;
      $mail->From = config('mail.'.($form ? 'owner' : 'from').'.address');
      $mail->FromName = mb_encode_mimeheader(config('mail.mailers.smtp.'.($form ? 'fromname' : 'noreplyfrom')), 'JIS');
      $mail->Username = config('mail.mailers.smtp.'.($form ? 'username' : 'noreplyuser'));
      $mail->Password = config('mail.mailers.smtp.'.($form ? 'password' : 'noreplypass'));

      $mail->AddAddress(config('mail.'.($form ? 'owner' : 'from').'.address'));
      if ($form) $mail->addReplyTo(config('mail.owner.address'), config('mail.owner.name'));
      else $mail->addReplyTo($val['adr']);

      $mail->SMTPOptions = [
        'ssl' => [
          'verify_peer' => false,
          'verify_peer_name' => false,
          'allow_self_signed' => true
        ]
      ];

      if (isset($val['attach'])) {
        for ($i=0; $i < count($val['attach']); $i++) {
          $mail->AddAttachment($val['attach'][$i], $val['attachname'][$i]);
        }
      }

      if (isset($val['gpg'])) {
        $mail->AddStringAttachment($val['gpg'], $val['filename']);
        $mail->AddStringAttachment($val['bunsyo'], $val['adr'].'.gpg');
      }

      $mail->isHTML(false);

      $mail->Subject = mb_encode_mimeheader('【'.$val['catname'].'】'.$val['kenmei'], 'JIS');
      if ($form) $mail->Body = mb_convert_encoding($val['bunsyo'], 'UTF-8');
      else $mail->Body = mb_convert_encoding($val['bunsyo'], 'JIS');

      if (!$mail->send()) {
        Log::critical('Mailer error: ' . $mail->ErrorInfo);
        return false;
      }
    } catch (Exception $e) {
      Log::critical($e);
      return false;
    }

    return true;
  }
}
