<?php
/**
 * Service WhatsApp
 * Gestion des messages WhatsApp via Twilio
 */

namespace App\Services;

class WhatsAppService
{
    private string $accountSid;
    private string $authToken;
    private string $whatsappNumber;
    
    public function __construct()
    {
        $this->accountSid = defined('TWILIO_ACCOUNT_SID') ? TWILIO_ACCOUNT_SID : '';
        $this->authToken = defined('TWILIO_AUTH_TOKEN') ? TWILIO_AUTH_TOKEN : '';
        $this->whatsappNumber = defined('TWILIO_WHATSAPP_NUMBER') ? TWILIO_WHATSAPP_NUMBER : '';
    }
    
    /**
     * Vérifier si WhatsApp est configuré
     */
    public function isConfigured(): bool
    {
        return !empty($this->accountSid) 
            && !empty($this->authToken) 
            && !empty($this->whatsappNumber)
            && $this->whatsappNumber !== '+1234567890';
    }
    
    /**
     * Envoyer un message WhatsApp
     */
    public function sendMessage(string $to, string $message): array
    {
        if (!$this->isConfigured()) {
            return ['success' => false, 'error' => 'WhatsApp non configuré'];
        }
        
        $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->accountSid}/Messages.json";
        
        $data = [
            'From' => 'whatsapp:' . $this->whatsappNumber,
            'To' => 'whatsapp:' . $this->normalizePhone($to),
            'Body' => $message
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERPWD, "{$this->accountSid}:{$this->authToken}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['success' => false, 'error' => $error];
        }
        
        $result = json_decode($response, true);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return [
                'success' => true,
                'message_sid' => $result['sid'] ?? null,
                'status' => $result['status'] ?? 'sent'
            ];
        }
        
        return [
            'success' => false,
            'error' => $result['message'] ?? 'Erreur inconnue',
            'code' => $result['code'] ?? $httpCode
        ];
    }
    
    /**
     * Envoyer un message avec média (image, audio, etc.)
     */
    public function sendMediaMessage(string $to, string $message, string $mediaUrl): array
    {
        if (!$this->isConfigured()) {
            return ['success' => false, 'error' => 'WhatsApp non configuré'];
        }
        
        $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->accountSid}/Messages.json";
        
        $data = [
            'From' => 'whatsapp:' . $this->whatsappNumber,
            'To' => 'whatsapp:' . $this->normalizePhone($to),
            'Body' => $message,
            'MediaUrl' => $mediaUrl
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERPWD, "{$this->accountSid}:{$this->authToken}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return ['success' => true, 'message_sid' => $result['sid'] ?? null];
        }
        
        return ['success' => false, 'error' => $result['message'] ?? 'Erreur'];
    }
    
    /**
     * Normaliser le numéro de téléphone (format E.164)
     */
    public function normalizePhone(string $phone): string
    {
        $phone = preg_replace('/[^0-9+]/', '', $phone);
        
        if (strpos($phone, '+') !== 0) {
            if (strlen($phone) === 8 && preg_match('/^[67]/', $phone)) {
                $phone = '+223' . $phone;
            } elseif (strlen($phone) > 8) {
                $phone = '+' . $phone;
            }
        }
        
        return $phone;
    }
    
    /**
     * Valider une requête Twilio (signature)
     */
    public function validateRequest(string $signature, string $url, array $params): bool
    {
        $data = $url;
        ksort($params);
        foreach ($params as $key => $value) {
            $data .= $key . $value;
        }
        
        $expectedSignature = base64_encode(hash_hmac('sha1', $data, $this->authToken, true));
        
        return hash_equals($expectedSignature, $signature);
    }
    
    /**
     * Parser un message WhatsApp entrant
     */
    public function parseIncomingMessage(array $data): array
    {
        return [
            'from' => str_replace('whatsapp:', '', $data['From'] ?? ''),
            'to' => str_replace('whatsapp:', '', $data['To'] ?? ''),
            'body' => $data['Body'] ?? '',
            'message_sid' => $data['MessageSid'] ?? '',
            'num_media' => (int)($data['NumMedia'] ?? 0),
            'media_url' => $data['MediaUrl0'] ?? null,
            'media_type' => $data['MediaContentType0'] ?? null,
            'profile_name' => $data['ProfileName'] ?? null,
            'wa_id' => $data['WaId'] ?? null,
        ];
    }
}
