<?php

namespace App\Traits;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Twilio\Rest\Client;


trait EmailHandlerTrait
{
    public function config()
    {
        Config::set('mail.mailers.smtp.transport', 'smtp');
        Config::set('mail.mailers.smtp.host', 'smtp.gmail.com'); // SMTP Host
        Config::set('mail.mailers.smtp.port', 587); // SMTP Port
        Config::set('mail.mailers.smtp.username', 'rokyh459@gmail.com'); // SMTP Username
        Config::set('mail.mailers.smtp.password', 'nppb quhw qhuz pmeo'); // SMTP Password
        Config::set('mail.mailers.smtp.encryption', 'tls'); // Encryption method
        Config::set('mail.from.address', 'rokyh459@gmail.com'); // From email address
        Config::set('mail.from.name', 'Delix'); // From name (optional)
    }

    public function sendResetLinkToEmail($email)
    {
        $this->config();
        $user = User::where('email', $email)->first();
        $token = Password::getRepository()->create($user);
        Mail::send('emails.password_reset', ['token' => $token, 'email' => $email], function ($message) use ($email) {
            $message->to($email)
                ->subject('Password Reset Request');
        });
        return [
            'success' => true,
            'message' => 'Email has been sent.',
        ];
    }

    public function sendOtpRequestToEmail($email)
    {
        $this->config();

        $user = User::where('email', $email);

        if (!$user->first()) {
            return response()->json(['message' => 'User not found.'], 404);
        }

        // Generate a 6-digit numeric OTP
        $otp = rand(100000, 999999);

        // Store OTP temporarily for 5 minutes
        $user->update([
            'token' => $otp,
            'expires_at' => Carbon::now()->addMinutes(5)
        ]);

        // Send email
        $mail = Mail::send('emails.otp', ['otp' => $otp], function ($message) use ($email) {
            $message->to($email)->subject('Your OTP Code');
        });
        if ($mail) {
            return $otp;
        }
        return true;
    }
    public function sendOtpRequestToPhone($phone)
    {
        $otp = rand(100000, 999999);

        try {
            $twilio = new Client(
                config('services.twilio.sid'),
                config('services.twilio.token')
            );

            $user = User::where('phone', $phone)->first();

            if (!$user) {
                $user = User::create([
                    'phone' => $phone,
                    'token' => $otp,
                    'expires_at' => Carbon::now()->addMinutes(5),
                    'name' => 'User_' . $otp,
                    'email' => 'phone_' . $phone . '@example.com',
                    'password' => bcrypt(Str::random(10)),
                ]);
            } else {
                // If user exists, just update OTP
                $user->update([
                    'token' => $otp,
                    'expires_at' => Carbon::now()->addMinutes(5)
                ]);
            }

            // Uncomment to enable Twilio message sending
            $response = $twilio->messages->create(
                $phone,
                [
                    'from' => config('services.twilio.phone_number'),
                    'body' => "Your OTP code is: $otp"
                ]
            );
            Log::info("otp sent" . $response);

            return $user;

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            throw $e;
        }
    }
    public function verifyOtp($emailOrPhone, $otp)
    {
        if (filter_var($emailOrPhone, FILTER_VALIDATE_EMAIL)) {
            // Input is an email
            $user = User::where('email', $emailOrPhone)->first();
        } else {
            // Input is a phone number
            $user = User::where('phone', $emailOrPhone)->first();
        }
        if (!$user) {
            return [
                'code' => 400,
                'message' => 'User not found'
            ];
        }
        if (!$user->token) {
            return [
                'code' => 400,
                'message' => 'OTP already used or not generated'
            ];
        }
        if ($user->token != $otp) {
            return [
                'code' => 400,
                'message' => 'Invalid OTP'
            ];
        }
        $expiresAt = Carbon::parse($user->updated_at)->addMinutes(5);
        if (Carbon::now()->gt($user->expires_at)) {
            return [
                'code' => 400,
                'message' => 'OTP has expired'
            ];
        }
        $user->update(['token' => null, 'expires_at' => null]);
        return [
            'code' => 200,
            'message' => 'OTP verified successfully',
            'user' => $user
        ];
    }

}
