<?php

namespace App\Http\Controllers\Backend;

use App\Http\Models\UserModel;
use App\Http\Controllers\Helpers\EmailHelperController;
use DateTime;
use Exception;
use Str;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;

class AuthenticateController extends Controller
{
    private $userDataAccess;
    private $exceptionPage;
    private $emailHelper;

    public function __construct(
        EmailHelperController        $emailHelpAccess
    ) {
        $this->exceptionPage = response()->view('errors/500', [], 500);
        $this->emailHelper = $emailHelpAccess;
    }

    public function index()
    {
        if (!Auth::check()) {
            return Redirect::to('login');
        } else {
            return Redirect::to('dashboard');
        }
    }

    /* Login */
    public function login()
    {
        // logged
        if (!Auth::check()) {
            return View::make('backend/login');
        } else {
            return Redirect::to('dashboard');
        }
    }

    /* Authenticate */
    public function authenticate(Request $request)
    {
        $email = $request->input('email');
        $password = $request->input('password');
        $rememberMe = $request->input('remember_me');

        if ($email == '' && $password == '') {
            return response()->json([
                'status' => "Fail",
                'message' => "Email and Password is required"
            ]);
        } else if ($email == '') {
            return response()->json([
                'status' => "Fail",
                'message' => "Email is required"
            ]);
        } else if ($password == '') {
            return response()->json([
                'status' => "Fail",
                'message' => "Password is required"
            ]);
        }

        $us = UserModel::where('email', $email)
                ->first();
        if ($us == null) {
            return response()->json([
                'status' => "Fail",
                'message' => "Email was not found"
            ]);
        }

        if (Auth::attempt(['email' => $email, 'password' => $password], $rememberMe)) {
            return response()->json([
                'status' => "Success",
                'message' => "Success"
            ]);
        } else {
            return response()->json([
                'status' => "Fail",
                'message' => "Email or Password was incorrect"
            ]);
        }
    }

    public function logout()
    {
        Auth::logout();
        return Redirect::to('');
    }

    public function forgotPassword()
    {
        return View::make('backend/forgot_password');
    }

    public function updateForgotPassword(Request $request)
    {
        if ($request->isMethod('post')) {

            // get data
            $email = $request->input('email');

            // get user by email
            try {

                $userObject = UserModel::where('email', $email)
                ->first();

                // not found with email
                if (is_null($userObject)) {

                    return response()->json([
                        'status' => "Fail",
                        'message' => "Not found an Email"
                    ]);
                }

                // not an admin
                if ($userObject->role == 1) {
                    return response()->json([
                        'status' => "Fail",
                        'message' => "No permission"
                    ]);
                }

                // create token
                $token = Str::random(10);
                $dataUpdate = [
                    'forgot_password_token' => $token,
                    'forgot_password_date' => new DateTime()
                ];

                // update token
                 UserModel::where('id', $userObject->id)->update($dataUpdate);

                // send Email
                if (!env('TEST_LOCAL')) {
                    $this->emailHelper->sendEmailForgotPassword($email, $token);
                }

                return response()->json([
                    'status' => "Success",
                    'message' => "Please check your email"
                ]);
            } catch (Exception $e) {
                return response()->json([
                    'status' => "Fail",
                    'message' => "Forgot password unsuccessfully"
                ]);
            }
        } else {
            return View::make('backend/forgot_password');
        }
    }

    public function resetPassword($token)
    {
        // check token in database
        try {
            $userObjectByToken = UserModel::where('forgot_password_token', $token)
                ->first();

            // not found with email
            if ($userObjectByToken == null) {
                return redirect('no-permission')
                    ->with('messageFail', 'Fail')
                    ->with('messageDetail', 'No have permission');
            }

            return View::make('backend/reset_password')
                ->with('userIdView', $userObjectByToken->id ?? 1);
        } catch (Exception $e) {
            // return response()->json([
            //     'status' => "Fail",
            //     'message' => "Reset password unsuccessfully"
            // ]);
        }
    }

    public function updateResetPassword(Request $request)
    {
        $userId = $request->input('userId');
        $newPassword = $request->input('password');

        try {
            $userObj = UserModel::where('id', $userId)
                ->first();

            $data = [
                'password' => Hash::make($newPassword),
                'forgot_password_token' => '',
                'forgot_password_date' => null
            ];


            // set new password
            UserModel::where('id', $userId)->update($data);

            // send Email new password
            if (!env('TEST_LOCAL')) {
                $this->emailHelper->sendEmailResetPassword($userObj->email, $newPassword);
            }

            return response()->json([
                'status' => "Success",
                'message' => "Reset password success"
            ]);
        } catch (Exception $e) {
            return response()->json([
                'status' => "Fail",
                'message' => "Reset password unsuccessfully"
            ]);
        }
    }
}
