<?php

namespace App\Http\Controllers\authentications;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Siswa;
use App\Notifications\UserNotification;
use Illuminate\Auth\Events\Registered;
use Exception;

class RegisterBasic extends Controller
{
  public function index()
  {
    return view('content.authentications.auth-register-basic');
  }

  public function biodata()
  {
    return view("content.authentications.auth-register-biodata-basic");
  }

  public function register(Request $request)
  {
    if ($request->password != $request->confirm_password) {
      return redirect()->route("auth-register-basic")->withErrors([
        "message" => "Password not match!"
      ]);
    }

    try {
      DB::transaction(function () use ($request) {
        $newUser = User::create([
          "email" => $request->email,
          "username" => $request->username,
          "password" => bcrypt($request->password),
          "role" => "Siswa",
        ]);

        Siswa::create([
          "nama" => $request->nama,
          "user_id" => $newUser->getKey(),
        ]);

        event(new Registered($newUser));
      });

      $admin = User::where("role", "=", "Admin")->get();
      Notification::send($admin, new UserNotification("1 Siswa Mendaftar", $request->nama . " mendaftarkan diri sebagai siswa baru!", "/tables/student"));

      $credentials = [
        "username" => $request->username,
        "password" => $request->password
      ];
      if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
      }
      return redirect()->route("auth-login-basic")->with(['status' => "Email verifikasi telah dikirimkan!"]);
    } catch (Exception $e) {
      return redirect()->back()->withErrors(['error' => $e->getMessage()]);
    }
  }
}
