<?php

namespace App\Traits;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;

trait OTPManagement
{
    public function generateOTP($length = 6)
    {
        return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }

    public function storeOTP($memberCode, $otp)
    {
        // First, delete existing OTPs for the member
        DB::table('Luv2_member_otp')->where('member_code', $memberCode)->delete();

        // Store the OTP along with its expiration time
        $expirationTime = now()->addMinutes(5); // OTP expiration time is 5 minutes from now

        DB::table('Luv2_member_otp')->insert([
            'member_code' => $memberCode,
            'otp' => $otp,
            'expired_at' => $expirationTime,
            'created_at' => now(),
        ]);
    }

    public function sendOTPMessage($memberCode, $otp)
    {
        $member = DB::table('Luv2_member')->where('code', $memberCode)->first();
        $phone = $member->phone;
        $nama = $member->name;
        // Send OTP message using a service like Twilio, Nexmo, etc.
        // Below is an example of using Laravel's HTTP client to send OTP via SMS using Twilio
        // Replace placeholders with your Twilio credentials
        $message = 'Halo *' . $nama . '*, 
Ini Kode OTP Kamu : *' . $otp . '*

Jangan berikan kode ini kepada siapapun !' ;
        $fonnte =  Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'GWNoRy#ngyYRD@4!zZnX',
        ])->asForm()->post('https://api.fonnte.com/send', [
            "target" => $phone,
            "type"  => "text",
            "message" => $message,
            "delay" => 3,
        ]);
    }

    public function verifyStoredOTP($memberCode, $otp)
    {
        // Verify the OTP as before
        return DB::table('Luv2_member_otp')
            ->where('member_code', $memberCode)
            ->where('otp', $otp)
            ->where('expired_at', '>', now())
            ->exists();
    }
}
