<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Repositories\Member\Auth\MemberAuthRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class LoginEmailController extends Controller
{
    protected $memberAuthRepository;

    public function __construct(MemberAuthRepository $memberAuthRepository)
    {
        $this->memberAuthRepository = $memberAuthRepository;
    }

    public function index()
    {
        return view('account.signin',[
            'type'  => 'email',
        ]);
    }

    public function otp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'identity' => 'required|email',
        ]);

  
        $email = $request->identity;

        try {
            // Find user by email
            $user = $this->memberAuthRepository->check(['email' => $email]);
            
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => __('signin.user_not_found'),
                ], 404);
            }

            try {

                // Use MemberAuthRepository to generate OTP
                $otp = $this->memberAuthRepository->emailOtp(['email' => $email]);

                // TODO: Integrate with WhatsApp API to send OTP
                // For now, we'll just log it (remove in production)
                Log::info("OTP for {$email}: {$otp->otp}");

                return response()->json([
                    'success' => true,
                    'message' => __('otp.sent'),
                    'redirect' => route('login-email.otp.view', ['identity' => $email]),
                ]);
            } catch (\Exception $e) {
                Log::error('OTP generation failed: '.$e->getMessage());

                return response()->json([
                    'success' => false,
                    'message' => __('otp.generate_failed'),
                ], 500);
            }
            
        } catch (\Exception $e) {
            Log::error('Email login failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => __('signin.login_failed')
            ], 500);
        }
    }

    public function otpView($identity)
    {
        return view('account.otp', [
            'identity' => $identity,
            'type' => 'email'
        ]);
    }

    public function verify(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'identity' => 'required|email',
            'otp' => 'required|string|size:6',
        ]);

        if ($validator->fails()) {
            return back()
                ->withErrors($validator)
                ->withInput();
        }

        $identity = $request->identity;
        $otp = $request->otp;

        try {
            // Use MemberAuthRepository to verify OTP for email
            $result = $this->memberAuthRepository->emailOtpConfirm([
                'email' => $identity,
                'otp' => $otp,
            ]);

            $check = $this->memberAuthRepository->check(['email' => $identity]);

            $loginData = [
                'fcm_token' => null,
                'device' => 'web',
            ];
            $this->memberAuthRepository->getAuth([
                'user_id' => $check->id,
                'device' => 'web',
            ]);

            

            return redirect()->route('home')->with('success', __('otp.login_success'));

        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()
                ->withErrors(['otp' => $e->getMessage()])
                ->withInput();
        } catch (\Exception $e) {
            Log::error('Email OTP verification failed: '.$e->getMessage());

            return back()
                ->withErrors(['otp' => __('otp.verification_failed')])
                ->withInput();
        }
    }
}
