<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;
use App\Models\Teacher;
use App\Models\Student;

class RegisterController extends Controller
{
  function returnToLogin()
  {
    return redirect()
      ->route('login')
      ->with('success', 'sorry but the session already timeout');
  }

  function errHandler($th)
  {
    $ERR_CANNOT_GET_EMAIL = 'Attempt to read property "email" on null';

    if ($ERR_CANNOT_GET_EMAIL == $th->getMessage()) {
      return $this->returnToLogin();
    } else {
      throw $th;
    }
  }

  public function createTeacher()
  {
    return view('register.createTeacher');
  }

  public function createStudent()
  {
    return view('register.createStudent');
  }

  public function registerTriage()
  {
    return view('register.triage');
  }

  public function create()
  {
    return view('register.create');
  }

  public function store()
  {
    try {
      $attributes = request()->validate([
        // name = firstName
        'name' => 'max:255',
        'lastName' => 'max:255',
        'email' => 'email|max:255|unique:users,email',
        'password' => 'min:5|max:255',
        'registerUserRole' => '',
      ]);

      $register_user_role = $attributes['registerUserRole'];

      if ($register_user_role == 'teacher') {
        $new_user = new User();
        $new_user->name = $attributes['name'];
        $new_user->email = $attributes['email'];
        $new_user->password = $attributes['password'];
        $new_user->role = 'teacher';
        $new_user->save();
        $new_user_id = $new_user->id;

        auth()->login($new_user);

        $teacher = new Teacher();
        $teacher->email = $attributes['email'];
        $teacher->firstName = $attributes['name'];
        $teacher->lastName = $attributes['lastName'];
        $teacher->user_id = $new_user_id;

        $teacher->save();

        return redirect()->route('teacherShowDashboard');
      } elseif ($register_user_role == 'student') {
        $new_user = new User();
        $new_user->name = $attributes['name'];
        $new_user->email = $attributes['email'];
        $new_user->password = $attributes['password'];
        $new_user->role = 'student';
        $new_user->save();
        $new_user_id = $new_user->id;

        auth()->login($new_user);

        $student = new Student();
        $student->email = $attributes['email'];
        $student->firstName = $attributes['name'];
        $student->lastName = $attributes['lastName'];
        $student->user_id = $new_user_id;

        $student->save();

        return redirect()->route('studentShowDashboard');
      } else {
        return route('helloworld');
      }

      return route('helloworld');
    } catch (\Throwable $th) {
      return $this->errHandler($th);
    }
  }
}
