<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function login_load()
    {
        if (auth()->user()) {
            return redirect('user/pending');
        }
        return view("auth.signin");
    }
    public function login_post(Request $request)
    {
        $request->validate([
            "email" => 'required',
            "password" => 'required',
        ]);
        $user = User::where("email", $request->email)->where("role", "user")->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return redirect()->back()->with("message", "Wrong Credentials");
        } else {
            $auth = Auth::attempt($request->only('email', 'password'));
            return redirect('user/pending');
        }
    }

    public function register_load()
    {
        return view("auth.sign-up");
    }

    public function register_form(Request $request)
    {
        $request->validate([
            "fname" => "required",
            "lname" => "required",
            "email" => "required",
            "password" => "required",
            "employeeID" => "required",
            "phone" => "required",
            "department" => "required",
            "jobTitle" => "required",

        ]);
        $user = new User();
        $user->role = "user";
        $user->fname = $request->fname;
        $user->lname = $request->lname;
        $user->employee_id = $request->employeeID;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->phone = $request->phone;
        $user->comp_dept = $request->department;
        $user->job_title = $request->jobTitle;
        $user->approved = 0;
        $result = $user->save();
        if ($result) {
            $auth = Auth::attempt($request->only('email', 'password'));
            return redirect("user/pending");
        }
        return redirect("user/pending");
    }

    public function pending_load()
    {
        $user_id = auth()->user()->id;
        if (auth()->user()->approved == 0) {
            $user = User::find($user_id);
            $data = compact('user');
            return view("auth.pending", $data);
        } else {
            return redirect("user/home");
        }

    }

    public function logout()
    {
        auth()->logout();
        return redirect("user/login");
    }
}
