<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mailer\DynamicMailConfig;
use App\Models\Setting;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Swift_Mailer;

class AlasanTolakController extends Controller
{
    public function index()
    {
        $alasan = Setting::query()->where('name', 'alasan')->first();
        $data['template'] = Setting::query()->where('name', 'template_email_tolak')->first();
        $data['template2'] = Setting::query()->where('name', 'template_email_tolak_bawah')->first();
        $data['alasan'] = !is_null($alasan) ? json_decode($alasan->value, true) : [];

        return view('content.backend.settings.alasan.index', $data);
    }

    public function store(Request $request)
    {
        try{
            Setting::query()->updateOrCreate([
                'name' => 'alasan'
            ], [
                'value' => json_encode($request->alasan)
            ]);

            Setting::query()->updateOrCreate([
                'name' => 'template_email_tolak'
            ], [
                'value' => $request->template
            ]);

            Setting::query()->updateOrCreate([
                'name' => 'template_email_tolak_bawah'
            ], [
                'value' => $request->template2
            ]);

            if(!is_null($request->preview)){

                if(!is_null($request->alasan)){
                    $catatan = '<ul>';
                    foreach($request->alasan as $key => $item){
                        $catatan .= '<li>'.$item.'</li>';
                    }
                    $catatan .= '</ul>';
                    $catatan .= '<p>(Alasan Lain bila ada)</p>';
                }
                $data['template'] = $request->template;
                $data['template2'] = $request->template2;
                $data['alasan'] = $catatan;
                $data['nama'] = '(Nama Pendaftar)';

                // $this->sendEmail($data);

                return view('email.email_tolak', $data);
            }
        }
        catch(Exception $ex){
            dd($ex);
        }

        return redirect()->back();
    }

    public function sendEmail($data)
    {

        $transport = DynamicMailConfig::getConfig();
        $swift_mailer = new Swift_Mailer($transport);

        Mail::setSwiftMailer($swift_mailer);
        Mail::send('email.email_tolak', $data, function ($message){
                $message->from('recruitment@unesa.ac.id', 'Universitas Negeri Surabaya');
                $message->sender('recruitment@unesa.ac.id', 'Universitas Negeri Surabaya');
                $message->subject('Informasi Hasil Seleksi Administrasi Pegawai UNESA');
                $message->to('iskandarjava@gmail.com', 'iskandarjava@gmail.com');
            }
        );
    }
}
