<?php

namespace App\Http\Controllers;

use App\Models\License;
use App\Models\Product;
use App\Models\User;
use App\Services\EnvatoService;
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.']);
        }

        // Prefer linking to a User by email. If user doesn't exist, create a user record.
        $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
        );

        Auth::login($user, true);

        // If using temporary email, redirect to profile to update email
        if (str_contains($email, '@envato.local')) {
            return redirect('/profile')->with('warning', 'Please update your email address in your profile.');
        }

        return redirect('/dashboard')->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, EnvatoService $envato)
    {
        $request->validate([
            'purchase_code' => 'required|string',
            'product_id' => 'required|exists:products,id',
        ]);

        $sale = $envato->verifyPurchase($request->purchase_code);

        if (!$sale) {
            return response()->json(['valid' => false, 'message' => 'Invalid purchase code']);
        }

        $product = Product::find($request->product_id);
        $itemId = (string) data_get($sale, 'item.id');

        if ($product->envato_item_id && $product->envato_item_id !== $itemId) {
            return response()->json(['valid' => false, 'message' => 'Purchase code does not match this product']);
        }

        // Check if user already has this license
        $existingLicense = License::where('purchase_code', $request->purchase_code)
            ->where('user_id', auth()->id())
            ->first();

        if ($existingLicense) {
            return response()->json(['valid' => true, 'message' => 'License already exists', 'license' => $existingLicense]);
        }

        // Create license for user
        $license = License::create([
            'purchase_code' => $request->purchase_code,
            'product_id' => $product->id,
            'user_id' => auth()->id(),
            'license_type' => 'regular',
            'status' => 'active',
            'support_expires_at' => data_get($sale, 'supported_until') ? date('Y-m-d', strtotime(data_get($sale, 'supported_until'))) : null,
        ]);

        return response()->json(['valid' => true, 'message' => 'License verified and added', 'license' => $license]);
    }
}