<?php

namespace App\Http\Controllers;
use EF;
use Auth;

use Crypt;
use App\User;
use DataTables;
use App\Contract;
use App\Department;
use App\Designation;
use App\ContractDetail;
use App\AssignDepartment;
use Illuminate\Http\Request;
use App\Inventory\VendorType;
use App\Http\Requests\UserRequest;
use Spatie\Permission\Models\Role;
use Illuminate\Contracts\Encryption\DecryptException;

class UserController extends Controller
{

    public function index()
    {
      return view('user.manage_customer');
    }

    public function showProfile()
    {
        return view('user.user_profile');
    }

    public function updateProfile(UserRequest $request)
    {
       try
       {
           $white_label = EF::branchWhiteLabel();

           $collect_form = $request->input();

           $user = new User;

           $collect_form['user_id'] = Auth::user()->id;

           $collect_form[$white_label['module']] = Auth::user()->branch_id;

           $collect_form['user_image'] = $request->user_image;

           $collect_form['designation_id'] = Auth::user()->designation_id;

           $collect_form['salary_mode']     = Auth::user()->salary_mode;
           $collect_form['bank_branch']     = Auth::user()->bank_branch;
           $collect_form['bank_name']       = Auth::user()->bank_name;
           $collect_form['account_no']      = Auth::user()->account_no;
           $collect_form['employee_form']   = Auth::user()->employee_form;
           $collect_form['blood_group']     = Auth::user()->blood_group;
           $collect_form['vendor_type']     = Auth::user()->vendor_type;
           $collect_form['employee_type']   = Auth::user()->employee_type;
           $collect_form['passport']        = Auth::user()->passport;
           $collect_form['other_contact']   = Auth::user()->other_contact;
           $collect_form['permanent_address']   = Auth::user()->permanent_address;
           $collect_form['temporary_address']   = Auth::user()->temporary_address;
           $collect_form['type']            = "Employee";









           $curr_user = $user->updateUser($collect_form,$white_label['module']);

           if($curr_user->id)
           {
              parent::successMessage('Profile has been updated.');
           }
       }
       catch (DecryptException $e)
       {

       }

       return back();

    }

    public function showCustomerDatatable()
    {
      try
      {
        
        $user = new User;
        $user_list = $user->getUserListByType(['Customer']);
        $count = 0;

        return DataTables::of($user_list)

        ->addColumn('count', function($rows) use (&$count) {
              return strval(++$count);
           })
           ->addColumn('name', function($rows){
            $view = '<img class="rounded image_padding img-fluid" src="'.EF::getFile($rows->dp).'" width="20%" alt="Customer Image"> &nbsp;&nbsp;&nbsp;'.$rows->name;
              return $view;
           })

           ->addColumn('created_at', function($rows){
              return EF::dateFormat($rows->created_at);
           })
           ->addColumn('email', function($rows){
              return EF::filterEmail($rows->email);
           })
           ->addColumn('branch', function($rows){
              return $rows->branch->name;
           })
          ->addColumn('action', function($rows){
            $branch_curr = $rows->branch;

            $pass_data = array(
              'user_id'      			   => Crypt::encrypt($rows->id),
              'full_name'        	   => $rows->name,
              'father_name'          => $rows->fname,
              'dob'                  => str_replace('1970-01-01','',date('Y-m-d',strtotime($rows->dob))),
              'cnic'                 => ($rows->cnic),
              'email'       	       => $rows->email,
              'contact'    	         => $rows->contact,
              'relation'  	         => $rows->relation,
              'gender'               => $rows->gender,
              'nationality'          => $rows->nationality,
              'occupation'           => $rows->occupation,
              'temporary_address'    => $rows->temp_address,
              'permanent_address'    => $rows->per_address,
              'other_contact'        => $rows->other_contact,
              'passport'             => $rows->passport,

              'user_image'           => $rows->dp,
              EF::branchWhiteLabel()['module']               => $branch_curr->code.' '.$branch_curr->name,
            );

              return view('user.actions.user_actions',[
                'rows' => $rows,
                'pass_data' => $pass_data
              ]);
              
          })

           ->rawColumns(['created_at','count','action','branch','name','email'])

           ->make(true);

      }
      catch(DecryptException $e)
      {

      }
    }

    public function viewAllCustomers()
    {
        $user = new User;

        $branch = new BranchController;

        $branch_list = $branch->getBranchList();

        $user_list = $user->getUserListByType(['Customer']);

        return view('user.manage_customer',['user_list' => $user_list,'branch' => $branch_list]);
    }

    public function getEmployeeAssets($id)
    {

      try
      {

        $employee_id = decrypt($id);


        $contract = new Contract;


        $contract_detail = new ContractDetail;


        $curr_contract = $contract->getContractByUser($employee_id);

        if(isset($curr_contract->id))
        {
          $contract_id = $curr_contract->id;

          $user = $curr_contract->user;



          $curr_contract_assets = $contract_detail->getContractAssets($contract_id);

           return view('user.manage_employee_asset',
          [
            'employee_assets'        => $curr_contract_assets,
            'employee'               => $user,


          ]);
        }
        else
        {
            parent::errorMessage('You cannot view assets without creating employee contract');
        }

      }
      catch(DecryptException $e)
      {

      }
      return redirect()->back();

    }

    public function viewAllEmployees()
    {
        $user = new User;

        $department = new Department;
        $designation = new Designation;

        $branch = new BranchController;

        $branch_list = $branch->getBranchList();

        $department_list = $department->getDepartmentList();

        $user_list = $user->getUserListByType(['Employee','Administrator','Super Admin']);

        $designation_list = $designation->getDesignationList();


        return view('user.manage_employee',
          [
            'user_list'        => $user_list,
            'branch'           => $branch_list,
            'department_list'  => $department_list,
            'user'             => $user,
            'designation_list' => $designation_list

          ]);
    }

    public function viewAllSuppliers()
    {
              $user = new User;
              $vendor_type = new VendorType;


        $user_list = $user->getUserListByType(['Supplier']);
        $user_list_contractor = $user->getUserListByType(['Contractor']);
         $vendor_type_list = $vendor_type->getAllVendorType();

        return view('inventory_module.supplier.manage_supplier',
          [
            'user_list'                   => $user_list,
            'user_list_contractor'        => $user_list_contractor,
            'vendor_type_list'            => $vendor_type_list,

          ]);
    }

    public function viewAllDealers()
    {
        $user = new User;

        $branch = new BranchController;

        $branch_list = $branch->getBranchList();

        $user_list = $user->getUserListByType(['Dealer','Vendor','Sub Dealer']);
          return view('user.manage_dealer_vendor',['user_list' => $user_list,'branch' => $branch_list]);
    }


    public function storeCustomer(UserRequest $request)
    {

      $branch_label = EF::branchWhiteLabel();

      $form_collect = $request->input();

      $form_collect['type']                  = "Customer";
      $form_collect['password']              = NULL;
      $form_collect['designation_id']        = 0;
      $form_collect['employee_type']         = NULL;
      // $form_collect[$branch_label['module']] = Crypt::decrypt($form_collect[$branch_label['module']]);
      // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
      $form_collect[$branch_label['module']] = 1;
      $form_collect['user_image']  = $request->user_image;

      $form_collect['salary_mode'] = NULL;
      $form_collect['bank_branch'] = NULL;
      $form_collect['bank_name']   = NULL;
      $form_collect['account_no']  = NULL;
       $form_collect['employee_form'] = NULL;
       $form_collect['blood_group']  = NULL;
        $form_collect['vendor_type'] = 0;




        $user = new User;

        $curr_user = $user->storeUser($form_collect,$branch_label['module']);

        if(isset($curr_user->id))
        {
            parent::setLogMessage('New customer "'.$curr_user->name.'" has been added.');

            parent::successMessage('New customer has been added.',parent::getLogMessage());

            if($request->ajax())
            {
               $data['cnic'] = $curr_user->cnic;
               $data['id']   = Crypt::encrypt($curr_user->id);
               $data['name'] = $curr_user->name;

               parent::clearMessageLog(1);


               return $data;
            }

        }
        else
        {
          parent::errorMessage('Customer already found.');
        }

        return redirect()->back();
    }


    public function storeSupplier(UserRequest $request)
    {

      $branch_label = EF::branchWhiteLabel();

      $form_collect = $request->input();
      $form_collect['type'] = "Supplier";
      $form_collect['password']    = NULL;
      $form_collect['employee_type'] =NULL;
      $form_collect['salary_mode'] =NULL;
      $form_collect['bank_branch'] =NULL;
      $form_collect['bank_name'] =NULL;
      $form_collect['account_no'] =NULL;
      $form_collect['employee_form'] =NULL;
      $form_collect['blood_group'] =NULL;
      $form_collect['designation_id'] = 0;
      $form_collect['vendor_type'] = decrypt($form_collect['vendor_type']);


      // $form_collect[$branch_label['module']] = Crypt::decrypt($form_collect[$branch_label['module']]);
      // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1

      $form_collect[$branch_label['module']] = 1;
      $form_collect['user_image']  = $request->user_image;
      $form_collect['email']       = null;

        $user = new User;

        $curr_user = $user->storeUser($form_collect,$branch_label['module']);

        if(isset($curr_user->id))
        {
            parent::setLogMessage('New supplier "'.$curr_user->name.'" has been added.');

            parent::successMessage('New supplier has been added.',parent::getLogMessage());

            if($request->ajax())
            {
               $data['cnic'] = $curr_user->cnic;
               $data['id']   = Crypt::encrypt($curr_user->id);
               $data['name'] = $curr_user->name;

               parent::clearMessageLog(1);


               return $data;
            }

        }
        else
        {
          parent::errorMessage('Supplier already found.');

        }

        return redirect()->back();
    }

    public function getUserDropDown($type)
   {
       $view = '<option value="'.Crypt::encrypt(0).'">Select User</option>';
       $data = array('view'=> "" , 'type'=> "");


      try
      {
          $type = decrypt($type);
          $user = new User;

           $user_list = $user->getUserListByType([$type]);


           foreach($user_list as $rows)
           {
             $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.ucfirst($rows->name).' '.ucfirst($rows->designation->title).'</option>';
           }
      } catch (DecryptException $e) {
          //
      }
       $data['view'] = $view;
       $data['type'] = $type;
       return ($data);





       return $view;

   }

       public function storeContractor(UserRequest $request)
    {

      $branch_label = EF::branchWhiteLabel();

      $form_collect = $request->input();
      $form_collect['type'] = "Contractor";
      $form_collect['password']    = NULL;
      $form_collect['designation_id'] = 0;
      $form_collect['vendor_type']  = 0;
      $form_collect['employee_type'] =NULL;
      $form_collect['salary_mode'] =NULL;
      $form_collect['bank_branch'] =NULL;
      $form_collect['bank_name'] =NULL;
      $form_collect['account_no'] =NULL;
      $form_collect['employee_form'] =NULL;
      $form_collect['blood_group'] =NULL;

      // $form_collect[$branch_label['module']] = Crypt::decrypt($form_collect[$branch_label['module']]);
      // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1

      $form_collect[$branch_label['module']] = 1;
      $form_collect['user_image']  = $request->user_image;
      $form_collect['email']       = null;

        $user = new User;

        $curr_user = $user->storeUser($form_collect,$branch_label['module']);

        if(isset($curr_user->id))
        {
            parent::setLogMessage('New Contractor "'.$curr_user->name.'" has been added.');

            parent::successMessage('New contractor has been added.',parent::getLogMessage());

            if($request->ajax())
            {
               $data['cnic'] = $curr_user->cnic;
               $data['id']   = Crypt::encrypt($curr_user->id);
               $data['name'] = $curr_user->name;

               parent::clearMessageLog(1);


               return $data;
            }

        }
        else
        {
          parent::errorMessage('Contractor already found.');

        }

        return redirect()->back();
    }



    public function updateCustomer(UserRequest $request)
    {
        try
        {
            $branch_label = EF::branchWhiteLabel();

            $form_collect = $request->input();

            $form_collect['user_id'] = decrypt($form_collect['user_id']);


            // $form_collect[$branch_label['module']]  = Crypt::decrypt($form_collect[$branch_label['module']]);

            // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
            $form_collect[$branch_label['module']] = 1;

            $form_collect['type'] = "Customer";

            $form_collect['password']              = NULL;
            $form_collect['user_image']            = $request->user_image;
            $form_collect['nationality']           = $request->input('nationality');
            $form_collect['occupation']            = $request->input('occupation');
            $form_collect['dob']                   = $request->input('dob');
            $form_collect['designation_id']        = 0;
            $form_collect['employee_type']         = NULL;
            $form_collect['salary_mode']           = NULL;
            $form_collect['bank_branch']           = NULL;
            $form_collect['bank_name']             = NULL;
            $form_collect['account_no']            = NULL;
            $form_collect['employee_form']         = NULL;
            $form_collect['blood_group']           = NULL;
            $form_collect['vendor_type']           = 0;


            $user = new User;

            $curr_user = $user->updateUser($form_collect,$branch_label['module']);

            if(isset($curr_user->id))
            {
                parent::setLogMessage($curr_user->name.' profile has been updated.');
                parent::successMessage('Customer profile has been updated.',parent::getLogMessage());
            }
        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function storeDealer(UserRequest $request)
   {

       $user = new User;
       $collect_form = $request->input();
       $collect_form['relation']                   = 'S/O';
       $collect_form['password']                   = NULL;
       $collect_form['nationality']                = NULL;
       $collect_form['occupation']                 = NULL;
       $collect_form['dob']                        = NULL;
       $collect_form['temporary_address']          = NULL;
       $collect_form['permanent_address']          = NULL;
       $collect_form['user_image']                 = NULL;
       $collect_form['passport']                   = NULL;
       $collect_form['other_contact']              = NULL;
       $collect_form['designation_id']             = 0;
       $collect_form['employee_type']              = NULL;
       $collect_form['salary_mode']                = NULL;
       $collect_form['bank_branch']                = NULL;
       $collect_form['bank_name']                  = NULL;
       $collect_form['account_no']                 = NULL;
       $collect_form['employee_form']              = NULL;
       $collect_form['blood_group']                = NULL;
       $collect_form['vendor_type']                = 0;
       $collect_form['type']                       = 'Dealer';


       $branch_label = EF::branchWhiteLabel();

       // $collect_form[$branch_label['module']]  = Crypt::decrypt($collect_form[$branch_label['module']]);
       // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
       $collect_form[$branch_label['module']] = 1;


       $curr_user =  $user->storeUser($collect_form,$branch_label['module']);

            if(isset($curr_user->id))
            {
              parent::setLogMessage('New dealer "'.$curr_user->name.'" has been added.');

              parent::successMessage('New dealer has been added.',parent::getLogMessage());

              if($request->ajax())
              {

                 $data['id']   = Crypt::encrypt($curr_user->id);
                 $data['name'] = $curr_user->name;
                 $data['designation'] = $curr_user->designation->title;
                 parent::clearMessageLog(1);

                 return $data;
              }

       }
       else
       {
          parent::errorMessage('Dealer already found.');

       }


       return back();

   }



   public function updateDealer(UserRequest $request)
   {
       try
       {
           $collect_form = $request->input();

           $collect_form['user_id'] = decrypt($collect_form['user_id']);

            $branch_label = EF::branchWhiteLabel();

            // $collect_form[$branch_label['module']]  = Crypt::decrypt($collect_form[$branch_label['module']]);

            // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
            $collect_form[$branch_label['module']] = 1;


           $collect_form['user_image']                 = NULL;
           $collect_form['designation_id']             = 0;
           $collect_form['employee_type']              = NULL;
           $collect_form['salary_mode']                = NULL;
           $collect_form['bank_branch']                = NULL;
           $collect_form['bank_name']                  = NULL;
           $collect_form['account_no']                 = NULL;
           $collect_form['employee_form']              = NULL;
           $collect_form['blood_group']                = NULL;
           $collect_form['passport']                   = NULL;
           $collect_form['other_contact']              = NULL;
           $collect_form['temporary_address']          = NULL;
           $collect_form['permanent_address']          = NULL;
           $collect_form['vendor_type']                = 0;

           $collect_form['type']                       =    'Dealer';


           $user = new User;
// dd($collect_form);
           $curr_user = $user->updateUser($collect_form,$branch_label['module']);

           if(isset($curr_user->id))
           {
              parent::setLogMessage($curr_user->name.' profile has been updated.');

              parent::successMessage('Dealer profile has been updated.',parent::getLogMessage());
           }
       }
       catch (DecryptException $e)
       {

       }

       return back();

   }


    public function removeUser($id)
    {
        return redirect('home');

        parent::errorMessage('User not found.');

        try
        {
            $id = decrypt($id);

            $user = new User;

            if($user->removeUser($id))
            {
                parent::successMessage('User has been removed.');
            }
        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

  public function uploadfile($file,$loaded_image = '/graphics/logo/user.png')
  {
      if((isset($file) && trim(strlen($file)) > 0))
      {
          $file =  \EF::uploadFile($file);

      }
      else
      {
          if(strlen(trim($loaded_image)) > 0)
          {
              $file =  $loaded_image;
          }
          else
          {
             $file = '/graphics/logo/user.png';
          }
      }


      return $file;
  }
    public function storeEmployee(UserRequest $request)
    {

       $user = new User;
       $assigned_department = new AssignDepartment;

       $collect_form = $request->input();




       if($collect_form['salary_mode'] == 'Cash')
       {

        $collect_form['bank_branch'] = NULL;
        $collect_form['bank_name']   = NULL;
        $collect_form['account_no']  = NULL;

       }


       if($request->user_image)
       {
          $collect_form['user_image']  = $request->user_image;

       }
       else
       {
         $collect_form['user_image']            = NULL;

       }


       $collect_form['employee_form'] = $this->uploadfile($request->employee_form);
       $collect_form['relation']              = 'S/O';
       $collect_form['nationality']           = NULL;
       $collect_form['occupation']            = NULL;
       $collect_form['dob']                   = NULL;
       $collect_form['passport']              = NULL;
       $collect_form['other_contact']         = NULL;
       $collect_form['vendor_type']           = 0;
       $collect_form['type']                  = 'Employee';
       $collect_form['designation_id']        = decrypt( $collect_form['designation_id']);
       $collect_form['department']           = decrypt( $collect_form['department']);

      $branch_label = EF::branchWhiteLabel();

       // $collect_form[$branch_label['module']]  = Crypt::decrypt($collect_form[$branch_label['module']]);
      // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
      $collect_form[$branch_label['module']] = 1;



      $curr_user =  $user->storeUser($collect_form,$branch_label['module']);

          if(isset($curr_user->id))
          {
            $department_data['department']  = $collect_form['department'];

            $department_data['user_id']     = $curr_user->id;

            $user_department = $assigned_department->assignDepartment($department_data);



                  parent::setLogMessage('New employee "'.$curr_user->name.'" has been added.');

                  parent::successMessage('New employee has been added.',parent::getLogMessage());




            if($request->ajax())
            {
               $data['id']   = Crypt::encrypt($curr_user->id);
               $data['name'] = $curr_user->name;
               $data['designation'] = str_replace(null, '', $curr_user->designation->title);
               parent::clearMessageLog(1);


               return $data;
            }

       }
       else
       {
          parent::errorMessage('Employee already found.');

       }


       return back();
    }



  public function updateEmployee(UserRequest $request)
   {
       try
       {
          $collect_form = $request->input();


       if($collect_form['salary_mode'] == 'Cash')
       {

        $collect_form['bank_branch'] = NULL;
        $collect_form['bank_name']   = NULL;
        $collect_form['account_no']  = NULL;

       }
          $collect_form['type']                  = 'Employee';
          $collect_form['employee_form'] = $this->uploadfile($request->employee_form);
          $collect_form['user_id']              = decrypt($collect_form['user_id']);
          $collect_form['designation_id']       = decrypt($collect_form['designation_id']);
          $collect_form['department']           = decrypt( $collect_form['department']);
          $collect_form['passport']             = NUlL;
          $collect_form['other_contact']        = NULL;
          $collect_form['vendor_type']          = 0;

        //   if(isset($collect_form['status'])){
        //     // $collect_form['status']           = decrypt( $collect_form['status']);
        //   }

          if($request->user_image)
          {
              $collect_form['user_image']  = $request->user_image;

          }
          else
          {
             $collect_form['user_image']            = NULL;

          }

          // If User has status updated then update it





          $branch_label = EF::branchWhiteLabel();

          // $collect_form[$branch_label['module']]  = Crypt::decrypt($collect_form[$branch_label['module']]);

          // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
          $collect_form[$branch_label['module']] = 1;




           $user                = new User;
           $assigned_department = new AssignDepartment;

//dd($collect_form);
           $curr_user = $user->updateUser($collect_form,$branch_label['module']);

         if(isset($curr_user->id))
          {
            $department_data['department']  = $collect_form['department'];

            $department_data['user_id']     = $curr_user->id;

            $user_department = $assigned_department->assignDepartment($department_data);



              parent::setLogMessage($curr_user->name.' profile has been updated.');

              parent::successMessage('Employee profile has been updated.',parent::getLogMessage());


          }
        }

       catch (DecryptException $e)
       {

       }

       return back();

   }

   public function getUserCnic($cnic)
   {
     $user = new User;

     $user_cnic = $user->getUserByCnic($cnic);

     return ($user_cnic);

   }

       public function updateSupplier(UserRequest $request)
    {
        try
        {
            $branch_label = EF::branchWhiteLabel();

            $form_collect = $request->input();

            $form_collect['user_id'] = decrypt($form_collect['user_id']);
            $form_collect['vendor_type'] = decrypt($form_collect['vendor_type']);
            $form_collect['employee_type'] =NULL;
            $form_collect['salary_mode'] =NULL;
            $form_collect['bank_branch'] =NULL;
            $form_collect['bank_name'] =NULL;
            $form_collect['account_no'] =NULL;
            $form_collect['employee_form'] =NULL;
            $form_collect['blood_group'] =NULL;



            // $form_collect[$branch_label['module']]  = Crypt::decrypt($form_collect[$branch_label['module']]);

            // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
            $form_collect[$branch_label['module']] = 1;

            $form_collect['type']             = "Supplier";
            $form_collect['password']         = NULL;
            $form_collect['user_image']       = $request->user_image;
            $form_collect['designation_id']   = 0;
            $form_collect['email']            = NULL;



            $user = new User;

            $curr_user = $user->updateUser($form_collect,$branch_label['module']);

            if(isset($curr_user->id))
            {
                parent::setLogMessage($curr_user->name.' supplier has been updated.');
                parent::successMessage('Supplier has been updated.',parent::getLogMessage());
            }
        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function updateContractor(UserRequest $request)
    {
        try
        {
            $branch_label = EF::branchWhiteLabel();

            $form_collect = $request->input();

            $form_collect['user_id'] = decrypt($form_collect['user_id']);


            // $form_collect[$branch_label['module']]  = Crypt::decrypt($form_collect[$branch_label['module']]);

            // BY DEFAULT BRANCH ATTACH WITH ALL USER RED SUN ITS ID === 1
            $form_collect[$branch_label['module']] = 1;

            $form_collect['type']             = "Contractor";
            $form_collect['password']         = NULL;
            $form_collect['user_image']       = $request->user_image;
            $form_collect['designation_id']   = 0;
            $form_collect['email']            = NULL;
            $form_collect['vendor_type']      = 0;
            $form_collect['employee_type']    = NULL;
            $form_collect['salary_mode']      = NULL;
            $form_collect['bank_branch']      = NULL;
            $form_collect['bank_name']        = NULL;
            $form_collect['account_no']       = NULL;
            $form_collect['employee_form']    = NULL;
            $form_collect['blood_group']      = NULL;



            $user = new User;

            $curr_user = $user->updateUser($form_collect,$branch_label['module']);

            if(isset($curr_user->id))
            {
                parent::setLogMessage($curr_user->name.' contractor has been updated.');
                parent::successMessage('Contractor has been updated.',parent::getLogMessage());
            }
        }
        catch (DecryptException $e)
        {

        }

        return redirect()->back();
    }

    public function storeVendorType(Request $request)
     {
            $vendor_type         = new VendorType;

            $form_collect = $request->input();

            $check_type = $vendor_type->checkVendorType($form_collect['name']);

              if($check_type == 1)
              {
                parent::errorMessage('Type already exists.');

                if($request->ajax())
                {
                   return ['success' => false];
                }
                else
                {
                  return redirect()->back();
                }

              }

              $curr_type = $vendor_type->storeVendorType($form_collect);

              if(isset($curr_type->id))
              {

              parent::setLogMessage('New supplier/vendor type "'.$curr_type->name.'" has been added.');

              parent::successMessage('New supplier/vendor has been added.',parent::getLogMessage());
               if($request->ajax())
              {

                $all_types = $vendor_type->getAllVendorType();

              $data['status'] = true;

             $data['view'] = '<option value="'.Crypt::encrypt(0).'">Select Type</option>';

             foreach($all_types as $rows)
             {
               $data['view'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.ucfirst($rows->name).'</option>';
             }



                 return $data;
              }
                  }

        return redirect()->back();



     }




     public function getUserByDesi($designation)
    {
        $view = '<option value="">Select User</option>';



       try
       {
           $designation = decrypt($designation);
           $user = User::where('designation_id',$designation)->get();

            foreach($user as $rows)
            {
              $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.ucfirst($rows->name).'|'.ucfirst($rows->designation->title).'</option>';
            }

            return ($view);
       } catch (DecryptException $e) {
           //
       }

        return ($view);


    }

    public function getUserTypesByCnic(string $cnic){
        $user = new User();

        $user_cnic = $user->getUserTypesByCnic($cnic);

        // Get Role Type From Role Model
        $role = new Role;

        $types = $role->getRoleList();
        // End
        //die($types);
        $view = '';
        if (isset($user_cnic->id)) {
            // user found

            $selected_types = $user_cnic->userRoles->whereNotIn('name', ['Super Admin'])->pluck('name')->toArray(); //json_decode($user_cnic->type);
            //dd($selected_types);
            foreach ($types as $type) {

                if (in_array($type, $selected_types)) {
                    $view .= "<option selected value='$type'>$type</option>";
                } else {
                    $view .= "<option value='$type'>$type</option>";
                }
            }

            return ['html' => $view, 'user' => encrypt($user_cnic->id)];
        } else {
            // user not found
            return $view;
        }
    }

    public function storeUserTypes(Request $request){
        // store user types.

        $user = new User;
        // check for user types contained in EF array.
        // User Required
        $form_collect = $request->input();

        //dd($form_collect);

        // Decrypt Values
        $form_collect['user_id'] = decrypt($form_collect['user']);

        $user_curr = $user->storeUserTypes($form_collect);

        if (isset($user_curr->id)) {
            // user with updated types.
            parent::successMessage('User Types has been updated.');
        }

        return back();
    }

    public function createRole(string $role){
        // $user = User::find(1);

        // dd($user->userRoles);


        // $user->assignRole([3,6]);

        $role_obj = new Role;

        $role_obj->findOrCreate($role);

//        $role_obj->save();

        echo "Role of ". $role." is created";
    }

    public function getUserRoleDropDown($role_id)
    {
        $view = '<option value="' . Crypt::encrypt(0) . '">Select User</option>';
        $data = array('view' => "", 'type' => "");

        //dd('Before try');
        try {
            $role_id = decrypt($role_id);
            $role = new Role;

            $role = $role->findById($role_id);
            $user = new User;


            if (isset($role->id)) {

                $user_list = $user->getUserListByType([$role->name]);


                foreach ($user_list as $rows) {
                    $view .= '<option value="' . Crypt::encrypt($rows->id) . '">' . ucfirst($rows->name) . '</option>';
                }


                $data['type'] = $role->name;
            }
            $data['view'] = $view;
        } catch (DecryptException $e) {
            //
        }

        return ($data);

        return $view;
    }
}
