<?php
/**
 * WhatsApp Messaging Class
 * 
 * Handles sending WhatsApp messages via UltraMsg API.
 */
require_once __DIR__ . '/EnvLoader.php';

class WhatsApp
{
    private $instanceId;
    private $token;
    private $apiUrl;
    private $enabled;

    public function __construct()
    {
        global $crud;
        $this->instanceId = EnvLoader::get('WHATSAPP_INSTANCE_ID', '');
        $this->token = EnvLoader::get('WHATSAPP_TOKEN', '');
        $this->apiUrl = "https://api.ultramsg.com/{$this->instanceId}/messages/chat";

        // Fetch enabled status from DB if crud is available
        if (isset($crud)) {
            $config = $crud->getRecordSet("SELECT whatsapp_enabled FROM config LIMIT 1");
            $this->enabled = !empty($config) ? (bool) $config[0]['whatsapp_enabled'] : false;
        } else {
            $this->enabled = false;
        }
    }

    /**
     * Send a WhatsApp message
     * 
     * @param string $to Phone number (with country code)
     * @param string $message Plain text message
     * @return array [success => bool, message => string]
     */
    public function sendMessage($to, $message)
    {
        // Check if enabled
        if (!$this->enabled) {
            return ['success' => false, 'message' => 'WhatsApp messaging is currently disabled in system settings.'];
        }

        // Basic validation
        if (empty($to)) {
            return ['success' => false, 'message' => 'Recipient phone number is missing.'];
        }

        if (empty($this->instanceId) || empty($this->token)) {
            return ['success' => false, 'message' => 'WhatsApp configuration missing (Instance ID / Token).'];
        }

        $params = [
            'token' => $this->token,
            'to' => $to,
            'body' => $message
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_HTTPHEADER => [
                "content-type: application/x-www-form-urlencoded"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            return ['success' => false, 'message' => "cURL Error: " . $err];
        }

        $resData = json_decode($response, true);
        if (isset($resData['sent']) && $resData['sent'] === 'true') {
            return ['success' => true, 'message' => 'Message sent successfully.'];
        } else {
            // Extract error message from API response if possible
            $errorMsg = 'Unknown error from WhatsApp provider.';
            if (isset($resData['error'])) {
                if (is_array($resData['error'])) {
                    $errorMsg = json_encode($resData['error']);
                } else {
                    $errorMsg = (string) $resData['error'];
                }
            }
            return ['success' => false, 'message' => $errorMsg];
        }
    }
}
