<?php

namespace App\Libraries;

use Config\WhatsApp;

class WhatsAppService
{
    protected WhatsApp $config;

    public function __construct(?WhatsApp $config = null)
    {
        $this->config = $config ?? config('WhatsApp');
    }

    public function sendText(string $toPhone, string $message): bool
    {
        if (!$this->config->enabled) {
            return false;
        }

        if ($this->config->testMode) {
            $dir = WRITEPATH . 'logs';
            if (!is_dir($dir)) {
                @mkdir($dir, 0775, true);
            }
            $line = date('c') . ' ' . $toPhone . ' ' . $message . PHP_EOL;
            return (bool) file_put_contents($dir . DIRECTORY_SEPARATOR . 'whatsapp_otp.log', $line, FILE_APPEND);
        }

        if ($this->config->provider === 'cloud') {
            $url = 'https://graph.facebook.com/v18.0/' . $this->config->cloudApiPhoneId . '/messages';
            $payload = [
                'messaging_product' => 'whatsapp',
                'to' => $toPhone,
                '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->config->cloudApiToken,
                ],
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_TIMEOUT => 10,
            ]);
            $resp = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return $httpCode >= 200 && $httpCode < 300;
        }

        return false;
    }
}
