<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    public function edit(Request $request): View
    {
        return view('admin.profile.edit', ['user' => $request->user()]);
    }

    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();
        $validated = $request->validated();

        // Remove password fields from fillable data (password updates are handled separately)
        unset($validated['current_password'], $validated['password'], $validated['password_confirmation']);

        $user->fill($validated);

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
            $user->save();
            $user->sendEmailVerificationNotification();
            return Redirect::route('verification.notice')
                ->with('success', 'Please verify your email address. A verification link has been sent to your email.');
        }

        $user->save();

        return Redirect::route('admin.profile.edit')->with('success', 'Profile updated successfully.');
    }

    public function updatePassword(Request $request): RedirectResponse
    {
        $request->validate([
            'current_password' => 'required|current_password',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = $request->user();
        $user->password = Hash::make($request->password);
        $user->save();

        return Redirect::route('admin.profile.edit')->with('success', 'Password updated successfully.');
    }

    public function connectEnvato(Request $request): RedirectResponse
    {
        $user = $request->user();
        
        // Get Envato settings from database
        $settings = \App\Models\Setting::first();
        
        if (!$settings || !$settings->envato_personal_token) {
            return Redirect::route('admin.profile.edit')
                ->with('error', 'Envato API is not configured. Please configure it in Settings first.');
        }

        try {
            // Test the API connection and get user info
            $envatoService = app('App\\Services\\EnvatoService');
            $response = \Illuminate\Support\Facades\Http::withToken($settings->envato_personal_token)
                ->acceptJson()
                ->timeout(30)
                ->get('https://api.envato.com/v1/market/private/user/account.json');

            if ($response->successful()) {
                $data = $response->json();
                
                // Update user with Envato info
                $user->envato_username = $data['username'] ?? null;
                $user->envato_id = $data['id'] ?? null;
                $user->save();

                return Redirect::route('admin.profile.edit')
                    ->with('success', 'Successfully connected to Envato account: ' . ($data['username'] ?? 'Unknown'));
            } else {
                return Redirect::route('admin.profile.edit')
                    ->with('error', 'Failed to connect to Envato. Please check your API token.');
            }
        } catch (\Exception $e) {
            return Redirect::route('admin.profile.edit')
                ->with('error', 'Failed to connect to Envato: ' . $e->getMessage());
        }
    }

    public function disconnectEnvato(Request $request): RedirectResponse
    {
        $user = $request->user();
        
        $user->envato_username = null;
        $user->envato_id = null;
        $user->envato_token = null;
        $user->envato_refresh_token = null;
        $user->envato_token_expires_at = null;
        $user->save();

        return Redirect::route('admin.profile.edit')
            ->with('success', 'Successfully disconnected from Envato account.');
    }
}
