<?php

namespace App\Http\Controllers\Auth;

use Formatter;
use App\Helpers\Helpers;
use App\Http\Controllers\Controller;
use App\Models\Autoreply;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        if (!empty($request->lastname)) return redirect('/login');
        if (filter_var(Helpers::setting('requireStrongPassword'), FILTER_VALIDATE_BOOLEAN)) {
            $request->validate([
                'name' => ['required', 'string', 'max:255', 'unique:users'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'phone' => ['required', 'string'],
                'password' => ['required', 'confirmed', Rules\Password::defaults()->mixedCase()->numbers()->symbols()],
            ]);
        } else {
            $request->validate([
                'name' => ['required', 'string', 'max:255', 'unique:users'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'phone' => ['required', 'string'],
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
            ]);
        }

        $username = str_replace(' ', '_', strtolower($request->name));
        $email = strtolower($request->email);
        $phone = Formatter::pf($request->phone);
        $role = 'user';
        $lang = config('app.locale');
        $theme = config('app.theme');
        $package_id = 2;
        $trial_period = (int) Helpers::setting('trialPeriod');
        $billing_interval = 'monthly';
        $billing_start = Carbon::now();
        $billing_end = Carbon::now()->addDay($trial_period);
        $ip_address = Self::getUserIpAddr();
        $ip_banned = User::where('ip_address', '<>', null || '' || '::1')->where('banned', '=', 1)->where('ip_address', '=', $ip_address)->first();
        if (!empty($ip_banned)) return redirect()->route('user.banned', ['ip_address' => $ip_address]);
        if (User::where('name', 'like', "%$username")->count() > 0) return redirect()->route('user.deleted', ['name' => $username]);
        if (User::where('email', 'like', "%$email")->count() > 0) return redirect()->route('user.deleted', ['email' => $email]);
        if (User::where('phone', 'like', "%$phone")->count() > 0) return redirect()->route('user.deleted', ['phone' => $phone]);

        $user = User::create([
            'name' => $username,
            'email' => $email,
            'phone' => $phone,
            'password' => Hash::make($request->password),
            'role' => $role,
            'lang' => $lang,
            'theme' => $theme,
            'package_id' => $package_id,
            'trial_period' => $trial_period,
            'billing_interval' => $billing_interval,
            'billing_start' => $billing_start,
            'billing_end' => $billing_end,
            'ip_address' => $ip_address,
        ]);

        $num = rand(1, 28);
        $path = public_path("users/$user->id");
        $source = public_path("app-assets/images/avatars/$num.png");
        $target = "$path/avatar.png";
        File::ensureDirectoryExists($path, 0755, true);
        File::copy($source, $target);

        event(new Registered($user));

        Auth::login($user);

        return redirect(RouteServiceProvider::HOME);
    }

    private static function getUserIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            //ip from share internet
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            //ip pass from proxy
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
}
