<?php

namespace App\Modules\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;

class IntegrationsController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Display the integrations settings page.
     *
     * @return void
     */
    public function index()
    {
        $settings = [
            // SMS Settings
            'sms_enabled' => Setting::get('notifications.sms_enabled', false),
            'twilio_enabled' => Setting::get('integrations.twilio.enabled', false),
            'twilio_sid' => Setting::get('integrations.twilio.account_sid', ''),
            'twilio_token' => Setting::get('integrations.twilio.auth_token', ''),
            'twilio_from' => Setting::get('integrations.twilio.from_number', ''),
            'textmagic_enabled' => Setting::get('integrations.textmagic.enabled', false),
            'textmagic_username' => Setting::get('integrations.textmagic.username', ''),
            'textmagic_api_key' => Setting::get('integrations.textmagic.api_key', ''),
            'sms_completion_message' => Setting::get('notifications.sms_completion_message', ''),
            
            // Phone System Settings (3CX)
            'threecx_enabled' => Setting::get('integrations.threecx.enabled', false),
            'threecx_base_url' => Setting::get('integrations.threecx.base_url', ''),
            'threecx_client_id' => Setting::get('integrations.threecx.client_id', ''),
            'threecx_client_secret' => Setting::get('integrations.threecx.client_secret', ''),
            'threecx_extension' => Setting::get('integrations.threecx.extension', '324'),
            'threecx_recording_path' => Setting::get('integrations.threecx.recording_path', ''),
            
            			// Asterisk integration removed - replaced with 3CX
            
            // Alternative SMS Gateway
            'sms_gateway_enabled' => Setting::get('integrations.sms_gateway.enabled', false),
            'sms_gateway_server' => Setting::get('integrations.sms_gateway.server', ''),
            'sms_gateway_username' => Setting::get('integrations.sms_gateway.username', ''),
            'sms_gateway_password' => Setting::get('integrations.sms_gateway.password', ''),
            
            // Xero Integration
            'xero_enabled' => Setting::get('integrations.xero.enabled', false),
            'xero_client_id' => Setting::get('integrations.xero.client_id', ''),
            'xero_client_secret' => Setting::get('integrations.xero.client_secret', ''),
            'xero_redirect_uri' => Setting::get('integrations.xero.redirect_uri', url('/api/v1/xero/callback')),
            
            // Office 365 Calendar Integration
            'office365_enabled' => Setting::get('integrations.office365.enabled', false),
            'office365_client_id' => Setting::get('integrations.office365.client_id', ''),
            'office365_client_secret' => Setting::get('integrations.office365.client_secret', ''),
            'office365_tenant_id' => Setting::get('integrations.office365.tenant_id', ''),
            'office365_redirect_uri' => Setting::get('integrations.office365.redirect_uri', url('/admin/settings/office365/callback')),
            'office365_selected_calendars' => Setting::get('integrations.office365.selected_calendars', ''),
            
            // KashFlow Integration removed - migrated to Xero
        ];

        $this->layout->content = View::make('admin::settings.integrations.index', compact('settings'));
    }

    /**
     * Update the integration settings.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            // SMS validation
            'sms_enabled' => 'boolean',
            'twilio_enabled' => 'boolean',
            'twilio_sid' => 'nullable|string|max:255',
            'twilio_token' => 'nullable|string|max:255',
            'twilio_from' => 'nullable|string|max:20',
            'textmagic_enabled' => 'boolean',
            'textmagic_username' => 'nullable|string|max:255',
            'textmagic_api_key' => 'nullable|string|max:255',
            'sms_completion_message' => 'nullable|string|max:500',
            
            // Phone system validation (3CX)
            'threecx_enabled' => 'boolean',
            'threecx_base_url' => 'nullable|url|max:255',
            'threecx_client_id' => 'nullable|string|max:255',
            'threecx_client_secret' => 'nullable|string|max:255',
            'threecx_extension' => 'nullable|string|max:10',
            'threecx_recording_path' => 'nullable|string|max:500',
            
            			// Asterisk validation removed - replaced with 3CX
            
            // Alternative SMS Gateway
            'sms_gateway_enabled' => 'boolean',
            'sms_gateway_server' => 'nullable|string|max:255',
            'sms_gateway_username' => 'nullable|string|max:255',
            'sms_gateway_password' => 'nullable|string|max:255',
            
            // Xero Integration
            'xero_enabled' => 'boolean',
            'xero_client_id' => 'nullable|string|max:255',
            'xero_client_secret' => 'nullable|string|max:255',
            'xero_redirect_uri' => 'nullable|url|max:500',
            
            // Office 365 Calendar Integration
            'office365_enabled' => 'boolean',
            'office365_client_id' => 'nullable|string|max:255',
            'office365_client_secret' => 'nullable|string|max:255',
            'office365_tenant_id' => 'nullable|string|max:255',
            'office365_redirect_uri' => 'nullable|url|max:500',
            'office365_selected_calendars' => 'nullable|string',
            
            // KashFlow Integration removed - migrated to Xero
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Update SMS settings
        Setting::set('notifications.sms_enabled', $request->boolean('sms_enabled'));
        Setting::set('integrations.twilio.enabled', $request->boolean('twilio_enabled'));
        Setting::set('integrations.twilio.account_sid', $request->input('twilio_sid', ''));
        Setting::set('integrations.twilio.auth_token', $request->input('twilio_token', ''));
        Setting::set('integrations.twilio.from_number', $request->input('twilio_from', ''));
        Setting::set('integrations.textmagic.enabled', $request->boolean('textmagic_enabled'));
        Setting::set('integrations.textmagic.username', $request->input('textmagic_username', ''));
        Setting::set('integrations.textmagic.api_key', $request->input('textmagic_api_key', ''));
        Setting::set('notifications.sms_completion_message', $request->input('sms_completion_message', ''));

        // Update 3CX phone system settings
        Setting::set('integrations.threecx.enabled', $request->boolean('threecx_enabled'));
        Setting::set('integrations.threecx.base_url', $request->input('threecx_base_url', ''));
        Setting::set('integrations.threecx.client_id', $request->input('threecx_client_id', ''));
        Setting::set('integrations.threecx.client_secret', $request->input('threecx_client_secret', ''));
        Setting::set('integrations.threecx.extension', $request->input('threecx_extension', '324'));
        Setting::set('integrations.threecx.recording_path', $request->input('threecx_recording_path', ''));
        
        // Always enable websocket for 3CX
        Setting::set('integrations.threecx.use_websocket', true);
        
        		// Asterisk settings removed - replaced with 3CX

        // Update alternative SMS gateway settings
        Setting::set('integrations.sms_gateway.enabled', $request->boolean('sms_gateway_enabled'));
        Setting::set('integrations.sms_gateway.server', $request->input('sms_gateway_server', ''));
        Setting::set('integrations.sms_gateway.username', $request->input('sms_gateway_username', ''));
        Setting::set('integrations.sms_gateway.password', $request->input('sms_gateway_password', ''));

        // Update Xero integration settings
        Setting::set('integrations.xero.enabled', $request->boolean('xero_enabled'));
        Setting::set('integrations.xero.client_id', $request->input('xero_client_id', ''));
        Setting::set('integrations.xero.client_secret', $request->input('xero_client_secret', ''));
        Setting::set('integrations.xero.redirect_uri', $request->input('xero_redirect_uri', url('/api/v1/xero/callback')));

        // Update Office 365 Calendar integration settings
        Setting::set('integrations.office365.enabled', $request->boolean('office365_enabled'));
        Setting::set('integrations.office365.client_id', $request->input('office365_client_id', ''));
        Setting::set('integrations.office365.client_secret', $request->input('office365_client_secret', ''));
        Setting::set('integrations.office365.tenant_id', $request->input('office365_tenant_id', ''));
        Setting::set('integrations.office365.redirect_uri', $request->input('office365_redirect_uri', url('/admin/settings/office365/callback')));
        Setting::set('integrations.office365.selected_calendars', $request->input('office365_selected_calendars', ''));

        // Update KashFlow integration settings
        // Removed KashFlow integration settings update

        return redirect()->route('admin.settings.integrations.index')
            ->with('success', 'Integration settings updated successfully!');
    }

    /**
     * Test SMS integration.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function testSMS(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone_number' => 'required|string|max:20',
            'message' => 'required|string|max:160',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 400);
        }

        try {
            // Use the new Twilio service to send test message
            $twilioService = app(\App\Modules\Twilio\Services\TwilioServiceInterface::class);
            $result = $twilioService->testSMS(
                $request->input('phone_number'), 
                $request->input('message')
            );
            
            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Test SMS sent successfully!',
                    'message_sid' => $result['message_sid'] ?? null
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to send test SMS: ' . ($result['error'] ?? 'Unknown error')
                ], 500);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'SMS test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test phone system integration.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function testPhoneSystem(Request $request)
    {
        // Asterisk integration has been removed and replaced with 3CX
        return response()->json([
            'success' => false,
            'message' => 'Asterisk integration has been removed. Please use the 3CX integration instead.',
            'redirect' => '/admin/settings/integrations#threecx'
        ], 410); // 410 Gone - resource no longer available
    }

    /**
     * Test 3CX phone system integration.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function test3CX(Request $request)
    {
        try {
            $threeCXService = app('App\\Modules\\ThreeCX\\Services\\ThreeCXAuthService');
            $result = $threeCXService->testConnection();

            return response()->json([
                'success' => $result['success'],
                'message' => $result['message']
            ], $result['success'] ? 200 : 400);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '3CX test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test 3CX call functionality.
     * Uses the same service as the working task detail page calls.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function test3CXCall(Request $request)
    {
        Log::info('[3CX] Integration test call started', [
            'from_extension' => $request->input('from_extension'),
            'to_number' => $request->input('to_number'),
            'user_id' => auth()->id(),
            'user_email' => auth()->user()->email ?? 'unknown'
        ]);

        $validator = Validator::make($request->all(), [
            'from_extension' => 'required|string|max:20',
            'to_number' => 'required|string|max:20',
        ]);

        if ($validator->fails()) {
            Log::warning('[3CX] Integration test validation failed', [
                'errors' => $validator->errors()->toArray(),
                'input' => $request->all()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            // Simplified: call via integration service only
            $integrationService = app(\App\Modules\ThreeCX\Services\ThreeCXIntegrationService::class);
            $result = $integrationService->makeCall($request->input('to_number'), ['timeout' => 10]);

            Log::info('[3CX] Integration test call result', [
                'success' => $result['success'],
                'result' => $result
            ]);

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => $result['message'] ?? 'Test call initiated successfully! Same functionality as task detail page.',
                    'call_status' => $result['call_status'] ?? 'initiated',
                    'data' => $result['data'] ?? null
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => $result['error'] ?? 'Failed to initiate test call',
                    'suggestion' => $result['suggestion'] ?? null,
                    'data' => null
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('[3CX] Integration test call exception', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '3CX call test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get integration status.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function status()
    {
        $status = [
            'sms' => [
                'enabled' => Setting::get('notifications.sms_enabled', false),
                'twilio_configured' => !empty(Setting::get('integrations.twilio.account_sid', '')),
                'gateway_configured' => !empty(Setting::get('integrations.sms_gateway.server', '')),
            ],
            'phone_system' => [
                'enabled' => Setting::get('integrations.threecx.enabled', false),
                'server_configured' => !empty(Setting::get('integrations.threecx.base_url', '')),
                'credentials_configured' => !empty(Setting::get('integrations.threecx.client_id', '')) && !empty(Setting::get('integrations.threecx.client_secret', '')),
                'oauth2_configured' => !empty(Setting::get('integrations.threecx.client_id', '')) && !empty(Setting::get('integrations.threecx.client_secret', '')),
                // 'asterisk_legacy' removed - replaced with 3CX integration
            ],
            'xero' => [
                'enabled' => Setting::get('integrations.xero.enabled', false),
                'credentials_configured' => !empty(Setting::get('integrations.xero.client_id', '')) && !empty(Setting::get('integrations.xero.client_secret', '')),
            ],
            'office365' => [
                'enabled' => Setting::get('integrations.office365.enabled', false),
                'credentials_configured' => !empty(Setting::get('integrations.office365.client_id', '')) && !empty(Setting::get('integrations.office365.client_secret', '')),
            ],
            'kashflow' => [
                'enabled' => false, // KashFlow is removed, so it's always false
                'credentials_configured' => false, // KashFlow is removed, so it's always false
            ]
        ];

        return response()->json($status);
    }
    
    /**
     * Test Xero credentials and connection
     */
    public function testXero(Request $request)
    {
        // Handle Office365 testing via parameter
        if ($request->input('service') === 'office365') {
            return $this->testOffice365($request);
        }
        
        try {
            $clientId = $request->input('client_id') ?: Setting::get('integrations.xero.client_id', '');
            $clientSecret = $request->input('client_secret') ?: Setting::get('integrations.xero.client_secret', '');
            
            if (empty($clientId) || empty($clientSecret)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Client ID and Secret are required'
                ], 400);
            }
            
            // Save the credentials first
            Setting::set('integrations.xero.client_id', $clientId);
            Setting::set('integrations.xero.client_secret', $clientSecret);
            
            // Use the proper Xero service to test connection
            $xeroService = app(\App\Modules\Xero\Services\XeroService::class);
            $authService = app(\App\Modules\Xero\Services\XeroAuthService::class);
            
            // Try to get or create a system token
            try {
                $token = $authService->getValidToken();
                if (!$token) {
                    // Need OAuth authorization
                    return response()->json([
                        'success' => false,
                        'needs_oauth' => true,
                        'auth_url' => $authService->getAuthorizationUrl(),
                        'message' => 'Please complete Xero authorization',
                        'data' => [
                            'client_id_length' => strlen($clientId),
                            'client_secret_length' => strlen($clientSecret),
                            'configured' => true
                        ]
                    ]);
                }
            } catch (\Exception $e) {
                // If token error, redirect to OAuth
                return response()->json([
                    'success' => false,
                    'needs_oauth' => true,
                    'auth_url' => $authService->getAuthorizationUrl(),
                    'message' => 'Please connect to Xero: ' . $e->getMessage(),
                    'data' => [
                        'client_id_length' => strlen($clientId),
                        'client_secret_length' => strlen($clientSecret),
                        'configured' => true
                    ]
                ]);
            }

            // Test the actual connection
            $isConnected = $xeroService->testConnection();
            
            if (!$isConnected) {
                throw new \Exception('Connection test failed. Please check your Xero settings.');
            }

            // Get organization details for verification
            $org = $xeroService->getOrganization();
            
            // Update connection status
            Setting::set('integrations.xero.connected', true);
            Setting::set('integrations.xero.organization', $org['Name'] ?? 'Unknown');
            
            return response()->json([
                'success' => true,
                'message' => 'Xero configuration test successful! Your credentials appear to be valid.',
                'data' => [
                    'client_id_length' => strlen($clientId),
                    'client_secret_length' => strlen($clientSecret),
                    'configured' => true,
                    'connected' => true,
                    'organization' => $org['Name'] ?? 'Unknown'
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('Xero test connection failed: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Test failed: ' . $e->getMessage(),
                'data' => [
                    'configured' => !empty($clientId) && !empty($clientSecret),
                    'connected' => false
                ]
            ], 500);
        }
    }

    /**
     * Test TextMagic credentials and connection
     */
    public function testTextMagic(Request $request)
    {
        try {
            $username = $request->input('textmagic_username') ?: Setting::get('integrations.textmagic.username', '');
            $apiKey = $request->input('textmagic_api_key') ?: Setting::get('integrations.textmagic.api_key', '');

            if (empty($username) || empty($apiKey)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Username and API Key are required'
                ], 400);
            }

            // Save credentials first
            Setting::set('integrations.textmagic.username', $username);
            Setting::set('integrations.textmagic.api_key', $apiKey);

            // Test the credentials
            $textMagicService = new \App\Modules\TextMagic\Services\TextMagicService();
            $result = $textMagicService->testCredentials();

            if ($result['success'] && $result['valid']) {
                return response()->json([
                    'success' => true,
                    'valid' => true,
                    'message' => 'TextMagic credentials are valid!',
                    'account_info' => $result['user_info'] ?? null
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'valid' => false,
                    'message' => 'Invalid credentials: ' . ($result['error'] ?? 'Unknown error')
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('TextMagic test connection failed: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test KashFlow credentials (basic validation)
     */
    public function testKashFlow(Request $request)
    {
        try {
            // KashFlow is removed, so this test will always return false
            return response()->json([
                'success' => false,
                'message' => 'KashFlow integration is no longer available.',
                'data' => [
                    'configured' => false
                ]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get available 3CX extensions for admin selection
     * 
     * @return \Illuminate\Http\JsonResponse
     */
    public function getThreeCXExtensions()
    {
        return response()->json([
            'success' => true,
            'extensions' => []
        ]);
    }

    /**
     * Test 3CX make call - use our working makeCall service
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function testCall(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone_number' => 'required|string|max:20',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Phone number is required',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            Log::info('[3CX Admin Test] Starting test call with diagnostics', [
                'phone_number' => $request->input('phone_number'),
                'user_id' => auth()->id()
            ]);

            // Simplified diagnostics: skip extension probing
            $extensions = [];
            $laravelappStatus = null;

            // Use our working makeCall service
            $integrationService = app(\App\Modules\ThreeCX\Services\ThreeCXIntegrationService::class);
            
            $result = $integrationService->makeCall($request->input('phone_number'), [
                'timeout' => 10 // Short timeout for testing
            ]);

            // Add diagnostic information to response
            if ($result['success']) {
                $extensionWarning = '';
                if ($laravelappStatus === null && count($extensions) === 0) {
                    $extensionWarning = '⚠️ WARNING: No extensions found. The call may not connect properly.';
                } elseif ($laravelappStatus === null) {
                    $extensionWarning = '⚠️ WARNING: laravelapp extension not found. Call may get stuck in Dialing.';
                }
                
                $result['diagnostic_info'] = [
                    'extension_used' => 'laravelapp',
                    'extension_status' => $laravelappStatus ?? 'Extension not found',
                    'extension_warning' => $extensionWarning,
                    'total_extensions' => count($extensions),
                    'note' => $extensionWarning ?: 'Call initiated successfully - extension found and available'
                ];
            }

            Log::info('[3CX Admin Test] Test call completed', [
                'result' => $result
            ]);

            // Log the exact response structure being sent to frontend
            Log::info('[3CX Admin Test] Response structure for frontend', [
                'response_keys' => array_keys($result),
                'has_participant_id' => isset($result['participant_id']),
                'has_call_id' => isset($result['call_id']),
                'has_tracking_started' => isset($result['tracking_started']),
                'success_value' => $result['success'] ?? 'not_set'
            ]);

            return response()->json($result);

        } catch (\Exception $e) {
            Log::error('[3CX Admin Test] Test call failed', [
                'error' => $e->getMessage(),
                'phone_number' => $request->input('phone_number'),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Test call failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get real-time call status for polling
     *
     * @param int $participantId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCallStatus(int $participantId)
    {
        try {
            Log::info('[3CX Admin] Frontend polling request', [
                'participant_id' => $participantId,
                'timestamp' => now()->toISOString()
            ]);
            
            // Get the tracking service to poll fresh status from 3CX API
            $trackingService = app(\App\Modules\ThreeCX\Services\ThreeCXCallTrackingService::class);
            
            // Poll fresh status from 3CX API (this will update the cache)
            $trackingService->pollCallStatusOnce($participantId);
            
            // Now get the updated cached status
            $integrationService = app(\App\Modules\ThreeCX\Services\ThreeCXIntegrationService::class);
            $status = $integrationService->getCallStatus($participantId);

            // CRITICAL: Check for participant migration ALWAYS (same logic as ThreeCXController)
            $cachedInfo = Cache::get("threecx_call_{$participantId}");
            if ($cachedInfo && isset($cachedInfo['migrated_to'])) {
                $newParticipantId = $cachedInfo['migrated_to'];
                Log::info('[3CX Admin Migration] Participant migrated, checking newer status', [
                    'old_participant_id' => $participantId,
                    'new_participant_id' => $newParticipantId,
                    'has_old_status' => !is_null($status)
                ]);

                // Get status for the new participant (this might have more recent status)
                $newStatus = $integrationService->getCallStatus($newParticipantId);
                if ($newStatus) {
                    // Use the newer participant's status
                    $status = $newStatus;
                    $status['participant_id'] = $newParticipantId;
                    $status['original_participant_id'] = $participantId;
                    $status['migrated'] = true;

                    Log::info('[3CX Admin Migration] Using migrated participant status', [
                        'old_participant_id' => $participantId,
                        'new_participant_id' => $newParticipantId,
                        'new_status' => $status['status']
                    ]);

                    return response()->json([
                        'success' => true,
                        'data' => $status,
                        'participant_migrated' => true,
                        'new_participant_id' => $newParticipantId,
                        'message' => 'Call transitioned to new participant (extension answered)'
                    ]);
                } else if (!$status) {
                    // Fallback: if no status for either participant, return migration info
                    Log::warning('[3CX Admin Migration] No status found for either participant', [
                        'old_participant_id' => $participantId,
                        'new_participant_id' => $newParticipantId
                    ]);
                }
            }

            // FALLBACK: If status not found and no migration, check for call transitions (old logic)
            if (!$status) {
                Log::info('[3CX Admin] Status not found - checking for call transitions', [
                    'participant_id' => $participantId
                ]);
                
                // Check if this participant was part of a call that transitioned to a new participant
                $originalCallInfo = Cache::get("threecx_call_{$participantId}");
                Log::info('[3CX Admin] Original call info lookup', [
                    'participant_id' => $participantId,
                    'found_call_info' => !is_null($originalCallInfo),
                    'call_info' => $originalCallInfo
                ]);
                
                if ($originalCallInfo && isset($originalCallInfo['call_id'])) {
                    $callId = $originalCallInfo['call_id'];
                    
                    // Look for the current active participant for this call
                    $currentPrimaryKey = Cache::get("threecx_call_by_id_{$callId}");
                    Log::info('[3CX Admin] Primary key lookup', [
                        'call_id' => $callId,
                        'primary_key' => $currentPrimaryKey
                    ]);
                    
                    if ($currentPrimaryKey) {
                        $currentCallInfo = Cache::get("threecx_call_primary_{$currentPrimaryKey}");
                        Log::info('[3CX Admin] Current call info lookup', [
                            'primary_key' => $currentPrimaryKey,
                            'found_current_call_info' => !is_null($currentCallInfo),
                            'current_call_info' => $currentCallInfo
                        ]);
                        
                        if ($currentCallInfo && $currentCallInfo['participant_id'] != $participantId) {
                            $newParticipantId = $currentCallInfo['participant_id'];
                            
                            Log::info('[3CX Admin] Call transition detected - redirecting to new participant', [
                                'old_participant' => $participantId,
                                'new_participant' => $newParticipantId,
                                'call_id' => $callId
                            ]);
                            
                            // Get status for the new participant
                            $status = $integrationService->getCallStatus($newParticipantId);
                            if ($status) {
                                // Return the new participant data with transition info
                                return response()->json([
                                    'success' => true,
                                    'data' => $status,
                                    'participant_transition' => [
                                        'old_participant_id' => $participantId,
                                        'new_participant_id' => $newParticipantId,
                                        'message' => 'Call transitioned to new participant (extension answered)'
                                    ]
                                ]);
                            }
                        }
                    }
                } else {
                    // Alternative approach: Check active calls for any call with same call ID pattern
                    $activeCalls = Cache::get('threecx_active_calls', []);
                    Log::info('[3CX Admin] Checking active calls for transitions', [
                        'participant_id' => $participantId,
                        'active_calls' => $activeCalls
                    ]);
                    
                    foreach ($activeCalls as $activeParticipantId) {
                        $activeCallInfo = Cache::get("threecx_call_{$activeParticipantId}");
                        if ($activeCallInfo) {
                            Log::info('[3CX Admin] Found active call info', [
                                'active_participant' => $activeParticipantId,
                                'active_call_info' => $activeCallInfo
                            ]);
                            
                            // Check if this could be a transition by looking at timestamps
                            $status = $integrationService->getCallStatus($activeParticipantId);
                            if ($status) {
                                Log::info('[3CX Admin] Alternative transition detected', [
                                    'old_participant' => $participantId,
                                    'new_participant' => $activeParticipantId
                                ]);
                                
                                return response()->json([
                                    'success' => true,
                                    'data' => $status,
                                    'participant_transition' => [
                                        'old_participant_id' => $participantId,
                                        'new_participant_id' => $activeParticipantId,
                                        'message' => 'Call transitioned to new participant (extension answered)'
                                    ]
                                ]);
                            }
                        }
                    }
                }
            }

            Log::info('[3CX Admin] Returning status to frontend', [
                'participant_id' => $participantId,
                'has_status' => !is_null($status),
                'status_data' => $status
            ]);

            if ($status) {
                // Check if call has ended - if so, stop frontend polling
                if (in_array($status['status'] ?? '', ['Ended', 'ended', 'Failed', 'failed', 'Cancelled', 'cancelled'])) {
                    Log::info('[3CX Admin] Call ended detected - admin test calls do not log call history', [
                        'participant_id' => $participantId,
                        'status' => $status['status'],
                        'task_id' => $status['task_id'] ?? null
                    ]);
                    

                    
                    // Clear cache after returning final status
                    $trackingService->clearCallCache($participantId);
                }
                
                return response()->json([
                    'success' => true,
                    'data' => $status
                ]);
            } else {
                // No cached status available - call likely ended or errored
                // Auto-log call history is now handled by ThreeCXController
                
                return response()->json([
                    'success' => false,
                    'message' => 'Call status not available - call may have ended',
                    'data' => null,
                    'call_ended' => true
                ], 404);
            }

        } catch (\Exception $e) {
            Log::error('[3CX Admin] Failed to get call status', [
                'participant_id' => $participantId,
                'error' => $e->getMessage()
            ]);
            
            // Clear cache on errors to prevent stale data
            try {
                $trackingService = app(\App\Modules\ThreeCX\Services\ThreeCXCallTrackingService::class);
                $trackingService->clearCallCache($participantId);
            } catch (\Exception $clearError) {
                // Ignore cache clear errors
            }

            return response()->json([
                'success' => false,
                'message' => 'Failed to get call status: ' . $e->getMessage(),
                'call_ended' => true
            ], 500);
        }
    }
    
    public function hangupCall(Request $request)
    {
        try {
            $participantId = $request->input('participant_id');
            
            if (!$participantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Participant ID is required'
                ], 400);
            }
            
            $integrationService = app(\App\Modules\ThreeCX\Services\ThreeCXIntegrationService::class);
            $result = $integrationService->hangupCall($participantId);
            
            Log::info('[3CX Admin] Hangup call request', [
                'participant_id' => $participantId,
                'result' => $result
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Hangup request sent',
                'result' => $result
            ]);
            
        } catch (\Exception $e) {
            Log::error('[3CX Admin] Failed to hangup call', [
                'participant_id' => $request->input('participant_id'),
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to hangup call: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test Office 365 integration 
     * Route: POST /api/v1/integrations/test-xero?service=office365
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function testOffice365(Request $request = null)
    {
        Log::info('[OFFICE365] Test connection started', [
            'user_id' => Auth::id(),
            'user_email' => Auth::user()->email ?? 'unknown',
            'request_method' => $request ? $request->method() : 'unknown',
            'request_headers' => $request ? $request->headers->all() : [],
            'csrf_token' => $request ? $request->input('_token') : 'not_provided',
            'session_token' => $request && $request->session() ? $request->session()->token() : 'no_session'
        ]);
        
        try {
            // Manually include Office365 classes to avoid autoloader issues - ORDER MATTERS!
            require_once app_path('Modules/Office365/services/Office365ServiceInterface.php');
            require_once app_path('Modules/Office365/models/Office365Token.php');
            require_once app_path('Modules/Office365/services/Office365AuthService.php');
            require_once app_path('Modules/Office365/services/Office365CalendarService.php');
            
            // Check if this is a calendar request
            if ($request && $request->get('action') === 'get_calendars') {
                return $this->handleGetCalendarsRequest($request);
            }
            
            // Instantiate the service
            $office365Service = new \App\Modules\Office365\Services\Office365AuthService();
            $userId = Auth::id();
            
            Log::info('[OFFICE365] Service instantiated, checking authentication', [
                'user_id' => $userId,
                'office365_service_class' => get_class($office365Service)
            ]);
            
            $isAuthenticated = $office365Service->isAuthenticated($userId);
            
            Log::info('[OFFICE365] Authentication check result', [
                'user_id' => $userId,
                'is_authenticated' => $isAuthenticated
            ]);
            
            if (!$isAuthenticated) {
                $authUrl = $office365Service->getAuthorizationUrl();
                Log::info('[OFFICE365] User not authenticated, redirecting to OAuth', [
                    'user_id' => $userId,
                    'auth_url' => $authUrl
                ]);
                
                return response()->json([
                    'success' => false,
                    'message' => 'Redirecting to Microsoft for authorization...',
                    'redirect_url' => $authUrl,
                    'auto_redirect' => true
                ]);
            }

            // Test the connection
            Log::info('[OFFICE365] User authenticated, testing connection', [
                'user_id' => $userId
            ]);
            
            $calendarService = new \App\Modules\Office365\Services\Office365CalendarService($office365Service);
            $testResult = $calendarService->testConnection($userId);

            Log::info('[OFFICE365] Test connection completed', [
                'user_id' => $userId,
                'test_result' => $testResult
            ]);

            return response()->json($testResult);

        } catch (\Exception $e) {
            Log::error('[OFFICE365] Test integration failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
                'exception_type' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Office 365 test failed: ' . $e->getMessage(),
                'debug' => [
                    'error_type' => get_class($e),
                    'line' => $e->getLine(),
                    'file' => basename($e->getFile())
                ]
            ], 500);
        }
    }

    /**
     * Handle Office 365 OAuth callback
     * Route: GET /admin/settings/office365/callback
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function office365Callback(Request $request)
    {
        Log::info('[OFFICE365] OAuth callback received', [
            'url' => $request->fullUrl(),
            'method' => $request->method(),
            'query_params' => $request->query(),
            'code' => $request->get('code') ? 'PRESENT' : 'MISSING',
            'state' => $request->get('state'),
            'error' => $request->get('error'),
            'error_description' => $request->get('error_description'),
            'user_id' => Auth::id(),
            'user_email' => Auth::user()->email ?? 'unknown'
        ]);

        try {
            // Manually include Office365 classes to avoid autoloader issues - ORDER MATTERS!
            require_once app_path('Modules/Office365/services/Office365ServiceInterface.php');
            require_once app_path('Modules/Office365/models/Office365Token.php');
            require_once app_path('Modules/Office365/services/Office365AuthService.php');
            require_once app_path('Modules/Office365/services/Office365CalendarService.php');

            $code = $request->get('code');
            $state = $request->get('state');
            $error = $request->get('error');

            if ($error) {
                Log::error('[OFFICE365] OAuth callback error received from Microsoft', [
                    'error' => $error,
                    'error_description' => $request->get('error_description'),
                    'user_id' => Auth::id()
                ]);
                
                return redirect()->route('admin.settings.integrations.index')
                    ->with('error', 'Office 365 authorization failed: ' . $error);
            }

            if (!$code) {
                Log::error('[OFFICE365] No authorization code received in callback', [
                    'user_id' => Auth::id(),
                    'query_params' => $request->query()
                ]);
                
                return redirect()->route('admin.settings.integrations.index')
                    ->with('error', 'Office 365 authorization code not received');
            }

            Log::info('[OFFICE365] Processing authorization code exchange', [
                'user_id' => Auth::id(),
                'has_code' => !empty($code)
            ]);

            $office365Service = new \App\Modules\Office365\Services\Office365AuthService();
            $result = $office365Service->exchangeCodeForToken($code, Auth::id());
            
            Log::info('[OFFICE365] Token exchange result', [
                'user_id' => Auth::id(),
                'success' => $result ? 'true' : 'false'
            ]);

            if ($result) {
                Log::info('Office365 OAuth callback successful', ['user_id' => Auth::id()]);
                return redirect()->route('admin.settings.integrations.index')
                    ->with('success', 'Office 365 connected successfully! You can now test the connection.')
                    ->with('auto_test_office365', true);
            } else {
                return redirect()->route('admin.settings.integrations.index')
                    ->with('error', 'Failed to exchange authorization code for token');
            }

        } catch (\Exception $e) {
            Log::error('Office365 callback failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
                'trace' => $e->getTraceAsString()
            ]);

            return redirect()->route('admin.settings.integrations.index')
                ->with('error', 'Office 365 connection failed: ' . $e->getMessage());
        }
    }

    /**
     * Handle get calendars request as part of testOffice365
     */
    private function handleGetCalendarsRequest(Request $request)
    {
        $office365Service = new \App\Modules\Office365\Services\Office365AuthService();
        $calendarService = new \App\Modules\Office365\Services\Office365CalendarService($office365Service);
        
        $result = $calendarService->getCalendars(Auth::id());
        
        
        return response()->json($result);
    }

    /**
     * Get Office 365 calendars for the authenticated user
     * Route: GET /api/v1/integrations/office365-calendars
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOffice365Calendars(Request $request)
    {
        try {
            // Manually include Office365 classes to avoid autoloader issues
            require_once app_path('Modules/Office365/services/Office365ServiceInterface.php');
            require_once app_path('Modules/Office365/models/Office365Token.php');
            require_once app_path('Modules/Office365/services/Office365AuthService.php');
            require_once app_path('Modules/Office365/services/Office365CalendarService.php');

            $office365Service = new \App\Modules\Office365\Services\Office365AuthService();
            $calendarService = new \App\Modules\Office365\Services\Office365CalendarService($office365Service);
            
            $result = $calendarService->getCalendars(Auth::id());
            
            return response()->json($result);

        } catch (\Exception $e) {
            Log::error('Office365 get calendars failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch calendars: ' . $e->getMessage()
            ], 500);
        }
    }
} 