<?php
namespace App\Controllers\MqttServices;

use App\Controllers\MqttServices\Auth\MqttServiceAuth;
use Models\ServiceAuthenticationsModel;

class MqttServiceAuthenticationsController extends MqttServiceAuth {

    public function actionOtp() {
        
        $objServiceAuthentication = ServiceAuthenticationsModel::createService();

        $arrmixServiceAuthenticationDetails = $objServiceAuthentication->where( ['user_id' => $this->g_arrmixDecryptedTokenDetails['user_id'], 'imei_number' => $this->g_arrmixDecryptedTokenDetails['imei_number'] ] )->first();
        
        $intOtp = generateRandomString( 6, true );
        if( true == isValArr( $arrmixServiceAuthenticationDetails ) ) {
            
            $arrmixUpdateData = [
                'otp'                       => $intOtp,
                'expired_at'                => date( 'Y-m-d H:i:s', strtotime( '+1 days' ) ),
                'service_authentication_id' => $arrmixServiceAuthenticationDetails['service_authentication_id']
            ];

            $objServiceAuthentication->edit( 'service_authentication_id', $arrmixUpdateData );

        } else {
            
            $arrmixInsertData = [
                'otp'             => $intOtp,
                'user_id'         => $this->g_arrmixDecryptedTokenDetails['user_id'],
                'expired_at'      => date( 'Y-m-d H:i:s', strtotime( '+1 days' ) ),
                'imei_number'     => $this->g_arrmixDecryptedTokenDetails['imei_number']
            ];
            
            $objServiceAuthentication->add( $arrmixInsertData );
        }
        
        $arrmixReceivedTopic =  explode( "/", $this->g_strReceivedTopic );

        $arrmixResponseData['is_require_publish'] = true;
        $arrmixResponseData['topic']              = self::MQTT_TOPIC . 'pub/' . $arrmixReceivedTopic[3] . '/otp';
        $arrmixResponseData['message']['otp']     = ( int ) $intOtp;
        
        return $arrmixResponseData;
    }
    
}
