<?php

namespace App\Http\Controllers;

use App\Modules;
use App\Role;
use App\User;
use Auth;
use File;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use App\Models\UserAccess\UserAccessOrganization;
use Illuminate\Support\Str;
use stdClass;
use View;
use DB;
use App\Models\AgentAccess;
class UserController extends BenthamController
{
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /*
     * Date: 15-08-2018
     * Author: Muhammad Arshad
     * Parameter:
     * Description:  this method return the list of users from DB
     */

    public function index(Request $request)
    {

        $search = $request->get('search');
        if (isset($search) && $search != "") {
            $users = User::getUserList($search);
        } else {
            $users = User::getUserList();
        }

        return view('admin.users.index', with(['users' => $users]));
    }

    public function create()
    {

        // Get all the available roles
        $roles     = Role::all();
        $countries = $this->countries;
        // Show the page
        return view('admin.users.create', with(['roles' => $roles, 'countries' => $countries]));
    }

    public function store(Request $request)
    {
        $data = new stdClass();

        $validator = Validator::make($request->all(), [
            'name'     => 'required|string|max:255|unique:users',
            'email'    => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

        //upload image
        if ($file = $request->file('pic_file')) {
            $extension       = $file->extension() ?: 'png';
            $destinationPath = 'uploads/users/';
            $safeName        = str_random(10) . '.' . $extension;
            $file->move($destinationPath, $safeName);
            $request['pic'] = $safeName;
        }
        //check whether use should be activated by default or not
        $activate = $request->get('activate') ? true : false;
        $input    = $request->all();
        if ($validator->fails()) {
            $roles     = Role::all();
            $countries = $this->countries;
            $messages  = $validator->messages();
            return View::make('admin.users.create', with(['roles' => $roles, 'countries' => $countries]))
                ->withErrors($validator)
                ->with('input', $input);
        } else {

            try {
                // Register the user
                $user = User::create([
                    'display_name'=> $request->display_name,
                    'name'       => $request->name,
                    'first_name' => $request->first_name,
                    'last_name'  => $request->last_name,
                    'email'      => $request->email,
                    'password'   => Hash::make($request->password),
                    'user_type'      => $request->user_type,
                    'counter_usage_report' => $request->get('counter_usage_report') ?? 0,
                    'change_password'      => $request->get('change_password') ?? 0,
                    'bio'        => $request->bio,
                    'gender'     => $request->gender,
                    'dob'        => $request->dob,
                    'pic'        => $request->pic,
                    'country'    => $request->country,
                    'state'      => $request->state,
                    'city'       => $request->city,
                    'address'    => $request->address,
                    'postal'     => $request->postal,
                    'proxy_download' => $request->get('proxy_download') ?? 0,
                ]);
                
                $login_user     = Auth::user();
                //-------------------Insert into user domain table---------------
                $user_domain = $request->get("user_domain");
                if ($user_domain != "") {
                    $DomainArray = explode(",", $user_domain);
                    if (!empty($DomainArray)) {

                        for ($a = 0; $a < count($DomainArray); $a++) {
                            $add_keywords[] = array('user_domain' => $DomainArray[$a],
                               'user_id' => $user->id,
                               'created_on' => time(),
                               'created_by' => $login_user->id,
                               'updated_on' => time(),
                               'updated_by' => $login_user->id,
                            );
                        }
                        User::AddUserDomain($add_keywords);
                    }
                }

                //$user = Sentinel::register($request->except('_token', 'password_confirm', 'role', 'activate', 'pic_file'), $activate);

                //add user to 'User' group
                $role = Role::find($request->get('role'));
                if ($role) {
                    $role->users()->attach($user);
                }
                //check for activation and send activation mail if not activated by default
                if (!$request->get('activate')) {
                    // Data to be used on the email view
                    $data->user_name     = $user->first_name . ' ' . $user->last_name;
                    $data->activationUrl = URL::route('activate', [$user->id, Activation::create($user)->code]);

                    // Send the activation code through email
                    Mail::to($user->email)
                        ->send(new Restore($data));
                }
                // Activity log for New user create

                // Redirect to the home page with success menu
                return Redirect::route('users.index')->with('success', "User was successfully created.");

            } catch (LoginRequiredException $e) {
                $error = "The login field is required";
            } catch (PasswordRequiredException $e) {
                $error = "The password is required.";
            } catch (UserExistsException $e) {
                $error = "User already exists!";
            }
        }
        // Redirect to the user creation page
        return Redirect::back()->withInput()->with('error', $error);

    }

    public function show()
    {

    }

    public function edit(User $user)
    {

        $countries = $this->countries;

		$org = UserAccessOrganization::where('access_organization_id',$user->access_organization_id)->first();
		if (!empty($org))
		{
			$user->organization_name = $org->organization_name;
		}

        // -----------------------User Domain----------------//
        $user_domains = User::getUserDomainById($user->id, 'user_id');

        $user_domain = '';
        if (!empty($user_domains)) {

            foreach ($user_domains as $vals) {

                $user_domain .= $vals->user_domain . ',';

            }
            $user_domain = substr($user_domain, 0, -1);
        }
        //-------------------------User Agent By Name & Country ------------------------------
        $user_agent = '';
        $user_agent_country = [];
        if($user->agent_access_type == 'U'){
            $user_agent_obj = User::getUserAgentAccessByName($user->id);
           
            if (!empty($user_agent_obj)) {

                foreach ($user_agent_obj as $agents) {

                    $user_agent .= $agents->name . ',';

                }
                $user_agent = substr($user_agent, 0, -1);
            }
        }elseif($user->agent_access_type == 'C'){
            $user_agent_obj = User::getUserAgentAccessByCountry($user->id);
             
             if (!empty($user_agent_obj)) {
                foreach($user_agent_obj as $row){
                    array_push($user_agent_country, $row->agent_id);
                }
             }
        }    
       
        //------------------------------------------------------------------ 
        
        // -----------------------Consortia User----------------//
        $cparam['agent_id'] = $user->id;
        $user_consortia_counter = User::getUserConsoriaById($cparam);
        $user_consortia = '';
        if (!empty($user_consortia_counter)) {

            foreach ($user_consortia_counter as $vals) {

                $user_consortia .= $vals->user_name . ',';

            }
            $user_consortia = substr($user_consortia, 0, -1);
        }
        // Show the page
        return view('admin.users.edit', with(['user' => $user, 'countries' => $countries, 'user_domain' => $user_domain, 'user_consortia' => $user_consortia,'user_agent'=> $user_agent,'user_agent_country'=> $user_agent_country]));
    }

    public function update(User $user, Request $request)
    {
        // dd($request->all());
        try {
            $user->update($request->except('name', 'email', 'pic_file', 'password', 'password_confirm','autohrs_keywords','agent_access_type'));

            if (!empty($request->password)) {
                $user->password = Hash::make($request->password);
            }

             $users = User::GetUserByField('id',$user->id);
             
          
            //if (!empty($request->referral_url) && empty($users->referral_token)) 
            if (!empty($request->referral_url)) 
            {
                 $str_arr = explode (",", $request->referral_url);

                 $referral_url="";
                 
                 for($a=0; $a<sizeof($str_arr); $a++)
                 {
                    $referral_url = $referral_url.hash('sha256', $str_arr[$a]).",";
                 }
                 //print_r($referral_url); 
                 $referral_url = substr(trim($referral_url), 0, -1);

                 if(empty($users->referral_token))
                 {
                     $token = Str::random(60);
                     $user->referral_token = hash('sha256', $token);
                 }

                 $user->referral_url = $request->referral_url;
                 $user->referral_hash = $referral_url;
            }
            else
            {   
                if(trim($user->referral_url)=="")
                { 
                    $user->referral_url = NULL;
                    $user->referral_hash = NULL;
                    $user->referral_token = NULL;
                    $user->referral_login = NULL;
                }
            }
            // is new image uploaded?
            if ($file = $request->file('pic_file')) {
                $extension = $file->extension() ?: 'png';
                $destinationPath = public_path() . '/uploads/users/';
                //$destinationPath = 'uploads/users/';
                $safeName        = str_random(10) . '.' . $extension;
                $file->move($destinationPath, $safeName);
                //delete old pic if exists
                if (File::exists($destinationPath . $user->pic)) {
                    File::delete($destinationPath . $user->pic);
                }
                //save new file path into db
                $user->pic = $safeName;
            }
             $user->counter_usage_report = $request->get('counter_usage_report') ?? 0;
             $user->change_password      = $request->get('change_password') ?? 0;
             $user->openathensrealmName  = $request->get('openathensrealmName');
             $user->openathensderivedEduPersonScope = $request->get('openathensderivedEduPersonScope');

            //save record
            $user->save();

            // Was the user updated?
            if ($user->save()) {

                //-------------------Insert into user domain table---------------
                $login_user     = Auth::user();
                $user_domain = $request->get("user_domain");
                if ($user_domain != "") {
                    User::DeleteUserDomain($user->id, 'user_id');
                    $DomainArray = explode(",", $user_domain);
                    if (!empty($DomainArray)) {

                        for ($a = 0; $a < count($DomainArray); $a++) {
                            $add_keywords[] = array('user_domain' => $DomainArray[$a],
                               'user_id' => $user->id,
                               'created_on' => time(),
                               'created_by' => $login_user->id,
                               'updated_on' => time(),
                               'updated_by' => $login_user->id,
                            );
                        }
                        User::AddUserDomain($add_keywords);
                    }
                }
                 //-------------------Insert into user consortia counter table---------------
                $user_consortia_counter = $request->get("user_consortia_counter");
                if ($user_consortia_counter != "") {
                    User::DeleteUserConsortiaCounter($user->id, 'agent_id');
                    $UserConsortiaArray = explode(",", $user_consortia_counter);
                    if (!empty($UserConsortiaArray)) {

                        for ($a = 0; $a < count($UserConsortiaArray); $a++) {
                            
                             $consortia_user = User::GetUserByField('name',$UserConsortiaArray[$a]);

                             if($consortia_user)
                             {
                                $add_user_consortia[] = array(
                                   'agent_id'   => $user->id,
                                   'user_name'  => $consortia_user->name,
                                   'user_id'    => $consortia_user->id,
                                   'created_on' => time(),
                                   'created_by' => $login_user->id,
                                   'updated_on' => time(),
                                   'updated_by' => $login_user->id,
                                );
                             }
                        }

                        User::AddUserConsortiaCounter($add_user_consortia);
                    }
                }

                /***********************************************************************
                 *                          AGENT ACCESS 
                 ***********************************************************************/ 
                  $agent_access_type = $request->agent_access_type;
                  
                  if($agent_access_type != 'none'){

                      AgentAccess::where('user_id',$user->id)->delete();   
                      
                      $agent_users_data = [];

                      if($agent_access_type == 'by_user'){
                        $access_type = 'U';
                        if(!empty($request->user_agent)){
                            $users_array = explode(',',$request->user_agent);
                            foreach ($users_array as $agent_name) {
                               $agent_user_id = DB::table('users')->where('name',trim($agent_name))->pluck('id')->first();
                               if(!empty($agent_user_id)){
                                    $data = ['user_id' => $user->id, 
                                            'agent_id' => $agent_user_id, 
                                            'created_at' => time(), 
                                            'created_by' => $login_user->id];

                                    array_push($agent_users_data,$data);
                                }         

                            }
                        }
                       
                      }elseif($agent_access_type =='by_country'){
                        $access_type = 'C';
                        if(!empty($request->agent_countries)){
                            
                            foreach($request->agent_countries as $row){
                                $data = ['user_id' => $user->id, 
                                            'agent_id' => $row, 
                                            'created_at' => time(), 
                                            'created_by' => $login_user->id];

                                    array_push($agent_users_data,$data);
                            }
                        }
                      }
                      AgentAccess::insert($agent_users_data);
                      // update user access type in users table.
                      DB::table('users')->where('id',$user->id)->update(['agent_access_type'=>$access_type]);

                  }

                /***********************************************************************/ 
                /***********************************************************************
                                UPDATE AUTHORS KEYWORDS
                ***********************************************************************/ 
                $autohrs_keywords = $request->autohrs_keywords;
                if(!empty($autohrs_keywords)){
                    DB::table('users')->where('id',$user->id)->update(['autohrs_keywords'=>$autohrs_keywords]);
                }                
               
                // Redirect to the user page
                if (!empty($request->referral_url)) {
                    $success = "User was successfully updated.";
                    return redirect('admin/users/' . $user->id . '/edit')->withInput()->with('success', $success);
                }
                else
                {
                return redirect('admin/users')->with('success', "User was successfully updated.");
                }

            }

            // Prepare the error message
            $error = "There was an issue updating the user. Please try again.";
        } catch (UserNotFoundException $e) {
            // Prepare the error message
            $error = "User does not exist.";

            // Redirect to the user management page
            return redirect('admin/users/' . $user->id . '/edit')->withInput()->with('error', $error);
        }

        // Redirect to the user page
        return redirect('admin/users/' . $user->id . '/edit')->withInput()->with('error', $error);
    }

    public function destroy($id = "", Request $request)
    {
        $userid = $request->input('id');
        User::DeleteUser($userid);
        return redirect()->route('users.index')->with('success', 'User delete successfully.');
    }

    /*
     * Date: 17-08-2018
     * Author: Muhammad Arshad
     * Parameter: userid
     * Description:  this method Display the Assign role/permission
     */

    public function AssignRole($userid, Request $request)
    {
        $usermodules      = array();
        $user             = User::getUserById($userid);
        $roles            = Role::all();
        $modules          = Modules::all();
        $usermodulesArray = Modules::getUserModules($userid);
        for ($i = 0; $i < count($usermodulesArray); $i++) {
            $usermodules[$usermodulesArray[$i]->module_id] = $usermodulesArray[$i];
        }
        return view('admin.users.permission', with(['user' => $user,
         'roles' => $roles,
          'modules' => $modules,
           'usermodules' => $usermodules]));
    }

    /*
     * Date: 17-08-2018
     * Author: Muhammad Arshad
     * Parameter: request
     * Description:  this method will add the
     */

    public function AddRolePermission(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'role_id' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('admin/users/' . $request->input('user_id') . '/permissions')
                ->withErrors($validator)
                ->withInput();
        }
        //---------------------Inert into user role table---------------
        $add_role = array('user_id' => $request->input('user_id'),
            'role_id'                   => $request->input('role_id'),
            'created_at'                => date('Y-m-d'),
            'updated_at'                => date('Y-m-d'),
        );
        Role::DeleteRole($request->input('user_id'));
        Role::Add($add_role);

        $modules = Modules::all();
        Modules::DeleteRoleModule($request->input('user_id'));
        foreach ($modules as $module) {
            $add_role_module               = array();
            $insertflag                    = 0;
            $add_role_module['user_id']    = $request->input('user_id');
            $add_role_module['module_id']  = $module->id;
            $add_role_module['created_at'] = date('Y-m-d');
            $add_role_module['updated_at'] = date('Y-m-d');

            if ($request->input('view_' . $module->id . '_1') != null) {
                $add_role_module['acc_view'] = 1;
                $insertflag                  = 1;
            }if ($request->input('create_' . $module->id . '_1') != null) {
                $add_role_module['acc_create'] = 1;
                $insertflag                    = 1;
            }if ($request->input('edit_' . $module->id . '_1') != null) {
                $add_role_module['acc_edit'] = 1;
                $insertflag                  = 1;
            }if ($request->input('delete_' . $module->id . '_1') != null) {
                $add_role_module['acc_delete'] = 1;
                $insertflag                    = 1;
            }
            //print_r($add_role_module); die;

            if ($insertflag == 1) {
                Modules::Add($add_role_module);
            }

        }

        return redirect('admin/users/' . $request->input('user_id') . '/permissions')->with('success', 'Role/Permission has been added.');

    }

    public function lockscreen($id)
    {

        if (Auth::check()) {
            $user = User::find($id);
            return view('admin.lockscreen', with(['user' => $user]));
        }
        return view('admin.login');
    }

    public function postLockscreen(Request $request)
    {
        $password = Auth::getUser()->password;
        if (Hash::check($request->password, $password)) {
            return 'success';
        } else {
            return 'error';
        }
    }

    public static function CheckAddUserDetails($data)
    {  
        $user_details = User::GetUserByField('email',$data->user_email);
        if (empty($user_details))
        {
            $pass = Str::random(10);
            
            $user_details['name'] = $data->user_email;
            $user_details['display_name'] = $data->user_name;
            $user_details['email'] = $data->user_email;
            $user_details['country'] = $data->user_country;
            $user_details['password'] = Hash::make($pass);
            
            $user_details['status'] = 1;
            $user_details['created_at'] = time();
            $user_details['updated_at'] = time();
            $user_details['org_name'] = '';
            $user_details['org_branch'] = '';
            $user_details['user_type'] = 'user';
            $user_details['access_organization_id'] = 0;
            $user_details['id'] = User::insertGetId($user_details);
            $user_details['password_text'] = $pass;
        }

        return $user_details;
    }

/*  This function use for discipline article access, campaign user register here */

    public static function DirectUserRegister($disc_access_code)
        {
            $pass = Str::random(10);
            
        $user_details['name'] = $disc_access_code;
        $user_details['display_name'] = $disc_access_code;
        $user_details['email'] = $disc_access_code.'@xolva.com';
        $user_details['country'] = 'PK';
            $user_details['password'] = Hash::make($pass);
            
            $user_details['status'] = 1;
            $user_details['created_at'] = time();
            $user_details['updated_at'] = time();
            $user_details['org_name'] = '';
            $user_details['org_branch'] = '';
            $user_details['user_type'] = 'user';
            $user_details['access_organization_id'] = 0;
            $user_details['id'] = User::insertGetId($user_details);

        return (object) $user_details;
    }
}
