<?php

namespace App\Modules\ThreeCX\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\BaseController;
use App\Modules\ThreeCX\Services\ThreeCXAuthService;
use App\Models\Setting;

/**
 * 3CX OAuth2 Authentication Controller
 * 
 * Handles OAuth2 connection management for admin interface
 */
class ThreeCXAuthController extends BaseController
{
    protected $authService;

    public function __construct(ThreeCXAuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * Test OAuth2 connection
     */
    public function testConnection(Request $request)
    {
        try {
            $result = $this->authService->testConnection();

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

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

    /**
     * Get connection status
     */
    public function getStatus(Request $request)
    {
        try {
            $status = $this->authService->getConnectionStatus();

            return Response::json([
                'success' => true,
                'data' => $status
            ]);

        } catch (\Exception $e) {
            return Response::json([
                'success' => false,
                'message' => 'Failed to get connection status: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Disconnect (revoke tokens)
     */
    public function disconnect(Request $request)
    {
        try {
            $this->authService->disconnect();

            return Response::json([
                'success' => true,
                'message' => '3CX OAuth2 tokens have been revoked successfully'
            ]);

        } catch (\Exception $e) {
            return Response::json([
                'success' => false,
                'message' => 'Failed to disconnect: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Save OAuth2 credentials
     */
    public function saveCredentials(Request $request)
    {
        $request->validate([
            'base_url' => 'required|url',
            'client_id' => 'required|string',
            'client_secret' => 'required|string',
            'default_extension' => 'nullable|string',
            'instance_id' => 'nullable|string',
            'instance_name' => 'nullable|string'
        ]);

        try {
            // Save to database settings
            Setting::set('integrations.threecx.base_url', $request->base_url);
            Setting::set('integrations.threecx.client_id', $request->client_id);
            Setting::set('integrations.threecx.client_secret', $request->client_secret);
            
            if ($request->has('default_extension')) {
                Setting::set('integrations.threecx.default_extension', $request->default_extension);
            }
            
            if ($request->has('instance_id')) {
                Setting::set('integrations.threecx.instance_id', $request->instance_id);
            }
            
            if ($request->has('instance_name')) {
                Setting::set('integrations.threecx.instance_name', $request->instance_name);
            }

            // Clear any existing tokens when credentials change
            $this->authService->disconnect();

            return Response::json([
                'success' => true,
                'message' => 'OAuth2 credentials saved successfully'
            ]);

        } catch (\Exception $e) {
            return Response::json([
                'success' => false,
                'message' => 'Failed to save credentials: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get current configuration (masked)
     */
    public function getConfiguration(Request $request)
    {
        try {
            $config = [
                'base_url' => Setting::get('integrations.threecx.base_url', ''),
                'client_id' => Setting::get('integrations.threecx.client_id', ''),
                'client_secret' => $this->maskSecret(Setting::get('integrations.threecx.client_secret', '')),
                'default_extension' => Setting::get('integrations.threecx.default_extension', ''),
                'instance_id' => Setting::get('integrations.threecx.instance_id', ''),
                'instance_name' => Setting::get('integrations.threecx.instance_name', ''),
                'use_websocket' => Setting::get('integrations.threecx.use_websocket', true),
                'timeout' => Setting::get('integrations.threecx.timeout', 30)
            ];

            return Response::json([
                'success' => true,
                'data' => $config
            ]);

        } catch (\Exception $e) {
            return Response::json([
                'success' => false,
                'message' => 'Failed to get configuration: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Mask sensitive data
     */
    private function maskSecret($secret)
    {
        if (empty($secret)) {
            return '';
        }
        
        $length = strlen($secret);
        if ($length <= 8) {
            return str_repeat('*', $length);
        }
        
        return substr($secret, 0, 4) . str_repeat('*', $length - 8) . substr($secret, -4);
    }
}