<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\WhatsAppService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class AuthController extends Controller
{
    protected $waService;

    public function __construct(WhatsAppService $waService)
    {
        $this->waService = $waService;
    }

    public function showLogin()
    {
        if (Auth::check()) {
            if (Auth::user()->whatsapp_verified_at) {
                return redirect()->route('dashboard');
            }
            return redirect()->route('auth.verify');
        }
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'login' => 'required|string', // can be email or whatsapp
            'password' => 'required|string',
        ]);

        $loginType = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'whatsapp';

        // Format whatsapp to 62 if needed
        $loginValue = $request->login;
        if ($loginType === 'whatsapp' && str_starts_with($loginValue, '0')) {
            $loginValue = '62' . substr($loginValue, 1);
        }

        $user = User::where($loginType, $loginValue)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            Auth::login($user, $request->boolean('remember'));
            
            // Check if verified
            if (!$user->whatsapp_verified_at) {
                // Send verification code
                $otpSent = $this->sendVerificationOtp($user);
                return response()->json([
                    'success' => true,
                    'verified' => false,
                    'message' => $otpSent 
                        ? 'Silakan verifikasi nomor WhatsApp Anda.' 
                        : 'Silakan verifikasi nomor WhatsApp Anda. (Gagal mengirim OTP, silakan periksa koneksi bot WhatsApp Anda).',
                    'redirect' => route('auth.verify')
                ]);
            }

            return response()->json([
                'success' => true,
                'verified' => true,
                'message' => 'Login berhasil!',
                'redirect' => route('dashboard')
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Email/WhatsApp atau password salah.'
        ], 401);
    }

    public function showRegister()
    {
        if (Auth::check()) {
            if (Auth::user()->whatsapp_verified_at) {
                return redirect()->route('dashboard');
            }
            return redirect()->route('auth.verify');
        }
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'whatsapp' => 'required|string|max:20',
            'password' => 'required|string|min:6|confirmed',
        ]);

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

        // Format whatsapp to international prefix if needed
        $whatsapp = $request->whatsapp;
        if (str_starts_with($whatsapp, '0')) {
            $whatsapp = '62' . substr($whatsapp, 1);
        }

        // Check uniqueness again after formatting
        if (User::where('whatsapp', $whatsapp)->exists()) {
            return response()->json([
                'success' => false,
                'errors' => ['whatsapp' => ['Nomor WhatsApp sudah terdaftar.']]
            ], 422);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'whatsapp' => $whatsapp,
            'password' => Hash::make($request->password),
        ]);

        Auth::login($user);

        // Generate and Send OTP
        $otpSent = $this->sendVerificationOtp($user);

        return response()->json([
            'success' => true,
            'message' => $otpSent 
                ? 'Registrasi berhasil. Silakan verifikasi nomor WhatsApp Anda.' 
                : 'Registrasi berhasil, namun gagal mengirim OTP WhatsApp. Silakan periksa koneksi bot Anda dan kirim ulang di halaman verifikasi.',
            'redirect' => route('auth.verify')
        ]);
    }

    public function showVerify()
    {
        $user = Auth::user();
        if (!$user) {
            return redirect()->route('login');
        }
        if ($user->whatsapp_verified_at) {
            return redirect()->route('dashboard');
        }
        return view('auth.verify');
    }

    public function verify(Request $request)
    {
        $request->validate([
            'otp' => 'required|string|size:6',
        ]);

        $user = Auth::user();

        if (!$user) {
            return response()->json(['success' => false, 'message' => 'Sesi habis. Silakan login kembali.'], 401);
        }

        if ($user->whatsapp_verified_at) {
            return response()->json(['success' => true, 'message' => 'WhatsApp Anda sudah terverifikasi.', 'redirect' => route('dashboard')]);
        }

        if ($user->otp_code !== $request->otp) {
            return response()->json(['success' => false, 'message' => 'Kode OTP salah.'], 422);
        }

        if (Carbon::now()->greaterThan($user->otp_expires_at)) {
            return response()->json(['success' => false, 'message' => 'Kode OTP telah kedaluwarsa. Silakan kirim ulang.'], 422);
        }

        // Clear OTP and set verified
        $user->update([
            'whatsapp_verified_at' => Carbon::now(),
            'otp_code' => null,
            'otp_expires_at' => null,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'WhatsApp berhasil diverifikasi!',
            'redirect' => route('dashboard')
        ]);
    }

    public function resendOtp()
    {
        $user = Auth::user();

        if (!$user) {
            return response()->json(['success' => false, 'message' => 'Sesi habis.'], 401);
        }

        $otpSent = $this->sendVerificationOtp($user);

        if (!$otpSent) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengirim OTP. Pastikan server bot WhatsApp Anda aktif dan terhubung.'
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Kode OTP baru telah dikirim ke WhatsApp Anda.'
        ]);
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route('login');
    }

    private function sendVerificationOtp(User $user)
    {
        $otp = sprintf("%06d", mt_rand(0, 999999));
        $user->update([
            'otp_code' => $otp,
            'otp_expires_at' => Carbon::now()->addMinutes(5),
        ]);

        $message = "Halo {$user->name}, kode verifikasi OTP Anda untuk CV Maker adalah: *{$otp}*. Kode ini berlaku selama 5 menit. Jangan bagikan kode ini kepada siapapun.";
        return $this->waService->sendMessage($user->whatsapp, $message);
    }
}
