<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\Product;
use App\Models\User;
use App\Services\EnvatoService;
use App\Services\LicenseAutoRegistrationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class EnvatoController extends Controller
{
    public function verify(Request $request, EnvatoService $envato)
    {
        $data = $request->validate([
            'purchase_code' => ['required','string'],
            'product_slug' => ['required','string'],
        ]);

        $sale = $envato->verifyPurchase($data['purchase_code']);
        if (!$sale) {
            return back()->withErrors(['purchase_code' => 'Could not verify purchase.']);
        }

        $product = Product::where('slug', $data['product_slug'])->firstOrFail();

        $buyerName = data_get($sale, 'buyer');
        $buyerEmail = data_get($sale, 'buyer_email');
        $supportEnd = data_get($sale, 'supported_until');
        $itemId = (string) data_get($sale, 'item.id');

        if ($product->envato_item_id && $product->envato_item_id !== $itemId) {
            return back()->withErrors(['purchase_code' => 'Purchase does not belong to this product.']);
        }

        $user = User::firstOrCreate(
            ['email' => $buyerEmail ?: Str::uuid().'@example.com'],
            ['name' => $buyerName ?: 'Envato Buyer']
        );

        $license = License::updateOrCreate(
            ['purchase_code' => $data['purchase_code']],
            [
                'product_id' => $product->id,
                'user_id' => $user->id,
                'support_expires_at' => $supportEnd ? date('Y-m-d', strtotime($supportEnd)) : null,
                'status' => 'active',
            ]
        );

        return back()->with('success', 'Purchase verified and license updated.');
    }

    public function redirectToEnvato()
    {
        return Socialite::driver('envato')->redirect();
    }

    public function handleEnvatoCallback(EnvatoService $envato)
    {
        $envatoUser = Socialite::driver('envato')->user();

        $username = $envatoUser->getNickname() ?: $envatoUser->getId();

        if (!$username) {
            // No username found in Envato user
            return redirect('/login')->withErrors(['envato' => 'Could not retrieve username from Envato.']);
        }

        // Try to get detailed user info, but don't fail if it doesn't work
        $userInfo = $envato->getOAuthUserInfo($envatoUser->token);

        $userData = [
            'name' => $envatoUser->getName() ?: data_get($userInfo, 'account.firstname', 'Envato User'),
            'password' => Hash::make(Str::random(16)), // Random password since OAuth
            'envato_username' => $envatoUser->getNickname() ?: data_get($userInfo, 'account.username', $username),
            'envato_id' => $envatoUser->getId(),
            'envato_token' => $envatoUser->token,
            'envato_refresh_token' => $envatoUser->refreshToken,
            'email_verified_at' => now(),
        ];

        // Check if we have a real email, if not, we need to handle this differently
        $email = $envatoUser->getEmail();
        if (!$email || str_contains($email, '@envato.temp')) {
            // If we don't have a real email, create a temporary one
            $email = 'temp_' . $username . '@envato.local';
        }

        $user = User::updateOrCreate(
            ['email' => $email],
            $userData
        );

        // Ensure user has proper role (if it's a new user or doesn't have admin role)
        if (!$user->hasRole('admin')) {
            // This is a regular user, no need to assign any specific role
            // The default behavior will work fine
        }

        Auth::login($user, true);

        // Determine redirect route based on user role (same logic as AuthenticatedSessionController)
        $redirectRoute = $user->hasRole('admin') ? route('admin.dashboard', absolute: false) : route('dashboard', absolute: false);

        // If using temporary email, redirect to profile to update email
        // But preserve the intended redirect for after profile update
        if (str_contains($email, '@envato.local')) {
            session(['url.intended' => $redirectRoute]);
            return redirect('/profile')->with('warning', 'Please update your email address in your profile.');
        }

        return redirect()->intended($redirectRoute)->with('success', 'Successfully logged in with Envato!');
    }

    public function linkEnvatoAccount(Request $request, EnvatoService $envato)
    {
        try {
            $envatoUser = Socialite::driver('envato')->user();

            $userInfo = $envato->getOAuthUserInfo($envatoUser->token);

            if (!$userInfo) {
                return back()->withErrors(['envato' => 'Could not retrieve user information from Envato.']);
            }

            auth()->user()->update([
                'envato_username' => $envatoUser->getNickname() ?: data_get($userInfo, 'account.username'),
                'envato_id' => $envatoUser->getId(),
                'envato_token' => $envatoUser->token,
                'envato_refresh_token' => $envatoUser->refreshToken,
            ]);

            return back()->with('success', 'Envato account linked successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['envato' => 'Failed to link Envato account.']);
        }
    }

    public function verifyUserPurchase(Request $request, LicenseAutoRegistrationService $licenseService)
    {
        $request->validate([
            'purchase_code' => 'required|string',
            'product_id' => 'required|exists:products,id',
        ]);

        // Use the license auto-registration service
        $registrationResult = $licenseService->autoRegisterLicense($request->purchase_code, $request->product_id);

        if (!$registrationResult['success']) {
            return response()->json([
                'valid' => false,
                'message' => $registrationResult['message']
            ]);
        }

        $license = $registrationResult['license'];

        return response()->json([
            'valid' => true,
            'message' => $registrationResult['message'],
            'license' => $license
        ]);
    }
}