<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\AssignModel;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class UsersController extends Controller
{
  function addData(Request $request){
        
    $validator = Validator::make(request()->all(), [
      'name' => 'required'
]);
    
if ($validator->fails())

  return response (["response"=>400],400);
    else{
      if(!isset($request->phone)&&!isset($request->email)&&!isset($request->password)){
        $response = [
          "response"=>201,
          'status'=>false,
          'message' => "phone or email required"];
          return response($response, 200);
      }
      // else if(!isset($request->phone)){
      //   if(!isset($request->email)||!isset($request->password)){
      //     $response = [
      //       "response"=>201,
      //       'status'=>false,
      //       'message' => "email and password required"];
      //       return response($response, 200);

      //   }
      // }
      if(isset($request->phone))
      {
        $alreadyAddedModel= User::where("phone",$request->phone)->first();
        if($alreadyAddedModel)
        {
          $response = [
            "response"=>201,
            'status'=>false,
            'message' => "phone number already exists"];
            return response($response, 200);
        }
      }
      if(isset($request->email))
      {
        $alreadyAddedModel= User::where("email",$request->email)->first();
        if($alreadyAddedModel)
        {
          $response = [
            "response"=>201,
            'status'=>false,
            'message' => "email id already exists"];
            return response($response, 200);
        }
      }

      if(isset($request->phone)){
        if(!is_numeric($request->phone)){
          $response = [
  "response"=>201,
  'status'=>false,
  'message' => "Please enter valid phone number"];
        return response($response, 200);
        }
      }
              try{
                $timeStamp= date("Y-m-d H:i:s");
                $userModel=new User;
                if(isset($request->phone)){
                  $userModel->phone= $request->phone;
                }
                if(isset($request->email)){
                  $userModel->email= $request->email;
                }
        
            
                if(isset($request->password)){
                  $userModel->password= Hash::Make($request->password);
                }
                else if(!isset($request->password)){
                  $userModel->password= Hash::make(Str::random(8));
                }
                $userModel->name=$request->name;
                $userModel->created_at=$timeStamp;
                $userModel->updated_at=$timeStamp;
                $qResponce= $userModel->save();
          
                   if($qResponce){
                    if(isset($request->role)){
                      $userId = $userModel->id;
                      $dataModelAssign=new AssignModel;
                      $dataModelAssign->user_id  =  $userId;
                      $dataModelAssign->role_id = $request->role;
                      $dataModelAssign->created_at=$timeStamp;
                      $dataModelAssign->updated_at=$timeStamp;
                      $dataModelAssign->save();    
                    }
               
                   if(isset($request->image)){
                    if($request->hasFile('image'))
                    app('App\Http\Controllers\ImageCountController')->uploadImage($request->image, "users",$userId,1,null);
                 //1=profile_image
                  }
                     $response = [
                         "response"=>200,
                         'status'=>true,
                         'message' => "successfully"
               
                     ];
                    }else 
                     $response = [
                       "response"=>201,
                       'status'=>false,
                       'message' => "error",
             
                   ];
                   return response($response, 200);
                           
              }catch(\Exception $e){
          
                $response = [
                  "response"=>201,
                  'status'=>false,
                  'message' => "error",
          
              ];
              return response($response, 200);
              }
            
   }

  }
  function getDataByRole($id)
  {

    $data = DB::table("assign_role")
    ->select(
      'assign_role.*',
      'users.name',
    'users.email',
    'users.phone',
    'users.fcm',
    'users.created_at',
    'users.wallet_amount'
    )
    ->Join('users','users.id','=','assign_role.user_id')
     ->where("assign_role.role_id","=",$id)
      ->get();
      for($i=0;$i<count($data);$i++){

        $data[$i]->role= DB::table("assign_role")
        ->select(
            'assign_role.id',
        'role.id as role_id' ,
        'role.title as role_title'
        )
        ->Join('role','role.id','=','assign_role.role_id')
        ->where('assign_role.user_id', '=',  $data[$i]->user_id)
        ->get();
      }
          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }
  function getDataById($id)
  {

    $data = DB::table("users")
    ->select('users.name',
    'users.email',
    'users.phone',
    'users.fcm',
    'users.created_at',
    'users.wallet_amount'
    )
     ->where("users.id","=",$id)
      ->first();
   

        $data->role= DB::table("assign_role")
        ->select(
            'assign_role.id',
        'role.id as role_id' ,
        'role.title as role_title',
        )
        ->Join('role','role.id','=','assign_role.role_id')
        ->where('assign_role.user_id', '=',  $id)
        ->get();
      
    
          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }
  function getData()
  {
    $data = DB::table("users")
    ->select(
      'users.id','users.email','users.phone',
   'users.name',
   'users.wallet_amount',
    'users.created_at','users.updated_at',
    'images.id as image_id',
    'images.image'   
    )
    ->leftJoin('images', function ($join) {
      $join->on('images.table_id', '=', 'users.id')
      ->where('images.table_name','=','users')
      ->where('images.image_type','=',1);
      })
      ->orderBy('users.created_at', 'ASC')
     ->get();
     for($i=0;$i<count($data);$i++){

      $data[$i]->role= DB::table("assign_role")
      ->select(
          'assign_role.id',
      'role.id as role_id' ,
      'role.title as role_title',
      )
      ->Join('role','role.id','=','assign_role.role_id')
      ->where('assign_role.user_id', '=',  $data[$i]->id)
      ->get();
    }
    
          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }


  function updatePassword(Request $request){
    $initialCheck=false;
    $validator = Validator::make(request()->all(), [
      'user_id'=>'required',
      'password'=>'required'
  ]);
  if ($validator->fails())
  $initialCheck=true;
  
    if ($initialCheck)
        return response (["response"=>400],400);
          else{
           try{
              $timeStamp= date("Y-m-d H:i:s");
              $userDetailsModel= User::where("id",$request->user_id)->first();
  
              $userDetailsModel->password= Hash::Make($request->password);
                 
           $qResponce= $userDetailsModel->save();
          if($qResponce)
            $response = [
                "response"=>200,
                'status'=>true,
                'message' => "successfully",
      
            ];else 
            $response = [
              "response"=>201,
              'status'=>false,
              'message' => "error",
    
          ];
          return response($response, 200);
       
            }
            catch(\Exception $e){
              $response = [
                "response"=>201,
                'status'=>false,
                'message' => "error $e",
            ];
            return response($response, 200);
            }
      
               
          } 
        
    
      }
      function updateDetails(Request $request){
        $initialCheck=false;
        $validator = Validator::make(request()->all(), [
          'id'=>'required'
      ]);
      if ($validator->fails())
      $initialCheck=true;
        if ($initialCheck)
            return response (["response"=>400],400);
              else{
               try{
                  $timeStamp= date("Y-m-d H:i:s");
                  $dataModel= User::where("id",$request->id)->first();
                  if(isset($request->phone))
                 {   $alreadyAddedModel= User::where("phone",$request->phone)->where('id',"!=",$request->id)->first();
            
                    if($alreadyAddedModel)
                    {
                      $response = [
                        "response"=>201,
                        'status'=>false,
                        'message' => "phone number already exists"];
                        return response($response, 200);
                    }}
                  
                  if(isset($request->email))
                  {
                    $alreadyAddedModel= User::where("email",$request->email)->where('id',"!=",$request->id)->first();
                    if($alreadyAddedModel)
                    {
                      $response = [
                        "response"=>201,
                        'status'=>false,
                        'message' => "email id already exists"];
                        return response($response, 200);
                    }
                  }
                  if(isset($request->name ))
                  $dataModel->name = $request->name ;
                  if(isset($request->wallet_amount ))
                  $dataModel->wallet_amount = $request->wallet_amount ;
                  if(isset($request->email ))
                  $dataModel->email = $request->email ;
                  if(isset($request->phone ))
                  $dataModel->phone = $request->phone ;
                  if(isset($request->fcm ))
                  $dataModel->fcm = $request->fcm ;
                  
  
                     $dataModel->updated_at=$timeStamp;
                
               
             $qResponce= $dataModel->save();
       
              if($qResponce)
           {   
      
            // $imageFile=isset($request->image)?$request->image:null;
            // $imageId=isset($request->image_id)?$request->image_id:null;
         
            // app('App\Http\Controllers\ImageCountController')->uploadImage($imageFile, "buses", $userDetailsModel->id,1,$imageId);
            // //1=profile_image  
            
            $response = [
                    "response"=>200,
                    'status'=>true,
                    'message' => "successfully",
          
                ];}
                else 
                $response = [
                  "response"=>201,
                  'status'=>false,
                  'message' => "error",
        
              ];
              return response($response, 200);
            
         
         
            
           
                }
                catch(\Exception $e){
                  $response = [
                    "response"=>201,
                    'status'=>false,
                    'message' => "error $e",
                ];
                return response($response, 200);
                }
          
                   
              } 
              
        
        
          }
          function deleteAssignData(Request $request){
      
            $initialCheck=false;
            $validator = Validator::make(request()->all(), [
              'id'=>'required'
          ]);
          if ($validator->fails())
          $initialCheck=true;
          
            
            if ($initialCheck)
                return response (["response"=>400],400);
                  else{
                   try{
                      $timeStamp= date("Y-m-d H:i:s");
                      $dataModel= AssignModel::where("id",$request->id)->first();
                  
                                   
                 $qResponce= $dataModel->delete();
                  if($qResponce)
                    $response = [
                        "response"=>200,
                        'status'=>true,
                        'message' => "successfully",
              
                    ];else 
                    $response = [
                      "response"=>201,
                      'status'=>false,
                      'message' => "error",
            
                  ];
                  return response($response, 200);
                
                
               
                    }
                    catch(\Exception $e){
                      $response = [
                        "response"=>201,
                        'status'=>false,
                        'message' => "error",
                    ];
                    return response($response, 200);
                    }
              
                       
                  }
               
              
        }
        function addAssignData(Request $request)
        {
            
            $validator = Validator::make(request()->all(), [
              'user_id' => 'required',
              'role_id' => 'required'
        ]);
            
        if ($validator->fails())
          return response (["response"=>400],400);
            else{
            
                   $alreadyExists = AssignModel::where('user_id', '=', $request->user_id)->where('role_id', '=', $request->role_id)->first();
                    if ($alreadyExists === null) {
                      try{
                        $timeStamp= date("Y-m-d H:i:s");
                        $dataModel=new AssignModel;
                        $dataModel->user_id = $request->user_id;
                        $dataModel->role_id = $request->role_id;
                        $dataModel->created_at=$timeStamp;
                        $dataModel->updated_at=$timeStamp;
                        $qResponce= $dataModel->save();
                           if($qResponce){
    
                           $response = [
                                 "response"=>200,
                                 'status'=>true,
                                 'message' => "successfully",
                                 'id' => $dataModel->id
                             ];
                            }else 
                             $response = [
                               "response"=>201,
                               'status'=>false,
                               'message' => "error",
                     
                           ];
                           return response($response, 200);
                                   
                      }catch(\Exception $e){
                  
                        $response = [
                          "response"=>201,
                          'status'=>false,
                          'message' => "error",
                  
                      ];
                      return response($response, 200);
                      }
                    }
                    
                    else {
                      $response = [
                        "response"=>201,
                        'status'=>false,
                        'message' => "Already assigned to same role"];
                        return response($response, 200);
                    }
          
           }
           
          }
   
        
  
}
