<?php

namespace App\Http\Controllers\Auth;

use App\Models\Job;
use App\Models\User;
use App\Models\Admin;
use App\Models\Lead;
use App\Models\Company;
use Illuminate\Validation\Rule;
use App\Models\Setting;
use App\Models\Candidate;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Providers\RouteServiceProvider;
use App\Http\Traits\HasCountryBasedJobs;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Notifications\CompanyCreatedNotification;
use App\Notifications\CandidateCreateNotification;
use App\Notifications\Admin\NewUserRegisteredNotification;
use App\Notifications\CompanyCreateApprovalPendingNotification;
use App\Notifications\CandidateCreateApprovalPendingNotification;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers, HasCountryBasedJobs;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectPath = RouteServiceProvider::HOME;


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }


    /**
     * Show the application registration form.
     *
     * @return \Illuminate\View\View
     */
    public function showRegistrationForm()
    {
        $data['newjobs'] = $this->filterCountryBasedJobs(Job::withoutEdited()->newJobs())->count();

        return view('auth.register', $data);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        
            return  Validator::make($data, [
                'name' => ['required', 'string', 'max:255'],
                'email' => [
                    'required',
                    'email',
                    Rule::unique('users', 'email')->where(function ($query){
                        return $query->whereNull('deleted_at');
                    }),
                ],
                'phone' => [
                    'required',
                    Rule::unique('users', 'phone')->where(function ($query){
                        return $query->whereNull('deleted_at');
                    }),
                ],
                'country' => ['required'],
                // 'password' => ['required', 'string', 'min:8', 'confirmed'],
                // 'g-recaptcha-response' => config('captcha.active') ? 'required|captcha' : ''
            ]
            // , [
            //     'g-recaptcha-response.required' => 'Please verify that you are not a robot.',
            //     'g-recaptcha-response.captcha' => 'Captcha error! try again later or contact site admin.',
            // ]
            );
       
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        $newUsername = Str::slug($data['name']);
        $oldUserName = User::where('username', $newUsername)->first();
        if ($oldUserName) {
            $username = Str::slug($newUsername) . '_' . Str::random(5);
        } else {
            $username = Str::slug($newUsername);
        }
        if(!empty($data['country'])){
            $countryData = explode('@#$?',$data['country']);
            $country=$countryData[0];
            $data['country']=$country;
            if(!empty($country)) $data['country']=$country;
            
            $code=$countryData[1];
            if(!empty($code)) $data['country_code']=$code;
        }
        $providerName = null;
        $providerId = null;

        if(isset($data['providerId'])){
            $providerId = $data['providerId'];
        }
        if(isset($data['providerName'])){
            $providerName = $data['providerName'];
        }
        $data['password']= Str::random(8, 'alnum') . '@#';
        $user = User::create([
            'role' => $data['role'] == 'candidate' ? 'candidate' : 'company',
            'name' => $data['name'],
            'username' => $username,
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'phone' => $data['phone'],
            'country' => @$data['country'],
            'country_code' => @$data['country_code'],
            'source' => 'Register',
            'provider' => $providerName,
            'provider_id' => $providerId,
        ]);
        $oldUser = $user;
        $oldUser->password = $data['password'];

                $lead = new Lead;
                $lead->name = $data['name'];
                $lead->email = $data['email'];
                $lead->phone = $data['phone'];
                $lead->country_id = $data['country'];
                $lead->url =  '/register';
                $lead->source =  'Register';
                $lead = $lead->save();

        session(['auth.password_confirmed_at' => time()]);
        try {
            $admins = Admin::all();
            foreach ($admins as $admin) {
                Notification::send($admin, new NewUserRegisteredNotification($admin, $user));
            }
        } catch (\Throwable $th) {}

        // if mail configured, send notification to candidate and company
        // if (checkMailConfig()) {
        //     if ($user->role == "candidate") {
        //         $candidate_account_auto_activation_enabled = Setting::where("candidate_account_auto_activation", 1)->count();
        //         if ($candidate_account_auto_activation_enabled) {
        //             Notification::route('mail', $user->email)->notify(new CandidateCreateNotification($user, $data['password']));
        //         } else {
        //             Notification::route('mail', $user->email)->notify(new CandidateCreateApprovalPendingNotification($user, $data['password']));
        //         }
        //     } elseif ($user->role == "company") {
        //         $employer_auto_activation_enabled = Setting::where("employer_auto_activation", 1)->count();
        //         if ($employer_auto_activation_enabled) {
        //             Notification::route('mail', $user->email)->notify(new CompanyCreatedNotification($user, $data['password']));
        //         } else {
        //             Notification::route("mail", $user->email)->notify(new CompanyCreateApprovalPendingNotification($user, $data['password']));
        //         }
        //     }
        // }
        $data = array('data'=>$oldUser);
        Mail::send('mails.welcome-mail', $data, function($message) use($oldUser) {
            $message->to($oldUser->email, 'Gradding')->subject
            ('Welcome to Gradding');
            $message->from('contact@gradding.com','Gradding Team');
        });
        
        return $user;
    }
}
