<?php

namespace App\Http\Controllers\User\Auth;

use App\Models\UserCookie;
use Illuminate\Support\Str;
use App\Models\UserLoginLog;
use App\Models\UserActivateAccount;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Stevebauman\Location\Facades\Location;

class LoginController extends Controller {
	public function __construct(Request $request) {
        $this->middleware('guest');
        $this->user_agent = new Agent();
        $this->location = Location::get($request->ip());
	}
    public function get() {
        return view('user.auth.login');
    }
    public function post(LoginRequest $request) {
        if ($request->ajax() == false) abort('404');
        $input_data = [
            'username' => escape_input($request->username),
            'password' => escape_input($request->password),
        ];
        if (Auth::attempt($input_data) == true) {
            if (Auth::user()->status == 0) {
                Auth::logout();
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Akun dinonaktifkan.'
                ]);
            }
            if (Auth::user()->is_verified == '0' AND website_config('main')->is_email_confirmation_enabled <> '') {
                $input_data['token'] = md5(Auth::user()->email.'-'.Auth::user()->username.'-'.rand(1, 99999));
                $email_details = [
                    'content' => [
                        'url'   => url('auth/activate/'.$input_data['token']),
                        'token' => $input_data['token']
                    ],
                    'receiver' => [
                        'email' => Auth::user()->email,
                        'name'  => Auth::user()->full_name,
                    ]
                ];
                $check_data = UserActivateAccount::where('email', Auth::user()->email)->first();
                if ($check_data == false) {
                    $insert_data = UserActivateAccount::create([
                        'email' => Auth::user()->email,
                        'token' => $input_data['token']
                    ]);
                    if ($insert_data == false) {
                        Auth::logout();
                        return response()->json([
                            'status'  => false, 
                            'type'    => 'alert',
                            'message' => 'Terjadi kesalahan.'
                        ]);
                    }
                } else {
                    $update_data = $check_data->update([
                        'email'      => Auth::user()->email,
                        'token'      => $input_data['token'],
                        'created_at' => now()
                    ]);
                    if ($update_data == false) {
                        Auth::logout();
                        return response()->json([
                            'status'  => false, 
                            'type'    => 'alert',
                            'message' => 'Terjadi kesalahan.'
                        ]);
                    }
                }
                $send_email = send_email($email_details, 'Aktivasi Akun - '.website_config('main')->website_name.'', 'user.mail.activate');
                if ($send_email['result'] == true) {
                    Auth::logout();
                    return response()->json([
                        'alert'   => 'info',
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Silahkan periksa Email anda untuk mengaktifkan akun Anda.'
                    ]);
                } else {
                    Auth::logout();
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Terjadi kesalahan.'
                    ]);
                }
            }
            if ($request->remember  == '1') {
                $random_string = Str::random(40);
                UserCookie::create([
                    'user_id' 	  => Auth::user()->id,
                    'value'	  	  => $random_string,
                    'expired_at'  => date('Y-m-d H:i:s', strtotime('next month'))
                ]);
                Cookie::queue(Cookie::make('user', $random_string, strtotime('next month')));
            }
            if ($this->location) {
                UserLoginLog::create([
                    'user_id'    => Auth::user()->id,
                    'ip_address' => $request->ip(),
                    'location'   => $this->location->countryName.' - '.$this->location->regionName.' - '.$this->location->cityName.' ('.$this->user_agent->device().' - '.$this->user_agent->platform().'/'.$this->user_agent->version($this->user_agent->platform()).' - '.$this->user_agent->browser().'/'.$this->user_agent->version($this->user_agent->browser()).')'
                ]);
            } else {
                UserLoginLog::create([
                    'user_id'    => Auth::user()->id,
                    'ip_address' => $request->ip(),
                    'location'   => '('.$this->user_agent->device().' - '.$this->user_agent->platform().'/'.$this->user_agent->version($this->user_agent->platform()).' - '.$this->user_agent->browser().'/'.$this->user_agent->version($this->user_agent->browser()).')'
                ]);
            }
			Session::put('information_popup', true);
            session()->flash('result', [
                'alert'   => 'success', 
                'title'   => 'Berhasil', 
                'message' => 'Selamat datang <b>'.Auth::user()->full_name.'</b>.',
                'timeout' => 8000,
                'size'    => 'col-lg-12'
            ]);
            return response()->json([
                'status'  => true, 
                'message' => 'Anda akan segera dialihkan secara otomatis.'
            ]);
        } else {
            return response()->json([
                'status'  => false, 
                'type'    => 'validation',
                'message' => ['password' => [
                    '- <b>Password</b> salah.'
                ]]
            ]);
        }
    }
}

class LoginRequest 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 [
            'username' => 'required|exists:users,username',
            'password' => 'required|string'
        ];
    }
    public function attributes() {
        return [
            'username' => 'Username',
            'password' => 'Password',
        ];
    }
}