<?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);


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

            foreach($request->konferensi as $kon){
                $i = 0;
                $daftarKonferensi[] = $kon;
                $konferensi = Konferensi::select('nama')->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']
                ];

                $multipartData = [
                    'noid' => $id_registrasi,
                    'nama' => $request->nama,
                    'tagihan' => $kegiatan[$i]['harga']
                ];

                $this->generateVa($multipartData);

                $i++;
            }

            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 = [
            'headers' => [
                'Cookie' => 'XSRF-TOKEN=eyJpdiI6IkNNRXc1SmprYzMxL3FpQTE2NHI2UHc9PSIsInZhbHVlIjoibzlLcE80TzAyUjJYT3VLTUJSblNIRkpXdytOS0djM0U5azRrMFY1SzRwei92ZzB4VWV0bVMyeGdNSE1LZ2RxOUw4RC9QbGw4V1BWaU5id2dFTWVkbVJaZFNOOWFDRENMQVBzdlhycEE4TDRPZmRzK2xQa21ZWUJMOFg2TGJ2ZVUiLCJtYWMiOiIwMWM2MGM1ZTAyODlhOThjYWYwNDk1OWUwNTUyMWM0MWFmMTA5MDc2OGYzNzliYTViYTAxOTg0MTJjNDY1MmZkIiwidGFnIjoiIn0%3D; siva_session=eyJpdiI6Ii9qeEt5S0xDSS91QThndEp4eTRNS0E9PSIsInZhbHVlIjoiNGxJQ1oxTGtMOXFodTRPUFJRMFY0R1ZXNUNwV0FnSXhDUzJ5VkdNdmZJUWUvdlZCZzVjN3E3WE1MajZhZDlKeng5WWVhcTFOc1NXTmNPVWR1RkZpaEQ0MFdRbVJpTEp6YXo4bzUvNkJtTkpKRWRSRTRNaHEyZndLYlNtYXUxUzQiLCJtYWMiOiJkOGRjMjUwZjlhYTIzYmM4NmUwMzQ1MjhlZTNjMDdjZWI2MWNkYjQ3ZGRjZTI5MDlhZTZjODVkYjhhNDU0YTYzIiwidGFnIjoiIn0%3D'
            ],
            'multipart' => new MultipartStream([
                [
                'name' => 'credential',
                'contents' => '$2a$08$xSX/XuObiJ3GoJWhjDTyXepT64o1ze.A/.OVYB15uzKW3V7pxgZ6O'
                ],
                [
                'name' => 'noid',
                'contents' => $multipartData['noid']
                ],
                [
                'name' => 'nama',
                'contents' => $multipartData['nama']
                ],
                [
                'name' => 'tagihan',
                'contents' => $multipartData['tagihan']
                ],
                [
                'name' => 'flag',
                'contents' => 'F'
                ],
                [
                'name' => 'expired_date',
                'contents' => ''
                ]
            ])
        ];

        $response = $client->request('POST', 'http://neo-sidata.inf/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);
    }
}
