<?php

namespace App\Http\Controllers;

use App\Http\Support\ValidationRule;
use App\Jobs\SendMail;
use App\Models\Kegiatan;
use App\Models\KegiatanPeserta;
use App\Models\Konferensi;
use App\Models\Registrasi;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\MultipartStream;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use RealRashid\SweetAlert\Facades\Alert;

class RegistrasiController extends Controller
{
    public function create(){
        $kegiatan = Kegiatan::orderBy('id')->get();
        $konferensi = Konferensi::get();
        $date = Date('Y-m-d');
        // $lastKode = Registrasi::query()->whereDate('created_at', $date)->max('kode_registrasi');
        // $nourut = sprintf("%05s", ((int) substr($lastKode, -5))+1);
        // $tgldaftar = Carbon::now()->format('d-m-Y');
        // $komponen = explode('-', $tgldaftar);
        // $kode_registrasi = $komponen[0].$komponen[1].$nourut;

        $data = [
            'kegiatan' => $kegiatan,
            'konferensi' => $konferensi,
            // 'kode_registrasi' => $kode_registrasi
        ];

        return view('form_registrasi', $data);
    }

    public function preview(Request $request){
        $rules = [
            'nama' => 'required|string',
            'email' => 'required|email:rfc,dns',
            'telepon' => 'required|numeric',
            'instansi' => 'required|string',
            'jabatan' => 'required|string',
            'alamat' => 'required|string',
            'kodepos' => 'required|string',
            'kota' => 'required|string',
        ];

        $request->validate($rules, ValidationRule::getErrorMessage($rules));

        DB::beginTransaction();

        try{
            $date = Date('Y-m-d');
            $lastKode = Registrasi::query()->whereDate('created_at', $date)->max('kode_registrasi');
            $nourut = sprintf("%05s", ((int) substr($lastKode, -5))+1);
            $tgldaftar = Carbon::now()->format('d-m-Y');
            $komponen = explode('-', $tgldaftar);
            $kode_registrasi = $komponen[0].$komponen[1].$nourut;

            $registrasi = [
                'nama' => strip_tags($request->nama),
                'email' => strip_tags($request->email),
                'telepon' => strip_tags($request->telepon),
                'instansi' => strip_tags($request->instansi),
                'jabatan' => strip_tags($request->jabatan),
                'alamat' => strip_tags($request->alamat),
                'kode_pos' => strip_tags($request->kodepos),
                'kota' => strip_tags($request->kota),
                'kode_registrasi' => strip_tags($kode_registrasi)
            ];

            $tglRegistrasi = Carbon::now()->format('Y-m-d h:i:s');
            $konaspi = Kegiatan::query()->where('id', '498633a9-082c-4a4a-9dbd-e20b678ec15e')->first();

            //inisial harga
            $totalHarga = (int) $konaspi->harga;

            if($request->konferensi[0] != null || $request->kegiatan0[0] != "498633a9-082c-4a4a-9dbd-e20b678ec15e"){
                $i = 0;
                foreach($request->konferensi as $kon){
                    $daftarKonferensi[] = $kon;
                    $konferensi = Konferensi::query()->where('id', $kon)->first();

                    foreach($request->input('kegiatan'.$i) as $keg){
                        $daftarKegiatan[] = $keg;
                        $kegiatan[] = Kegiatan::select('id', 'nama', 'harga')->where('id', $keg)->first();
                    }

                    $kegiatanpeserta[] = [
                        'id_kegiatan' => $kegiatan[$i]['id'],
                        'id_konferensi' => $daftarKonferensi[$i],
                        'nama_kegiatan' => $kegiatan[$i]['nama'],
                        'nama_konferensi' => $konferensi->nama,
                        'harga' => $kegiatan[$i]['harga']
                    ];

                    $hargaKonferensi[] = [
                        'idkon' => $konferensi->id,
                        'namakon' => $konferensi->nama,
                        'hargakon' => $konferensi->harga,
                        'namakeg' => $kegiatan[$i]['nama']
                    ];

                    $totalHarga += (int) $konferensi->harga;
                    $i++;
                }
            }
            else{
                $hargaKonferensi = null;
                $kegiatanpeserta[] = [
                    'id_kegiatan' => $request->kegiatan0[0],
                    'id_konferensi' => null,
                ];
            }

            $data = [
                'registrasi' => $registrasi,
                'kegiatanpeserta' => $kegiatanpeserta,
                'tglRegistrasi' => $tglRegistrasi,
                'konaspi' => $konaspi,
                'hargaKonferensi' => $hargaKonferensi,
                'totalHarga' => $totalHarga
            ];

            return view('preview', $data)->with('success', 'Data saved successfully');

        }
        catch(Exception $e){
            Log::error($e);
            DB::rollBack();

            return redirect()->back()
                ->with('error', 'Data failed to save');
        }
    }

    public function store(Request $request) {
        DB::beginTransaction();

        try{
            $registrasi = json_decode($request->registrasi, true);
            $kegiatanpeserta = json_decode($request->kegiatanpeserta, true);
            $konaspi = json_decode($request->konaspi, true);
            $hargaKonferensi = json_decode($request->hargaKonferensi, true);
            $tglRegistrasi = $request->tglRegistrasi;
            // $totalHargas = $request->totalHarga;

            $registrasi = Registrasi::query()->create($registrasi);
            $id_registrasi = $registrasi->id;
            $jumlahKeg = count($kegiatanpeserta);

            //inisial harga
            $totalHarga = (int) $konaspi['harga'];

            foreach($kegiatanpeserta as $keg){
                $kegpeserta = [
                    'id_registrasi' => $id_registrasi,
                    'id_kegiatan' => $keg['id_kegiatan'],
                    'id_konferensi' => $keg['id_konferensi'],
                ];
                KegiatanPeserta::query()->create($kegpeserta);

                if($keg['id_kegiatan'] != '498633a9-082c-4a4a-9dbd-e20b678ec15e'){
                    $konferensi = Konferensi::query()->where('id', $keg['id_konferensi'])->first();
                    $totalHarga += (int) $konferensi->harga;
                }
            }

            $multipartData = [
                'noid' => $registrasi['kode_registrasi'],
                'nama' => $registrasi['nama'],
                'tagihan' => $totalHarga
            ];

            $generatedVa = $this->generateVa($multipartData);
            $arrResponse = json_decode($generatedVa, true);
            $registrasi->status_va = $arrResponse['BTNresponse'];
            $registrasi->tagihan = $totalHarga;

            $registrasi->save();

            if($arrResponse['BTNresponse'] != 'Request has been processed successfully'){
                DB::rollBack();
                Log::error('---');
                Log::error($multipartData);
                Log::error($arrResponse['BTNresponse']);
                Log::error('---');

                return redirect()->back()
                ->with('error', 'Data failed to save');
            }

            DB::commit();

            // return redirect()->route('user.create')->with('success', 'Data saved successfully');

            $data = [
                'registrasi' => $registrasi,
                'kegiatanpeserta' => $kegiatanpeserta,
                'tglRegistrasi' => $tglRegistrasi,
                'konaspi' => $konaspi,
                'hargaKonferensi' => $hargaKonferensi,
                'totalHarga' => $totalHarga
            ];

            return view('invoice', $data)->with('success', 'Data saved successfully');

        }
        catch(Exception $e){
            Log::error($e);
            DB::rollBack();

            return redirect()->route('user.create')
                ->with('error', 'Data failed to save');
        }
    }

    private function generateVa($multipartData)
    {
        $client = new Client();
        $options = [
            'form_params' => [
                'credential' => '$2a$08$xSX/XuObiJ3GoJWhjDTyXepT64o1ze.A/.OVYB15uzKW3V7pxgZ6O',
                'noid' => $multipartData['noid'],
                'nama' => $multipartData['nama'],
                'tagihan' => $multipartData['tagihan'],
                'flag' => 'F',
                'expired_date' => '',
                'deskripsi' => 'pembayaran konaspi'
            ]
        ];

        $response = $client->request('POST', 'https://neosidata.unesa.ac.id/btn_v2/create', $options);

        return $response->getBody()->getContents();
    }

    public function addFormKegiatan(Request $request)
    {
        $data['kegiatan'] = Kegiatan::get();
        $data['konferensi'] = Konferensi::get();
        $data['i'] = $request->i;

        return view('form_kegiatan', $data);
    }

    public function updatePembayaran(Request $request, $va)
    {
        if($request->bearerToken() != 'zGKEX7CDNLOvVtetz6lqFZzhZv11Gr9Y2MKVIQmqusAyD5STPPEt7ZC1gl8P'){
            return response([
                'status' => 403,
                'message' => 'unauthorized access'
            ], 200);
        }

        $registrasi = Registrasi::query()
        ->where('kode_registrasi', $va)
        ->update([
            'tanggal_bayar' => Carbon::now()
        ]);

        return response([
            'status' => 200,
            'message' => 'success'
        ], 200);
    }

    public function testEmail(Request $request)
    {
        $data['registrasi'] = Registrasi::query()->where('kode_registrasi', '070300013')->first();

        SendMail::dispatch($data, 'email.invoice', $data['registrasi']->email, 'registrasi', 'email_regis_sent_at');
    }
}

