<?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\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class LoginWaController extends Controller
{
    protected $memberAuthRepository;

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

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

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

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => __('otp.invalid_phone'),
                'errors' => $validator->errors(),
            ], 422);
        }

        $identity = $request->identity;

        // Find or create user by phone number
        $user = $this->memberAuthRepository->check(['phone' => $identity]);
        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => __('otp.user_not_found'),
            ], 404);
        }

        try {

            // Use MemberAuthRepository to generate OTP
            $otp = $this->memberAuthRepository->waOtp(['phone' => $identity]);

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

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

            return response()->json([
                'success' => false,
                'message' => __('otp.generate_failed'),
            ], 500);
        }
    }

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

    public function verify(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'identity' => 'required|string|min:10|max:15',
            '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
            $result = $this->memberAuthRepository->waOtpConfirm([
                'phone' => $identity,
                'otp' => $otp,
            ]);

            $check = $this->memberAuthRepository->check(['phone' => $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('OTP verification failed: '.$e->getMessage());

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