<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\OtpVerification;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserOtpController extends Controller
{
    public function viewUserOtps($userId)
    {
        $pageTitle = 'User OTP Codes';
        $user = User::findOrFail($userId);
        
        $otps = OtpVerification::where('user_id', $userId)
            ->latest()
            ->paginate(getPaginate());
            
        return view('admin.users.otps', compact('pageTitle', 'user', 'otps'));
    }
    
    public function generateOtp(Request $request, $userId)
    {
        $request->validate([
            'purpose' => 'required|string|max:255'
        ]);
        
        $user = User::findOrFail($userId);
        
        $otpVerification = new OtpVerification();
        $otpVerification->user_id = $user->id;
        $otpVerification->send_via = 'email';
        $otpVerification->otp = verificationCode(6);
        $otpVerification->verifiable_type = '';
        $otpVerification->verifiable_id = 0;
        $otpVerification->expired_at = Carbon::now()->addMinutes(10);
        $otpVerification->additional_data = json_encode([
            'after_verified' => 'user.home',
            'purpose' => $request->purpose,
            'generated_by' => 'admin'
        ]);
        $otpVerification->save();
        
        // Send OTP to user via email
        notify($user, 'OTP_GENERATED', [
            'code' => $otpVerification->otp,
            'purpose' => $request->purpose
        ], ['email']);
        
        $notify[] = ['success', 'OTP generated successfully'];
        $notify[] = ['info', 'Code: <strong>' . $otpVerification->otp . '</strong> | Purpose: ' . $request->purpose . ' | Expires: ' . $otpVerification->expired_at->format('Y-m-d H:i:s')];
        return back()->withNotify($notify);
    }
    
    public function getActiveOtp($userId)
    {
        $activeOtp = OtpVerification::where('user_id', $userId)
            ->whereNull('used_at')
            ->where('expired_at', '>', now())
            ->latest()
            ->first();
            
        if ($activeOtp) {
            return response()->json([
                'success' => true,
                'otp' => $activeOtp->otp,
                'expires_at' => $activeOtp->expired_at->format('Y-m-d H:i:s'),
                'purpose' => json_decode($activeOtp->additional_data)->purpose ?? 'Login'
            ]);
        }
        
        return response()->json([
            'success' => false,
            'message' => 'No active OTP found'
        ]);
    }
}