<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Modules\ThreeCX\Services\ThreeCXIntegrationService;
use App\Modules\ThreeCX\Services\ThreeCXCallMonitorService;
use App\Modules\ThreeCX\Services\ThreeCXMakeCallService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class ThreeCXIntegrationController extends Controller
{
    protected $integrationService;
    protected $monitorService;
    protected $makeCallService;

    public function __construct(
        ThreeCXIntegrationService $integrationService,
        ThreeCXCallMonitorService $monitorService,
        ThreeCXMakeCallService $makeCallService
    ) {
        $this->integrationService = $integrationService;
        $this->monitorService = $monitorService;
        $this->makeCallService = $makeCallService;
    }

    /**
     * Show the 3CX integration dashboard
     */
    public function dashboard()
    {
        $status = $this->integrationService->getStatus();
        $activeCalls = $this->monitorService->getActiveCalls();
        $callHistory = $this->monitorService->getCallHistory(20);

        return view('admin.integrations.threecx.dashboard', compact(
            'status',
            'activeCalls', 
            'callHistory'
        ));
    }

    /**
     * Get real-time call data for AJAX updates
     */
    public function getCallData(): JsonResponse
    {
        $activeCalls = $this->monitorService->getActiveCalls();
        $callHistory = $this->monitorService->getCallHistory(10);

        return response()->json([
            'active_calls' => $activeCalls,
            'call_history' => $callHistory,
            'timestamp' => now()->toISOString()
        ]);
    }

    /**
     * Make a test call
     */
    public function testCall(Request $request): JsonResponse
    {
        $request->validate([
            'phone_number' => 'required|string|min:10'
        ]);

        $phoneNumber = $request->input('phone_number');
        
        $result = $this->integrationService->makeCall($phoneNumber, [
            'timeout' => 10 // Short timeout for testing
        ]);

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

    /**
     * Get integration status
     */
    public function getStatus(): JsonResponse
    {
        $status = $this->integrationService->getStatus();
        
        return response()->json($status);
    }

    /**
     * Test the integration
     */
    public function testIntegration(): JsonResponse
    {
        $result = $this->integrationService->testIntegration();
        
        return response()->json($result);
    }

    /**
     * Get call details by participant ID
     */
    public function getCallDetails(string $participantId): JsonResponse
    {
        $details = $this->makeCallService->getCallStatus($participantId);
        
        return response()->json($details);
    }
}