<?php

namespace App\Http\Controllers\User\Auth;

use Exception;
use App\Models\Page;
use App\Models\User;
use App\Models\Order;
use App\Models\Deposit;
use App\Mail\HelperEmail;
use App\Mail\ActivateEmail;
use App\Models\Information;
use App\Models\RegisterLog;
use Illuminate\Support\Str;
use App\Models\UserLoginLog;
use App\Models\PasswordReset;
use Illuminate\Support\Carbon;
use App\Models\ActivateAccount;
use App\Models\UserRegisterLog;
use App\Models\UserActivateAccount;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Models\Cookie as CookieModel;
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 RegisterController 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.register');
    }
    public function post(RegisterRequest $request) {
        if ($request->ajax() == false) abort('404');
        $input_data = [
            'full_name'    => escape_input(ucwords($request->full_name)),
            'email' 	   => escape_input($request->email),
            'phone_number' => escape_input($request->phone_number),
            'username'     => escape_input($request->username),
            'password'     => escape_input(Hash::make($request->password)),
            'balance'      => 0,
            'level'        => 'Member',
            'api_key'      => create_api_key(),
            'is_verified'  => '0',
        ];
        if (website_config('main')->is_email_confirmation_enabled == '') {
            $input_data['is_verified'] = '1';
        }
        $check_data['ip_address'] = UserRegisterLog::where([['ip_address', $request->ip()], ['upline_user_id', null]])->first();
        if ($check_data['ip_address'] == true) {
            return response()->json([
                'alert'   => 'info', 
                'status'  => false, 
                'type'    => 'alert',
                'message' => 'Anda sudah mendaftarkan akun sebelumnya.'
            ]);
        }
        $insert_data = User::create($input_data);
        if ($this->location) {
            UserRegisterLog::create([
                'user_id'    => $insert_data->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 {
            UserRegisterLog::create([
                'user_id'    => $insert_data->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()).')'
            ]);
        }
        if ($input_data['is_verified'] == '0') {
            $input_data['token'] = md5($input_data['email'].'-'.$input_data['username'].'-'.rand(1, 99999));
            $email_details = [
                'content' => [
                    'url'   => url('auth/activate/'.$input_data['token']),
                    'token' => $input_data['token']
                ],
                'receiver' => [
                    'email' => $input_data['email'],
                    'name'  => $input_data['full_name'],
                ]
            ];
            $insert_data = UserActivateAccount::create([
                'email' => $input_data['email'],
                'token' => $input_data['token']
            ]);
            if ($insert_data == true) {
                $send_email = send_email($email_details, 'Aktivasi Akun - '.website_config('main')->website_name.'', 'user.mail.activate');
                if ($send_email['result'] == true) {
                    session()->flash('result', [
                        'alert'   => 'info', 
                        'title'   => 'Informasi', 
                        'message' => 'Silahkan periksa Email anda untuk mengaktifkan akun Anda.',
                        'timeout' => 3000,
                        'size'    => 'col-lg-6 offset-lg-3'
                    ]);
                    return response()->json([
                        'status'  => true, 
                        'message' => 'Silahkan periksa Email anda untuk mengaktifkan akun Anda.'
                    ]);
                } else {
                    return response()->json([
                        'status'  => false, 
                        'type'    => 'alert',
                        'message' => 'Terjadi Kesalahan.'
                    ]);
                }
            } else {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Terjadi Kesalahan.'
                ]);
            }
        }
        session()->flash('result', [
            'alert'   => 'success', 
            'title'   => 'Berhasil', 
            'message' => 'Pendaftaran berhasil, silahkan masuk.',
            'timeout' => 3000,
            'size'    => 'col-lg-6 offset-lg-3'
        ]);
        return response()->json([
            'status'  => true, 
            'message' => 'Pendaftaran berhasil, silahkan masuk.'
        ]);
    }
}

class RegisterRequest 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 [
            'full_name'        => 'required|max:30|regex:/^[\pL\s\-]+$/u|unique:users,full_name',
            'phone_number'     => 'required|numeric|phone:ID,mobile|unique:users,phone_number',
            'email'            => 'required|email|unique:users,email',
            'username'         => 'required|alpha_num|min:5|max:20|unique:users,username',
            'password'         => 'required|alpha_num|min:5|max:20',
            'confirm_password' => 'required|same:password',
            'approval'         => 'required|in:1',
        ];
    }
    public function attributes() {
        return [
            'full_name'        => 'Nama Lengkap',
            'phone_number'     => 'Nomor Telepon',
            'email'            => 'Email',
            'username'         => 'Username',
            'password'         => 'Password',
            'confirm_password' => 'Konfirmasi Password',
            'approval'         => 'Persetujuan',
        ];
    }
}