<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\SendMail;
use App\Mailer\DynamicMailConfig;
use App\Models\Biodata;
use App\Models\MsFormasi;
use App\Models\MsKabupaten;
use App\Models\MsKecamatan;
use App\Models\MsKelurahan;
use App\Models\MsPeriode;
use App\Models\MsProvinsi;
use App\Models\Pendaftaran;
use App\Models\Setting;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Swift_Mailer;

class PendaftaranController extends Controller
{
    const CATATAN = [
        'Foto tidak sesuai',
        'Biodata tidak valid',
        'Pendidikan tidak  sesuai kualifikasi',
    ];

    public function filterPendaftar($filter)
    {
        $pendaftar = Pendaftaran::query()->whereNotNull('konfirmasi_at');

        if(isset($filter['formasi_id'])){
            $pendaftar = $pendaftar->where('formasi_id', $filter['formasi_id']);
        }

        if(isset($filter['periode_id'])){
            $pendaftar = $pendaftar->where('periode_id', $filter['periode_id']);
        }

        if(isset($filter['valid'])){
            if($filter['valid'] == '1'){
                $pendaftar = $pendaftar->whereNotNull('validasi_at');
            }
            if($filter['valid'] == '-1'){
                $pendaftar = $pendaftar->whereNotNull('tolak_at');
            }
            if($filter['valid'] == '0'){
                $pendaftar = $pendaftar->whereNull('tolak_at')->whereNull('validasi_at');
            }
        }

        return $pendaftar;
    }

    public function index(Request $request)
    {
        $data['filter'] = $request->filter;

        if(!is_null($data['filter'])){
            foreach($data['filter'] as $key => $filter){
                $data['filter'][$key] = !is_null($filter) ? decrypt($filter) : null;
            }
        }

        $periode = null;

        if(!isset($data['filter']['periode_id'])){
            $periode = MsPeriode::getCurrentPeriode();
            $periode = !is_null($periode) ? $periode : MsPeriode::query()->orderBy('closed_at', 'desc')->first();

            $data['filter']['periode_id'] = !is_null($periode) ? $periode->id : null;
        }
        else{
            $periode = MsPeriode::with('formasi')->find($data['filter']['periode_id']);
        }

        $data['formasi'] = !is_null($periode) ? $periode->formasi : collect([]);

        $data['periode'] = MsPeriode::query()
        ->orderBy('opened_at', 'desc')
        ->get();

        $data['pendaftar'] = $this->filterPendaftar($data['filter'])
        ->with('biodata.pendidikan.jenjangPendidikan', 'formasi', 'prodi.jenjangPendidikan', 'periode', 'validator')
        ->get();

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

    public function show(Request $request, $id)
    {
        // $catatan = PendaftaranController::CATATAN;
        $alasan = Setting::query()->where('name', 'alasan')->first();
        $catatan = !is_null($alasan) ? json_decode($alasan->value, true) : [];
        $Pendaftaran = Pendaftaran::with('biodata.biodataPendidikan.prodi.jenjangPendidikan')->find(decrypt($id));
        $Biodata = $Pendaftaran->biodata;
        $MsProvinsi  = MsProvinsi::orderby('name','asc')->pluck("name","code");
        $msKelurahanDomisili = [];
        $msKecamatanDomisili = [];
        $msKabupatenDomisili = [];
        $msProvinsiDomisili = [];

        $msKelurahanKtp = [];
        $msKecamatanKtp = [];
        $msKabupatenKtp = [];
        $msProvinsiKtp = [];

        if(!is_null($Biodata)){
            $msKelurahanDomisili = MsKelurahan::where('district_code', $Biodata->kelurahanDomisili->district_code)->get();
            $msKecamatanDomisili = MsKecamatan::where('city_code', $Biodata->kelurahanDomisili->kecamatan->city_code)->get();
            $msKabupatenDomisili = MsKabupaten::where('province_code', $Biodata->kelurahanDomisili->kecamatan->kabupaten->province_code)->get();
            $msProvinsiDomisili  = MsProvinsi::where('code', $Biodata->kelurahanDomisili->kecamatan->kabupaten->provinsi->code)->get();

            $msKelurahanKtp = MsKelurahan::where('district_code', $Biodata->kelurahanDomisili->district_code)->get();
            $msKecamatanKtp = MsKecamatan::where('city_code', $Biodata->kelurahanDomisili->kecamatan->city_code)->get();
            $msKabupatenKtp = MsKabupaten::where('province_code', $Biodata->kelurahanDomisili->kecamatan->kabupaten->province_code)->get();
            $msProvinsiKtp = MsProvinsi::where('code', $Biodata->kelurahanDomisili->kecamatan->kabupaten->provinsi->code)->get();
        }

        $data =
        [
            'Biodata' => $Biodata,
            'Pendaftaran' => $Pendaftaran,
            'MsProvinsi' => $MsProvinsi,
            'MsKelurahanDomisili' => $msKelurahanDomisili,
            'MsKecamatanDomisili' => $msKecamatanDomisili,
            'MsKabupatenDomisili' => $msKabupatenDomisili,
            'MsProvinsiDomisili' => $msProvinsiDomisili,
            'MsKelurahanKtp' => $msKelurahanKtp,
            'MsKecamatanKtp' => $msKecamatanKtp,
            'MsKabupatenKtp' => $msKabupatenKtp,
            'MsProvinsiKtp' => $msProvinsiKtp,
            'DokumenTambahan' => $Biodata->dokumenTambahan,
            'Catatan' => $catatan
        ];

        return view('content.backend.pendaftaran.biodata',$data);
    }

    public function adminCancelValidate(Request $request)
    {
        try{
            $pendaftar = Pendaftaran::query()->find(decrypt($request->id));
            $pendaftar->catatan = null;
            $pendaftar->validasi_at = null;
            $pendaftar->tolak_at = null;
            $pendaftar->save();

            return response('success', 200);
        }
        catch(Exception $ex){
            return response('error', 500);
        }

    }

    public function adminValidate(Request $request)
    {
        $pendaftar = Pendaftaran::query()->find(decrypt($request->id));
        $data = [];

        if($request->validasi == '1'){
            $pendaftar->validasi_at = Carbon::now();
        }
        elseif($request->validasi == '0'){
            $pendaftar->tolak_at = Carbon::now();

            $catatan = '';

            if(!is_null($request->catatan)){
                $catatan = '<ul>';
                foreach($request->catatan as $key => $item){
                    $catatan .= '<li>'.$item.'</li>';
                }
                $catatan .= '</ul>';
            }
            $catatan .= '<p>'.$request->catatan_lain.'</p>';
            $pendaftar->catatan = $catatan;
            $data['alasan'] = $catatan;
        }

        $pendaftar->validator_id = Auth::user()->id;

        $pendaftar->save();

        $data['pendaftar'] = $pendaftar;

        // if($request->validasi == '0'){

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

        return response('success', 200);
    }

    public function sendEmailInfo($id)
    {
        $pendaftar = Pendaftaran::query()
        ->with('biodata')
        ->whereNotNull('konfirmasi_at')
        ->whereNull('sent_at')
        ->where('periode_id', decrypt($id))
        // ->limit(3)
        ->get();

        $data['template'] = Setting::getSetting('template_email_info');

        // $data['template'] = Setting::query()->where('name', 'template_email_tolak')->first()->value;
        // $data['template2'] = Setting::query()->where('name', 'template_email_tolak_bawah')->first()->value;
        // dd($pendaftar);
        foreach($pendaftar as $item){
            $data['pendaftar'] = $item;
            $data['nama'] = $data['pendaftar']->biodata->nama;
            $user = $data['pendaftar']->user;

            SendMail::dispatch($data, 'email.email_info', $user->email);
        }

        return redirect()->back()->with('success', 'Email diproses!');

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

        // Mail::setSwiftMailer($swift_mailer);
        // Mail::send('email.email_tolak', $data, function ($message) use ($user){
        //         $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($user->email, $user->email);
        //     }
        // );
    }

    public function sendEmailTerima($id)
    {
        $pendaftar = Pendaftaran::query()
        ->with('biodata')
        ->whereNull('sent_at')
        ->whereNotNull('validasi_at')
        ->where('periode_id', decrypt($id))
        // ->limit(3)
        ->get();

        $data['template'] = Setting::getSetting('template_email_terima');

        // $data['template'] = Setting::query()->where('name', 'template_email_tolak')->first()->value;
        // $data['template2'] = Setting::query()->where('name', 'template_email_tolak_bawah')->first()->value;
        // dd($pendaftar);
        foreach($pendaftar as $item){
            $data['pendaftar'] = $item;
            $data['nama'] = $data['pendaftar']->biodata->nama;
            $user = $data['pendaftar']->user;

            SendMail::dispatch($data, 'email.email_terima', $user->email);
        }

        return redirect()->back()->with('success', 'Email diproses!');

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

        // Mail::setSwiftMailer($swift_mailer);
        // Mail::send('email.email_tolak', $data, function ($message) use ($user){
        //         $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($user->email, $user->email);
        //     }
        // );
    }

    public function sendEmailTolak($id)
    {
        $pendaftar = Pendaftaran::query()
        ->with('biodata')
        ->whereNull('sent_at')
        ->whereNotNull('tolak_at')
        ->where('periode_id', decrypt($id))
        // ->limit(3)
        ->get();

        $data['template'] = Setting::getSetting('template_email_tolak');
        $data['template2'] = Setting::getSetting('template_email_tolak_bawah');

        // $data['template'] = Setting::query()->where('name', 'template_email_tolak')->first()->value;
        // $data['template2'] = Setting::query()->where('name', 'template_email_tolak_bawah')->first()->value;
        // dd($pendaftar);
        foreach($pendaftar as $item){
            $data['pendaftar'] = $item;
            $data['nama'] = $data['pendaftar']->biodata->nama;
            $data['alasan'] = $item->catatan;
            $user = $data['pendaftar']->user;

            SendMail::dispatch($data, 'email.email_tolak', $user->email);
        }

        return redirect()->back()->with('success', 'Email diproses!');
        // $transport = DynamicMailConfig::getConfig();
        // $swift_mailer = new Swift_Mailer($transport);

        // Mail::setSwiftMailer($swift_mailer);
        // Mail::send('email.email_tolak', $data, function ($message) use ($user){
        //         $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($user->email, $user->email);
        //     }
        // );
    }
}
