<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Language;
use App\User;
use App\Setting;
use App\ProductDescription;
use App\Product;
use App\Page;
use App\Models;
use App\ProductAttribute;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\SettingResource;
use App\Http\Resources\PageResource;
use App\Http\Resources\QuestionResource;
use App\Http\Resources\MemberResource;
use App\Http\Resources\ConsultResource;
use Mail;
use App\Mail\SendMail;

use App\Experience;
use App\ExperienceDescription;
use App\Certification;
use App\CertificationDescription;
use App\Question;
use App\Http\Requests\Api\MemberRegistRequest;
use App\Http\Requests\Api\ConsultRegistRequest;
use App\Http\Requests\Api\LoginRequest;
use App\Http\Requests\Api\ForgetRequest;
use App\Http\Requests\Api\ResetRequest;
use App\Http\Requests\Api\VerifyRequest;
use Illuminate\Http\Exceptions\HttpResponseException;


class AuthController extends Controller
{
    public function login(LoginRequest $request) :JsonResponse
    {
        
     
            $credentials = ['email'=>$request->email,'password'=>$request->password];
           
            
        if (!\Auth::attempt($credentials )) 
        {
        
        if(getCurrentLocale() == 'ar')
        {
            $errors = ['checkinputs'=>'تاكد من البيانات المدخلة'];
            $error =  'في انتظار موافقة الادارة';
            $message = $errors['checkinputs'];
        }
        else
        {
            $errors = ['checkinputs'=>['Check your inputs']];
            $error = 'waiting accept from management';
            $message = $errors['checkinputs'][0];
        }
        
            
            throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
        }
         if(getCurrentLocale() == 'ar')
        {
            
            $error =  'في انتظار موافقة الادارة';
        }
        else
        {
            $error = 'waiting accept from management';
        }
            $user = \Auth::user();
            if($user->active == '0'){
                return response()->json(['message'=>$error,'data'=>[]],400);
            }
            $user->api_token = md5(time().rand(1000,1110));
            $user->save();
            if(!is_null($request->tokenDevice))
                        {
                            
                           
                                $user->update(['device_token'=>$request->tokenDevice]);
                            
                        }  
                        
                        $user->update(['language'=>getCurrentLocale()]);
             if($user->role == 'member'){
                $resource = new MemberResource(\Auth::user());
            }
            else{
                $resource = new ConsultResource(\Auth::user());
            }
            
            
        if($user->status == 'inactive'){
            if(!is_null($request->force_activate)){
                    return response()->json(['message'=>__('web.not_active'),'data'=>''],401);
                }
                if($request->force_activate == 'inactive'){
                   return response()->json(['message'=>__('web.not_active'),'data'=>''],401);
                }
            $user->status = 'active';
            $user->save();
            if($user->role == 'member'){
                $resource = new MemberResource(\Auth::user());
            }
            else{
                $resource = new ConsultResource(\Auth::user());
            }
        return response()->json(['message'=>__('web.actived'),'data'=>['api_token'=>\Auth::user()->api_token,'user'=>$resource]],200);
        }else{
        return response()->json(['message'=>'','data'=>['api_token'=>\Auth::user()->api_token,'user'=>$resource]],200);
        }
    }
    
     public function logout(Request $request) :JsonResponse
    {
        $user = \Auth::user();
        $user->update(['api_token'=>null]);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
        return response()->json(['message'=>$msg,'data'=>''],401);
    }
    
    /**
     * deactivate User.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function deactivate(Request $request) :JsonResponse
    {
        $user = \Auth::user();
        $user->update(['api_token'=>null,'status'=>'inactive']);
        return response()->json(['message'=>__('web.success'),'data'=>''],401);
    }
    public function registmember(MemberRegistRequest $request) :JsonResponse
    {
        if(!is_null($request->photo)){
        $name = time().rand(11111,99999).'.' . explode('/', explode(':', substr($request->photo, 0, strpos($request->photo, ';')))[1])[1];

            \Image::make($request->photo)->save(public_path('uploads/images/').$name);
            $request->merge(['photo'=> '/uploads/images/'.$name]);
        }
        $request->merge(['password'=>bcrypt($request->password)]);
        $user = User::create($request->all());
        // if($request->hasFile('photo')){
        // $user->photo = upload($request->file('photo'));
        // $user->save();
        // }
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
      $user->api_token = md5(time().rand(1000,1110));
      $user->save();
      \Auth::login($user);
        $user = User::with('type')->find(\Auth::user()->id);
        if(!is_null($request->tokenDevice))
                        {
                            
                           
                                $user->update(['device_token'=>$request->tokenDevice]);
                            
                        }  
                        
                        $user->update(['language'=>getCurrentLocale()]);
         return response()->json(['message'=>$msg,'data'=>['api_token'=>$user->api_token,'data'=>new MemberResource($user)]], 200);
         
         
    }
    public function registconsult(ConsultRegistRequest $request) :JsonResponse
    {
         if(!is_null($request->photo)){
        $name = time().rand(11111,99999).'.' . explode('/', explode(':', substr($request->photo, 0, strpos($request->photo, ';')))[1])[1];

            \Image::make($request->photo)->save(public_path('uploads/images/').$name);
            $request->merge(['photo'=> '/uploads/images/'.$name]);
        }
        $request->merge(['password'=>bcrypt($request->password),'active'=>'0','role'=>'consult']);
        if(!is_null($request->gender)){
        if($request->gender == 'male'){
            $request->merge(['gender'=>'1']);
        }
        else{
            $request->merge(['gender'=>'0']);
        }
        }
        $user = User::create($request->all());
        // if($request->hasFile('photo')){
        // $user->photo = upload($request->file('photo'));
        // $user->save();
        // }
        
        if(!is_null($request->experience)){
        foreach ($request->experience as $key=>$row) 
        {
            $name = time().rand(11111,99999).'.' . explode('/', explode(':', substr($row['image'], 0, strpos($row['image'], ';')))[1])[1];

            \Image::make($row['image'])->save(public_path('uploads/images/').$name);
            $data=[
                'user_id'=> $user->id,
                'image'=> '/uploads/images/'.$name,
                    ];
            $experience = Experience::create($data);
            
                foreach (languages() as $lang) 
                    {
                    $data_desc=[
                        'experience_id'=> $experience->id,
                        'language_id'=> $lang->id,
                        'name'=> $row['name_'.$lang->local],
                        
                                ];
                    ExperienceDescription::create($data_desc);
                    }
        }
        }
                if(!is_null($request->certification)){
        foreach ($request->certification as $key=>$row) 
        {
            $name = time().rand(11111,99999).'.' . explode('/', explode(':', substr($row['image'], 0, strpos($row['image'], ';')))[1])[1];

            \Image::make($row['image'])->save(public_path('uploads/images/').$name);
            
            $data=[
                'user_id'=> $user->id,
                'image'=> '/uploads/images/'.$name,
                    ];
            $certification = Certification::create($data);
             
                foreach (languages() as $lang) 
                    {
                    $data_desc=[
                        'certification_id'=> $certification->id,
                        'language_id'=> $lang->id,
                        'name'=> $row['name_'.$lang->local],
                        
                                ];
                    CertificationDescription::create($data_desc);
                    }
                
        
        
        }
                }
        
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'في انتظار موافقة الادارة';
        }
        else
        {
            $msg = 'waiting accept from management';
        }
        
      $user->api_token = md5(time().rand(1000,1110));
      $user->save();
      \Auth::login($user);
        $user = User::with(['country','category','experience','certification'])->find(\Auth::user()->id);
        
        if(!is_null($request->tokenDevice))
                        {
                            
                           
                                $user->update(['device_token'=>$request->tokenDevice]);
                            
                        }  
                        
                        $user->update(['language'=>getCurrentLocale()]);
         
         //return response()->json(['message'=>$msg,'data'=>['api_token'=>$user->api_token,'data'=>new ConsultResource($user)]], 200);
         return response()->json(['message'=>$msg,'data'=>null], 200);
         
         
    }
   public function forgetpassword(ForgetRequest $request) :JsonResponse
    {
        $user = User::where('email',$request->email)->first();
        if(!$user)
        {
            if(getCurrentLocale() == 'ar')
            {
                $msg = 'لا يوجد بريد الكتروني';
            }
            else
            {
                $msg = 'Not Exist';
            }
                return response()->json(['message'=>$msg,'data'=>''],401); 
        }
        
        $code = rand(11111,99999);
        $user->code = $code;
        $user->save();
        Mail::to($user->email)->send(new SendMail($code));
        
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
        return response()->json(['message'=>$msg,'data'=>$code],200);
    }
    
    public function  verify(VerifyRequest $request) 
    {
       
            $user = User::where('email',$request->email)->where('code',$request->code)->first();
        
       
            if(!$user)
            {
                if(getCurrentLocale() == 'ar')
                {
                    $errors = ['code'=>'تاكد من  الكود'];
                    $message = $errors['code'];
                }
                else
                {
                    $errors = ['code'=>['Check Code']];
                    $message = $errors['code'][0];
                }
        
                    
                    throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
            }
        
        
        
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
      
        return response()->json(['message'=>$msg,'data'=>$user->email],200);
        
        
        
    }
    public function resetpassword(ResetRequest $request) :JsonResponse
    {
        $user = User::where('email',$request->email)->first();
        if(!$user){
             if(getCurrentLocale() == 'ar')
            {
                $msg = 'لا يوجد بريد الكتروني';
            }
            else
            {
                $msg = 'Not Exist';
            }
                return response()->json(['message'=>$msg,'data'=>''],401); 
        }
        $user->update(['password'=>bcrypt($request->password),'code'=>null]);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        $user->api_token = md5(time().rand(1000,1110));
      $user->save();
      \Auth::login($user);
        if($user->role == 'member'){
                $resource = new MemberResource(\Auth::user());
            }
            else{
                $resource = new ConsultResource(\Auth::user());
            }
            
        return response()->json(['message'=>'','data'=>['api_token'=>\Auth::user()->api_token,'user'=>$resource]],200);
    }
    
}
