<?php
namespace App\Http\Controllers\BMControllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\bmmodels\CustomerAuth;
use App\Models\bmmodels\CustomerUser;
use App\Models\bmmodels\Customer;
use Auth;
use App\Libs\Mobisky;
use DateTime;
use Hash;
use Exception;
use ErrorException;


class CustomerOtpController extends Controller{
  
    public function index(){
      if(Auth::user()->user_type == 'organization'){
          
           $customer=Auth::user();
           
          ////////////////////////////////////////////////////////////////////
          try{
                  CustomerAuth::where('customer_cust_id',$customer->bulk_cust_id)->where('otp','!=',NULL)->delete();
                 $customers=Customer::where('cust_id',$customer->bulk_cust_id)->get();
                
                 //get username and password for mobisky sms api
                 $mobiskysms=app('App\Http\Controllers\BMControllers\ServiceCredentialController')->mobiskySettings();
                
                     //read the values from the settings after db mapping
                     $sms_username=\Config::get('outpost.sms_username');
                     $sms_password=\Config::get('outpost.sms_password'); 

                         $smsobject=new Mobisky('demo1','mob1d3m01');
 
                         $phn="254".$customer->cust_primary_contact_type;
                        ////////????????????? $phn="254712516957";
                         $otp_code=strtoupper(substr(Hash::make($smsobject->codeGenerator(6)),4,6));
                         $otp=$otp_code."0";
                         $otp_status=0;
                         $otp_created=new DateTime();
                         $customer_user_cust_user_id=$customer->bulk_cust_id;
                        
                        
                        $sms="Verification code: ".$otp;
                        
                        $textstatus='test';
                        $textstatus=$smsobject->sendMessage($phn,$sms);
                       CustomerAuth::create(['otp'=>Hash::make($otp),'sms'=>'hello','otp_status'=>$otp_status,'otp_created'=>$otp_created,'otp_expired'=>now()->addMinute(3),'customer_cust_id'=>$customer_user_cust_user_id]);
                        $id = $customer->bulk_cust_id; 
                        Customer::where('cust_id',$customer->bulk_cust_id)->update(['cust_otp_status' => '0']);
                    
                                
              
                        $data=["status"=>"customersuccess","textstate"=>$textstatus];   

         
         }
        catch(\Exception $e) {
            

            return abort('504', 'Could not connect to the database.  Please check your configuration.'.$e);
            
        }
        
        ///////////////////////////////////////////////////////////////////
        
         
          return view('bmviews.auth.customer-login.customer-otp',compact('customer'));
       
      }
      
    }

    public function customeruserOtp(){
      if(Auth::user()->user_type == 'organization_user')
      {
        //get the phone number
           $customeruser=Auth::user();
           
          ////////////////////////////////////////////////////////////////////
          try{
                CustomerAuth::where('customer_user_cust_user_id',$customeruser->cust_user_id)->where('otp','!=',NULL)->delete();
                 $customers=CustomerUser::where('cust_user_id',$customeruser->cust_user_id)->get();
                
                 //get username and password for mobisky sms api
                 $mobiskysms=app('App\Http\Controllers\BMControllers\ServiceCredentialController')->mobiskySettings();
                
                     //read the values from the settings after db mapping
                     $sms_username=\Config::get('outpost.sms_username');
                     $sms_password=\Config::get('outpost.sms_password'); 

                         $smsobject=new Mobisky('demo1','mob1d3m01');
 
                         $phn="254".$customers[0]->cust_user_contact;
                         ////////????????????? $phn="254712516957";
                         $otp_code=strtoupper(substr(Hash::make($smsobject->codeGenerator(6)),4,6));
                         $otp=$otp_code."0";
                         $otp_status=0;
                         $otp_created=new DateTime();
                         $customer_user_cust_user_id=$customeruser->cust_user_id;
                        
                        
                        $sms="Verification code: ".$otp;
                        
                        $textstatus='test';
                        $textstatus=$smsobject->sendMessage($phn,$sms);
                        CustomerAuth::create(['otp'=>Hash::make($otp),'sms'=>'hello','otp_status'=>$otp_status,'otp_created'=>$otp_created,'otp_expired'=>now()->addMinute(3),'customer_user_cust_user_id'=>$customer_user_cust_user_id]);
                        $id = $customeruser->cust_user_id; 
                        $update= CustomerUser::where('cust_user_id',$id)->update(['cust_otp_status' => '0']);
                    
                        
              
                        $data=["status"=>"customersuccess","textstate"=>$textstatus];   
         
         }
        catch(\Exception $e) {

            return abort('504', 'Could not connect to the database.  Please check your configuration.'.$e);
            
        }
        
         $customer = $customeruser;
          return view('bmviews.auth.customer-user-otp',compact('customer'));
       
      }

    }

     //vue editUser 
     public function verifyUser(Request $request)
     {
       $data="";
       request()->validate([
         'otp' => 'required',        
       ]);
       //check for the code in the customerauths
       $cust_id = $request->cust_id;
       //get the latest code
       if(Auth::user()->user_type == 'organization'){
           //CUST
           $otpdets = CustomerAuth::where('customer_cust_id',Auth::user()->bulk_cust_id)->where('otp_status',0)->first();
           //update the record
          if($otpdets!=null){
              //password verify
              $check = Hash::check($request->otp,$otpdets->otp);
              if($check)
                  {
                   //get the id of the otp record
                   $otpid=$otpdets->cust_auth_id;
                   //call otp generator
                    $code=CustomerOtpController::codeGenerator(7);
                    
                   $otpupdate=CustomerAuth::where('cust_auth_id',$otpid)->update(['otp'=>$code,'otp_status'=>'1','otp_expired'=>Now()]);
                   if($otpupdate){
                       if(Auth::user()->user_type == 'organization'){  
                         $id = Auth::user()->bulk_cust_id; 
                         $customer_update = Customer::find($id);
                         $customer_update->cust_otp_status = 1;
                         $customer_update->save();    
                         
                             $data="cust_success";
                       }
                   } 
                   else{
                        $data="cust_failed";
                       }
                  }
                  else {
                    $data="cust_failed";
                   }
             } 
             else{
                               
                $data="cust_failed";
             }
         }
         //USER
         else if(Auth::user()->user_type == 'organization_user'){
           $uotpdets = CustomerAuth::where('customer_user_cust_user_id',Auth::user()->cust_user_id)->where('otp_status',0)->first();
           
           //update the record
          if($uotpdets!=null){
              //password verify
              $check = Hash::check($request->otp,$uotpdets->otp);
              if($check)
                    {  
                       //get the id of the otp record
                       $otpid=$uotpdets->cust_auth_id;
                       //call otp generator
                        $code=CustomerOtpController::codeGenerator(7);
                       $otpupdate=CustomerAuth::where('cust_auth_id',$otpid)->update(['otp'=>$code,'otp_status'=>'1','otp_expired'=>Now()]);
                       if($otpupdate){
                           
                           if(Auth::user()->user_type == 'organization_user'){    
                            $id = Auth::user()->cust_user_id; 
                            $user_update = CustomerUser::where('cust_user_id',$id)->update(['cust_otp_status' => '1']);                
                            $data="user_success";
                          }
                       } 
                       else{
                                         
                       $data="user_failed";
                     
                       }
                    }
               else{
                                 
               $data="user_failed";
             
               }
             } 
             else{
                                
           $data="user_failed";
           
         }
          
          
         }
         return response()->json($data);
     }

      public function codeRegenerate(){

      $smsobject=new Mobisky('twalisha','twalisha');
      $otp=strtoupper(substr(Hash::make($smsobject->codeGenerator(6)),4,6));
      $otp_status=0;
      $otp_created=new DateTime();
      $sms="Verification code: ".$otp;
      $data['status']="Hallo there";

      if(Auth::user()->user_type == 'organization'){
        $customer_cust_id=Auth::user()->bulk_cust_id;
        $phn="254".Auth::user()->cust_primary_contact_type;

        CustomerAuth::create(['otp'=>$otp,'sms'=>'hello',
        'otp_status'=>$otp_status,'otp_created'=>$otp_created,
        'customer_cust_id'=>$customer_cust_id]);
         $status=$smsobject->sendMessage($phn,$sms);
         $data['status']=$status;
      }
      elseif(Auth::user()->user_type == 'organization_user'){
        $cust_user_id=Auth::user()->cust_user_id;        
        $phn="254".Auth::user()->cust_user_contact;

        CustomerAuth::create(['otp'=>$otp,'sms'=>'hello',
        'otp_status'=>$otp_status,'otp_created'=>$otp_created,
        'customer_user_cust_user_id'=>$cust_user_id]);
        $status=$smsobject->sendMessage($phn,$sms);
        $data['status']=$status;
        
      }
      return response()->json($data);
     
    }
    public function codeGenerator($length)
    {
        $code = '';
        $codes = array_merge(range(0, 9), range('A', 'Z'));

        for ($i = 0; $i < $length; $i++) {
            $code .= $codes[array_rand($codes)];
        }
        return $code;
    }


}