<?php

namespace App\Http\Controllers;

use App\Http\Support\ValidationRule;
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;

class RegistrasiController extends Controller
{
    public function create(){
        $kegiatan = Kegiatan::get();
        $konferensi = Konferensi::get();
        $jumlahPendaftar = Registrasi::count();
        $nourut = sprintf("%05s", $jumlahPendaftar+1);
        $tgldaftar = Carbon::now()->format('d-m-Y');
        $komponen = explode('-', $tgldaftar);
        // $koderegistrasi = 'REG-'.$komponen[0].$komponen[1].$komponen[2].$nourut;
        $koderegistrasi = $komponen[0].$komponen[1].$nourut;

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

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

    public function store(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',
            'kode_registrasi' => 'required'
        ];

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

        DB::beginTransaction();

        try{
            $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($request->kode_registrasi)
            ];

            $tglRegistrasi = Carbon::now()->format('Y-m-d h:i:s');
            // $kegiatan = Kegiatan::find($request->kegiatan);
            // $konferensi = Konferensi::find($request->konferensi);
            $konaspi = Kegiatan::query()->where('id', '498633a9-082c-4a4a-9dbd-e20b678ec15e')->first();
            $registrasi = Registrasi::query()->create($registrasi);
            $id_registrasi = $registrasi->id;
            $kode_registrasi = $registrasi->kode_registrasi;
            //inisial harga
            // dd($konaspi);
            $totalHarga = (int) $konaspi->harga;

            foreach($request->konferensi as $kon){
                $i = 0;
                $daftarKonferensi[] = $kon;
                $konferensi = Konferensi::query()->where('id', $kon)->first();

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

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

                $totalHarga += (int) $konferensi->harga;
                $i++;
            }

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

            $generatedVa = $this->generateVa($multipartData);
            $arrResponse = json_decode($generatedVa, true);

            $registrasi->status_va = $arrResponse['BTNresponse'];
            $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');
            }


            foreach($kegiatanpeserta as $keg){
                KegiatanPeserta::query()->create($keg);
            }

            DB::commit();

            // return redirect()->back()
            //     ->with('success', 'Data saved successfully');
            // dd($kegiatanpeserta);
            return view('invoice', compact('registrasi', 'tglRegistrasi', 'kegiatanpeserta'))->with('success', 'Data saved successfully');

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

            return redirect()->back()
                ->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);
    }
}
