<?php

namespace App\Modules\Xero\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Xero\Services\XeroAuthService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Exception;

/**
 * Xero OAuth2 Authentication Controller
 * 
 * Handles the OAuth2 flow for Xero API authentication
 */
class XeroAuthController extends Controller
{
    protected $authService;
    
    public function __construct(XeroAuthService $authService)
    {
        $this->authService = $authService;
    }
    
    /**
     * Redirect to Xero OAuth2 authorization
     */
    public function redirectToProvider(Request $request)
    {
        try {
            $authUrl = $this->authService->getAuthorizationUrl();
            return redirect($authUrl);
        } catch (Exception $e) {
            Log::error('Xero OAuth redirect failed: ' . $e->getMessage());
            
            return redirect()->route('admin.settings.integrations.index')
                ->with('error', 'Failed to initialize Xero authorization: ' . $e->getMessage());
        }
    }
    
    /**
     * Handle OAuth2 callback from Xero
     */
    public function handleCallback(Request $request)
    {
        try {
            $code = $request->get('code');
            $state = $request->get('state');
            $error = $request->get('error');
            
            if ($error) {
                throw new Exception('Xero authorization failed: ' . $error);
            }
            
            if (!$code) {
                throw new Exception('No authorization code received from Xero');
            }
            
            // Exchange code for tokens
            $token = $this->authService->handleCallback($code, $state);
            
            if (!$token) {
                throw new Exception('Failed to obtain access token from Xero');
            }
            
            // Update connection status
            \App\Models\Setting::set('integrations.xero.connected', true);
            
            // Get organization details
            try {
                $xeroService = app(\App\Modules\Xero\Services\XeroService::class);
                $org = $xeroService->getOrganization();
                \App\Models\Setting::set('integrations.xero.organization', $org['Name'] ?? 'Unknown');
            } catch (Exception $e) {
                Log::warning('Failed to get organization details: ' . $e->getMessage());
            }
            
            return redirect()->route('admin.settings.integrations.index')
                ->with('success', 'Xero authorization successful! Your application is now connected to Xero.');
            
        } catch (Exception $e) {
            Log::error('Xero OAuth callback failed: ' . $e->getMessage());
            
            return redirect()->route('admin.settings.integrations.index')
                ->with('error', 'Xero authorization failed: ' . $e->getMessage());
        }
    }
    
    /**
     * Get connection status
     */
    public function getConnectionStatus(Request $request): JsonResponse
    {
        try {
            $token = $this->authService->getValidToken();
            $connected = $token ? true : false;
            
            $status = [
                'connected' => $connected,
                'expires_at' => $token ? $token->expires_at : null,
                'organization' => \App\Models\Setting::get('integrations.xero.organization', ''),
                'tenant_id' => $token ? $token->tenant_id : null
            ];
            
            return response()->json([
                'success' => true,
                'data' => $status
            ]);
            
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'connected' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * Disconnect from Xero
     */
    public function disconnect(Request $request): JsonResponse
    {
        try {
            $this->authService->revokeToken();
            
            // Update connection status
            \App\Models\Setting::set('integrations.xero.connected', false);
            \App\Models\Setting::set('integrations.xero.organization', '');
            
            return response()->json([
                'success' => true,
                'message' => 'Disconnected from Xero successfully'
            ]);
            
        } catch (Exception $e) {
            Log::error('Xero disconnect failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to disconnect: ' . $e->getMessage()
            ], 500);
        }
    }
} 