<?php
require_once __DIR__ . '/WhatsAppInterface.php';

class BaileysProvider implements WhatsAppInterface {
    private $baseUrl;
    private $apiKey;
    
    public function __construct() {
        $db = db();
        $config = [];
        
        try {
            $stmt = $db->query("SELECT setting_key, setting_value FROM wa_config");
            while ($row = $stmt->fetch()) {
                $config[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Throwable $e) {
            // Fallback
        }
        
        $this->baseUrl = rtrim($config['baileys_url'] ?? 'http://localhost:3000', '/');
        $this->apiKey = $config['baileys_api_key'] ?? '';
    }
    
    public function sendText($phone, $message): array {
        return $this->request('/send/text', [
            'phone' => $this->formatPhone($phone),
            'message' => $message
        ]);
    }
    
    public function sendImage($phone, $imageUrl, $caption = ''): array {
        return $this->request('/send/image', [
            'phone' => $this->formatPhone($phone),
            'image' => $imageUrl,
            'caption' => $caption
        ]);
    }
    
    public function sendDocument($phone, $documentUrl, $filename = ''): array {
        return $this->request('/send/document', [
            'phone' => $this->formatPhone($phone),
            'document' => $documentUrl,
            'filename' => $filename
        ]);
    }
    
    public function checkStatus(): array {
        $result = $this->request('/status', [], 'GET');
        return $result['data'] ?? ['success' => false, 'error' => 'Connection failed'];
    }
    
    public function getQRCode(): ?string {
        $response = $this->request('/qr', [], 'GET');
        if (isset($response['success']) && $response['success'] && isset($response['data']['qr'])) {
            return $response['data']['qr'];
        }
        return null;
    }
    
    public function isConnected(): bool {
        $status = $this->checkStatus();
        return isset($status['connected']) && $status['connected'] === true;
    }
    
    private function formatPhone($phone) {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (substr($phone, 0, 2) === '62') return $phone;
        if (substr($phone, 0, 1) === '0') return '62' . substr($phone, 1);
        return '62' . $phone;
    }
    
    private function request($endpoint, $data, $method = 'POST') {
        if (empty($this->baseUrl)) {
            return [
                'success' => false,
                'error' => 'Baileys URL belum dikonfigurasi',
                'data' => []
            ];
        }
        
        $url = $this->baseUrl . $endpoint;
        $curl = curl_init($url);
        
        $headers = ['Content-Type: application/json'];
        if (!empty($this->apiKey)) {
            $headers[] = 'X-API-Key: ' . $this->apiKey;
        }
        
        if ($method === 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        } else {
            curl_setopt($curl, CURLOPT_HTTPGET, true);
        }
        
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        
        $result = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);
        
        if ($error) {
            return [
                'success' => false,
                'error' => 'Connection error: ' . $error,
                'data' => []
            ];
        }
        
        $decoded = json_decode($result, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [
                'success' => false,
                'error' => 'Invalid JSON response',
                'data' => []
            ];
        }
        
        return [
            'success' => $httpCode === 200 && isset($decoded['success']) && $decoded['success'],
            'data' => $decoded,
            'http_code' => $httpCode
        ];
    }
}