<?php

namespace App\Http\Controllers\User\Auth;

use Exception;
use App\Models\User;
use App\Mail\HelperEmail;
use App\Models\UserPasswordReset;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class ResetPasswordController extends Controller {
	public function __construct() {
        $this->middleware('guest');
	}
    public function get($reset_token = null) {
        if ($reset_token == null) {
            return view('user.auth.passwords.email');
        } else {
            $check_token = UserPasswordReset::where('token', $reset_token)->first();
            if ($check_token == false) return redirect('auth/reset');
            $components['target'] = $check_token;
            return view('user.auth.passwords.reset', $components);
        }
    }
    public function post($reset_token = null, ResetRequest $request) {
        if ($request->ajax() == false) abort('404');
        if ($reset_token == null) {
            $user = User::where('email', escape_input($request->email))->first();
            $input_data = [
                'email' => escape_input($request->email),
                'token' => md5(escape_input($request->email).'-'.$user->username.'-'.rand(1, 99999))
            ];
            $check_data = UserPasswordReset::where('email', $input_data['email'])->first();
            if ($check_data == false) {
                $insert_data = UserPasswordReset::create($input_data);
                if ($insert_data == false) {
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Terjadi Kesalahan.'
                    ]);
                }
            } else {
                $update_data = $check_data->update([
                    'email'      => $input_data['email'],
                    'token'      => $input_data['token'],
                    'created_at' => now()
                ]);
                if ($update_data == false) {
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Terjadi Kesalahan.'
                    ]);
                }
            }
            $email_details = [
                'content' => [
                    'url'   => url('auth/reset/'.$input_data['token']),
                    'token' => $input_data['token']
                ],
                'receiver' => [
                    'email' => $user->email,
                    'name'  => $user->full_name,
                ]
            ];
            $send_email = send_email($email_details, 'Atur Ulang Kata Sandi - '.website_config('main')->website_name.'', 'user.mail.reset_password');
            if ($send_email['result'] == true) {
                session()->flash('result', [
                    'alert'   => 'info', 
                    'title'   => 'Informasi', 
                    'message' => 'Silahkan periksa Email anda untuk mengatur ulang kata sandi akun Anda.',
                    'timeout' => 5000,
                    'size'    => 'col-lg-6 offset-lg-3'
                ]);
                return response()->json([
                    'status'  => true, 
                    'message' => 'Silahkan periksa Email anda untuk mengatur ulang kata sandi akun Anda.'
                ]);
            } else {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Terjadi Kesalahan.'
                ]);
            }
        } else {
            $input_data['password'] = escape_input(Hash::make($request->password));
            $update_data = User::where('email', $request->email)->update($input_data);
            if ($update_data == true) {
                $delete_data = UserPasswordReset::where('email', $request->email)->delete();
                session()->flash('result', [
                    'alert'   => 'success', 
                    'title'   => 'Berhasil', 
                    'message' => 'Password berhasil diatur ulang.',
                    'timeout' => 5000,
                    'size'    => 'col-lg-6 offset-lg-3'
                ]);
                return response()->json([
                    'status'  => true, 
                    'message' => 'Password berhasil diatur ulang.'
                ]);
            } else {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Terjadi Kesalahan.'
                ]);
            }
        }
    }
}

class ResetRequest extends FormRequest {
    protected function getValidatorInstance() {
		$instance = parent::getValidatorInstance();
        if ($instance->fails() == true) {
			throw new HttpResponseException(response()->json([
				'status'  => false, 
				'type'    => 'validation',
				'message' => parent::getValidatorInstance()->errors()
			]));
		}
        return parent::getValidatorInstance();
    }
	public function rules() {
        return [
            'email'            => 'required|email|exists:users,email',
            'password'         => request()->segment(3) == null ? '' : 'required|alpha_num|min:5|max:15',
            'confirm_password' => request()->segment(3) == null ? '' : 'required|same:password',
        ];
    }
    public function attributes() {
        return [
            'email'            => 'Email',
            'password'         => 'Password',
            'confirm_password' => 'Konfirmasi Password'
        ];
    }
}