<?php

namespace App\Http\Controllers;

use App\OtpToken;
use Illuminate\Http\Request;

use Carbon\Carbon;

class OtpController extends Controller
{
    public function createOtp($nokp,Request $request){

        $otp = OtpToken::on('mysql7')->create([
            'nokp' => $nokp,
            'expired' => $request->expired,
            'token' => $request->otptoken,
            'used'=> 0,
            'kodcaw' => $request->kodcaw
        ]);

        return response()->json($otp, 201);
    }

    public function getOtp($nokp){
        $current = Carbon::now();
        $current = new Carbon();

        $otp = OtpToken::on('mysql7')->where([['nokp','=',$nokp],['used','=',0],['expired','>=',$current]])->get();

        return response()->json($otp);
    }

    public function getOtpUsed($nokp){
        $current = Carbon::now();
        $current = new Carbon();

        $otp = OtpToken::on('mysql7')->where([['nokp','=',$nokp],['used','=',1]])->get();

        return response()->json($otp);
    }

    public function checkToken($otp_token){
        $current = Carbon::now();
        $current = new Carbon();

        $otp = OtpToken::on('mysql7')->where([['token','=',$otp_token],['used','=',0],['expired','>=',$current]])->get();

        return response()->json($otp);
    }

    public function usedOTP(Request $request){
        $otp = OtpToken::on('mysql7')->where([['nokp','=',$request->nokp]])->update(array(
            'used'=>1
        ));

        return response()->json($otp,201);
    }
}