<?php

namespace App\Http\Controllers;

use App\Http\Support\ValidationRule;
use App\Models\Kegiatan;
use App\Models\Konferensi;
use App\Models\Registrasi;
use Carbon\Carbon;
use Exception;
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;

        $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',
            'konferensi' => 'required',
            'kegiatan' => 'required',
            '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),
                'id_konferensi' => $request->konferensi,
                'id_kegiatan' => $request->kegiatan,
                'kode_registrasi' => strip_tags($request->kode_registrasi)
            ];
            // dd($registrasi);
            Registrasi::query()->create($registrasi);
            DB::commit();

            return redirect()->back()
                ->with('success', 'Data saved successfully');

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

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

    }
}
