<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;


class ApiUserController extends Controller
{

    public function profile()
    {      
        $user = auth()->user();       
        $address = UserAddress::whereUserId(authId())->first();
        $data['image'] = fetchImage($user->image);        
        $data['name'] = $user->first_name;        
        $data['shop_name'] = $user->shop_name;                        
        $data['phone'] = $user->phone;                        
        $data['alternate_phone'] = $user->alternate_phone;                        
        $data['gender'] = $user->gender;                        
        $data['image'] = img($user->image);
        $data['pincode'] = $address->pincode ?? '';
        $data['address1'] = $address->house ?? '';
        $data['address2'] = $address->area ?? '';
        $data['landmark'] = $address->landmark ?? '';
        $data['country'] = $address->country ?? '';
        $data['city'] = $address->city ?? '';
        $data['district'] = $address->district ?? '';
        $data['state'] = $address->state ?? '';            
        return response()->json(['status'=>true, 'message'=>'Profile fetched successfully!', 'data' => $data]);
    }
    public function updateProfile(Request $request)
    {
        try{
          // all();
        $rule['name'] = 'required';
        $rule['phone'] = 'required|digits:10|unique:users,email,' . authId();
        $rule['shop_name'] = 'required';
        $rule['alternate_phone'] = 'required|digits:10';
        $rule['pincode'] = 'required|digits:6';
        $rule['address1'] = 'required';
        $rule['city'] = 'required';
        $rule['district'] = 'required';
        $rule['state'] = 'required';
        $rule['landmark'] = 'required';
        $validator = Validator::make($request->all(), $rule);      
        if ($validator->fails()) {            
          return response()->json(array('status'=>'Validator Failed', 'errors' => $validator->getMessageBag()->toArray()));
        }   
        $user = User::find(authId());
        if(request()->image){
          $user->image = saveFileInPublic(request()->image, 'upload/user', $user->image);
        }
        $user->first_name = request()->name;
        $user->shop_name = request()->shop_name;                   
    
        $user->save();
        UserAddress::updateOrCreate(
            [
                'user_id' => authId()
            ],[
            'user_id' => authId(),
            'shop_name' => request()->shop_name,
            'name' => request()->name,
            'email' => request()->email,
            'phone' => request()->phone,
            'pincode' => request()->pincode,
            'address1' => request()->address1,
            'address2' => request()->address2,
            'landmark' => request()->landmark,
            'country' => request()->country,
            'city' => request()->city,
            'district' => request()->district,
            'state' => request()->state,                             
         ]);             
        DB::commit();        
        return response()->json(['status'=>true, 'message'=>'Profile updated successfully!']);
      }catch(\Exception $e){
        DB::rollback();
        return response()->json(['status' => false, 'message' => $e->getMessage()]);
      }           
    }
   public function sendOtp(Request $request){
      $validator = Validator::make($request->all(), [            
        'phone' => 'required|digits:10',
      ]);      
      if ($validator->fails()) {            
        return response()->json(array('status'=>false, 'message' => validationError($validator)));
      }   
      $user = User::where('phone',$request->phone)->first();      
      if(!$user){        
        $user = new User;
        $user->role = 'User';
        $user->phone = $request->phone;
        $user->password = Hash::make(12345678);
        $user->save();
        return response()->json(['status' => true, 'message' => 'Please enter details.', 'new_user' => true]);
      }
      $user->otp = rand(1000, 9999);
      $user->otp_sent_time = date('Y-m-d h:i:s');
      $user->save();            
      return response()->json(['status' => true, 'message' => 'Otp has been sent! this will be valid till next 10 minutes.', 'new_user' => false]);
   }    
   public function verifyOtp(Request $request){
    $validator = Validator::make($request->all(), [
      'otp' => 'required',      
    ]);
    $user = User::whereOtp($request->otp)->first();
    if(!$user){
      return response()->json(['status'=>false, 'message'=>'Invalid otp!']);
    }
    if((strtotime(date('Y-m-d h:i:s')) - strtotime($user->otp_sent_time)) > 600){
      return response()->json(['status'=>false, 'message'=>'Otp expired!']);
    }
    $user->otp = '';
    $user->save();
    return response()->json(['status'=>true, 'message'=>'Otp verified!']);
   }
   public function changePassword(Request $request){
    $validator = Validator::make($request->all(), [
      'email' => 'required',
      'password' => 'required',
      'confirm_password' => 'required'        
    ]);
    if($request->password != $request->confirm_password){
      return response()->json(['status'=>false, 'message'=>'Password confirmation does`nt match!']);
    }
    if($validator->fails()) {
        return response()->json(['status'=>false, 'message'=>'Validation error', 'data' => validationError($validator)]);
    }
    $user = User::whereEmail($request->email)->first();
    if(!$user){
      return response()->json(['status'=>false, 'message'=>'Invalid otp sent!']);
    }
      
    if(!$user->otp){
      return response()->json(['status'=>false, 'message'=>'Invalid otp sent!']);
    }

    $user->password = Hash::make($request->password);
    $user->otp = '';
    $user->otp_sent_time = '';
    $user->save();
    return response()->json(['status'=>true, 'message'=>'Password change successfully!']);
  }
   public function UserChangePassword(Request $request){
    $validator = Validator::make($request->all(), [
      'password' => 'required',
      'confirm_password' => 'required'        
    ]);
    if($request->password != $request->confirm_password){
      return response()->json(['status'=>false, 'message'=>'Password confirmation does`nt match!']);
    }
    if($validator->fails()) {
        return response()->json(['status'=>false, 'message'=>'Validation error', 'data' => validationError($validator)]);
    }
    $user = auth()->guard(guardName())->user();
    $user->password = Hash::make($request->password);
    $user->save();
    return response()->json(['status'=>true, 'message'=>'Password updated successfully!']);
  }
}