<?php
/**
 * Service Twilio Client (WebRTC)
 * Génération de tokens pour les appels depuis le navigateur
 */

namespace App\Services;

class TwilioClientService
{
    private string $accountSid;
    private string $apiKeySid;
    private string $apiKeySecret;
    private string $twimlAppSid;
    
    public function __construct()
    {
        $this->accountSid = TWILIO_ACCOUNT_SID;
        $this->apiKeySid = TWILIO_API_KEY_SID;
        $this->apiKeySecret = TWILIO_API_KEY_SECRET;
        $this->twimlAppSid = TWILIO_TWIML_APP_SID;
    }
    
    /**
     * Générer un Access Token pour Twilio Client SDK
     */
    public function generateAccessToken(string $identity, int $entrepriseId): string
    {
        // Créer le token JWT manuellement (sans SDK Twilio PHP)
        $ttl = 3600; // 1 heure
        
        $header = [
            'typ' => 'JWT',
            'alg' => 'HS256',
            'cty' => 'twilio-fpa;v=1'
        ];
        
        $now = time();
        
        $payload = [
            'jti' => $this->apiKeySid . '-' . $now,
            'iss' => $this->apiKeySid,
            'sub' => $this->accountSid,
            'exp' => $now + $ttl,
            'grants' => [
                'identity' => $identity,
                'voice' => [
                    'incoming' => [
                        'allow' => true
                    ],
                    'outgoing' => [
                        'application_sid' => $this->twimlAppSid,
                        'params' => [
                            'entreprise_id' => (string)$entrepriseId
                        ]
                    ]
                ]
            ]
        ];
        
        return $this->encodeJwt($header, $payload);
    }
    
    /**
     * Encoder un JWT
     */
    private function encodeJwt(array $header, array $payload): string
    {
        $headerEncoded = $this->base64UrlEncode(json_encode($header));
        $payloadEncoded = $this->base64UrlEncode(json_encode($payload));
        
        $signature = hash_hmac('sha256', "$headerEncoded.$payloadEncoded", $this->apiKeySecret, true);
        $signatureEncoded = $this->base64UrlEncode($signature);
        
        return "$headerEncoded.$payloadEncoded.$signatureEncoded";
    }
    
    /**
     * Base64 URL encode
     */
    private function base64UrlEncode(string $data): string
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
    
    /**
     * Vérifier si WebRTC est configuré
     */
    public function isConfigured(): bool
    {
        return !empty($this->twimlAppSid) 
            && $this->twimlAppSid !== 'APxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
            && !empty($this->apiKeySid)
            && !empty($this->apiKeySecret);
    }
    
    /**
     * Générer une identité unique pour un client
     */
    public function generateClientIdentity(int $entrepriseId, ?int $clientId = null): string
    {
        if ($clientId) {
            return "client_{$entrepriseId}_{$clientId}";
        }
        return "visitor_{$entrepriseId}_" . uniqid();
    }
}
