<?php

namespace App\Http\Controllers\nn_site;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\nn_site_users;
use App\Models\nn_company;
use App\Models\nn_company_lang;
use App\Models\nn_category;
use App\Models\nn_company_category;
use DB;
use Illuminate\Support\Facades\Hash;
use LaravelLocalization;

class SiteUserPage extends SiteController
{
    public function __construct()
    {
        parent::__construct();
    }

    // /**
    //  * Display a listing of the resource.
    //  *
    //  * @return \Illuminate\Http\Response
    //  */
    // public function index(Request $request)
    // {
    //     return view('nn_site.pages.profile', ['user' => self::getUser($request)]);
    // }

    // public static function getUser($request)
    // {
    //     $userid = $request->session()->get('user');
       
    //     $user = DB::table('nn_site_users') ->select(
    //         'id',
    //         'email',
    //         'password',
    //         )->where('id', $userid->id)->first();

    //     return $user;
    // }

    public function index()
    {
        $logedIn = $this->redirectIfLogedIn();

        if ($logedIn) {
            return $logedIn;
        }

        return view('nn_site.pages.login');
    }

    public function redirectIfLogedIn()
    {
        if (session()->get('company_user')) {

            return redirect()->route('company-profile');
            
        } else if (session()->get('user')) {

            return redirect()->route('profile');

        } else {
            
            return false;

        }
    }

    public function login(Request $request)
    {
        $validator  = $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);

        $user = DB::table('nn_site_users')->select
                                                (
                                                    'id',
                                                    'email',
                                                    'password',
                                                    'user_type'
                                                )
                                                ->where('email', $request->email)->first();
        
        if ($user && Hash::check($request->password, $user->password)) {

            $userForSession = array();
            $userForSession['id'] = $user->id;

            if ($user->user_type == 1) {

                $userForSession['company_id'] = DB::table('nn_company')->where('user_id', $user->id)->select('id')->first()->id;

                $request->session()->put('company_user', $userForSession);

                return redirect(getCurrentLocale() . '/company/profile');
                
            } else {

                $request->session()->put('user', $userForSession);

                return redirect(getCurrentLocale() . '/profile');

            }

        } else {

            return redirect(getCurrentLocale() . '/login');

        }
    }

    public function logout()
    {
        session()->forget('company_user');
        session()->forget('user');

        return redirect(getCurrentLocale() . '/login');
    }

    public function registerForm()
    {
        $logedIn = $this->redirectIfLogedIn();

        if ($logedIn) {
            return $logedIn;
        }

        $data['categories'] = nn_category::getCategory();
        
        return view('nn_site.pages.register', $data);
    }

    public function register(Request $request)
    {
        $userType = $request->is_company ? 1 : 0;

        $validationData = [
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'unique:nn_site_users,email',
            'phone' => 'required',
            'personal_id' => 'required|max:11|min:11',
            'password' => 'required|confirmed|min:6',
        ];

        if ($userType == 1) {

            $validationData['company_name'] = 'required';
            $validationData['company_code'] = 'required';
            $validationData['category_id'] = 'required';

        }

        $validated = $request->validate($validationData);

        $user = new nn_site_users();
        $user->firstname = $request->firstname;
        $user->lastname = $request->lastname;
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->personal_id = $request->personal_id;
        $user->user_type = $userType;
        
        $user->password = Hash::make($request->password);
        $user->save();

        if ($userType == 1) {
            $company = new nn_company();

            $company->code = $request->company_code;
            $company->user_id = $user->id;

            $company->save();

            $companyIds = $request->get('category_id');

            foreach ($companyIds as $item) {

                $companyCategory = new nn_company_category();
    
                $companyCategory->company_id = $company->id;
                $companyCategory->category_id = $item;
    
                $companyCategory->save();
    
            }

            foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties) {

                $companyLang = new nn_company_lang();

                $companyLang->name = $request->company_name;
                $companyLang->lang = $localeCode;
                $companyLang->company_id = $company->id;

                $companyLang->save();

            }
        }

        if ($user) {
            return redirect('/'.getCurrentLocale().'/register?success=1');
        } else {
            return redirect('/'.getCurrentLocale().'/register?success=0');
        }
    }
    
    public function update(Request $request)
    {
        $user = $request->session()->get('user');
    
        if( $user->usertype == 0){

            $validator  = $request->validate([
                
                'name' => 'required|max:100|min:2',
                'mobile' => 'required|max:13|min:9',
                'surname' => 'required|max:150|min:2',
                'email' => 'email:rfc,dns|unique:nn_site_users,email,'.$user->id,
                'personal_id' => 'required|max:11|min:11|unique:nn_site_users,personal_id,'.$user->id,
                
            ]);

        } else {
            $validator  = $request->validate([
                
                'name' => 'required|max:100|min:2',
                'company_name' => 'required|max:200|min:2',
                'surname' => 'required|max:150|min:2',
                'email' => 'email:rfc,dns|unique:nn_site_users,email',
                'company_id' => 'required|max:9|min:9|unique:nn_site_users,company_id',
                'password' => 'required|confirmed|min:6',

            ]);
    
        }

        if ($request->oldPassword != '') {

            $validator  = $request->validate([
                
                'password' => 'required|confirmed|min:6',
                
            ]);

        }

        $useru = nn_site_users::find($user->id);
       
        $useru->name = $request->name;
        $useru->surname = $request->surname;
        $useru->email = $request->email;
        $useru->mobile = $request->mobile;

        if ($request->usertype == 1) {
            $useru->company_name = $request->company_name;
            $useru->company_id = $request->company_id;
        } else {
            $useru->personal_id = $request->personal_id;
        }

        if ($request->oldPassword != '')
        $useru->password = Hash::make($request->password);

        $useru->save();

        if ($user) {
            return redirect('/'.getCurrentLocale().'/user/profile/success');
        } else {
            return redirect('/'.getCurrentLocale().'/user/profile/fail');
        }
    }
}
