<?php
// admin/whatsapp_cloud.php
// إرسال رسائل WhatsApp عبر Meta WhatsApp Cloud API.

require_once __DIR__ . '/settings_store.php';

class WhatsAppCloudSender
{
    private mysqli $conn;
    private string $token;
    private string $phoneNumberId;
    private string $apiVersion;
    private string $countryCode;
    private bool $enabled;

    public function __construct(mysqli $conn, ?array $config = null)
    {
        $this->conn = $conn;
        $cfg = $config ?? setting_get($conn, 'whatsapp_cloud', []);
        if (!is_array($cfg)) $cfg = [];
        $this->enabled = (int)($cfg['enabled'] ?? 0) === 1;
        $this->token = (string)($cfg['access_token'] ?? '');
        $this->phoneNumberId = (string)($cfg['phone_number_id'] ?? '');
        $this->countryCode = preg_replace('/\D+/', '', (string)($cfg['default_country_code'] ?? '963')) ?: '963';
        $version = trim((string)($cfg['api_version'] ?? 'v20.0'));
        $this->apiVersion = preg_match('/^v\d+\.\d+$/', $version) ? $version : 'v20.0';
    }

    public function isConfigured(): bool
    {
        return $this->enabled && $this->token !== '' && $this->phoneNumberId !== '';
    }

    /**
     * إرسال رسالة نصية بسيطة.
     * @param string $to رقم المستقبل بصيغة E.164 مثل: 491234567890
     */
    public function sendText(string $to, string $message): array
    {
        if (!$this->isConfigured()) {
            return ['ok' => false, 'error' => 'إرسال واتساب غير مفعّل أو بيانات Meta Cloud غير مكتملة.'];
        }

        $to = preg_replace('/[^0-9]/', '', $to);
        if (str_starts_with($to, '00')) $to = substr($to, 2);
        if (str_starts_with($to, '0')) $to = $this->countryCode . substr($to, 1);
        if ($to === '') {
            return ['ok' => false, 'error' => 'رقم المستقبل غير صحيح'];
        }

        $url = "https://graph.facebook.com/{$this->apiVersion}/{$this->phoneNumberId}/messages";
        $payload = [
            'messaging_product' => 'whatsapp',
            'to' => $to,
            'type' => 'text',
            'text' => ['preview_url' => false, 'body' => $message],
        ];

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->token,
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            CURLOPT_TIMEOUT => 20,
        ]);

        $resp = curl_exec($ch);
        $errno = curl_errno($ch);
        $err = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($errno) {
            return ['ok' => false, 'error' => "cURL($errno): $err"]; 
        }

        $json = json_decode((string)$resp, true);
        $ok = $code >= 200 && $code < 300;
        if (!$ok) {
            $msg = $json['error']['message'] ?? ($resp ?: 'فشل الإرسال');
            return ['ok' => false, 'http' => $code, 'error' => $msg, 'raw' => $json ?: $resp];
        }

        return ['ok' => true, 'http' => $code, 'data' => $json];
    }
}
