<?php

namespace App\Utils;

use App\Config\Database;
use PDO;

class WhatsAppAlertHelper {
    
    // =========================================================================
    // TWILIO WHATSAPP CONFIGURATION
    // 1. Sign up for a free Twilio account: https://www.twilio.com/
    // 2. Go to the Twilio Console > Messaging > Try it out > Send a WhatsApp message.
    // 3. Connect your device to the Twilio Sandbox.
    // 4. In the application, login as superadmin and configure these keys in Global Settings.
    // =========================================================================

    /**
     * Send a WhatsApp message using Twilio API (via cURL)
     *
     * @param string $toPhone   The recipient's phone number (must include country code, e.g. +94771234567)
     * @param string $message   The message text to send
     * @return bool             True on success
     * @throws \Exception       If the API request fails
     */
    public static function send(string $toPhone, string $message): bool {
        
        $db = Database::getInstance()->getConnection();
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('twilio_sid', 'twilio_token', 'twilio_whatsapp_number')");
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

        $twilioSid = $settings['twilio_sid'] ?? '';
        $twilioToken = $settings['twilio_token'] ?? '';
        $twilioWhatsAppNumber = $settings['twilio_whatsapp_number'] ?? '';

        if (empty($twilioSid) || empty($twilioToken) || empty($twilioWhatsAppNumber)) {
            throw new \Exception("Twilio is not configured. Please ask the superadmin to configure Twilio settings in the Global Settings panel.");
        }

        // Format recipient number for WhatsApp
        $to = "whatsapp:" . preg_replace('/[^0-9+]/', '', $toPhone);
        $from = $twilioWhatsAppNumber;
        
        $url = "https://api.twilio.com/2010-04-01/Accounts/" . $twilioSid . "/Messages.json";
        
        $data = [
            'To' => $to,
            'From' => $from,
            'Body' => $message
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERPWD, $twilioSid . ':' . $twilioToken);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Fixes SSL local issuer error on localhost
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \Exception("cURL Error: " . $error);
        }
        
        curl_close($ch);
        
        $responseData = json_decode($response, true);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return true;
        } else {
            $errorMsg = $responseData['message'] ?? 'Unknown Twilio API error';
            throw new \Exception("Twilio API Error ($httpCode): " . $errorMsg);
        }
    }

    /**
     * Send a WhatsApp message using Twilio Content API
     *
     * @param string $toPhone           The recipient's phone number
     * @param string $contentSid        The Twilio Content SID (e.g. HX...)
     * @param array  $contentVariables  Array of variables to replace in the template
     * @return bool                     True on success
     * @throws \Exception               If the API request fails
     */
    public static function sendTemplate(string $toPhone, array $contentVariables): bool {
        
        $db = Database::getInstance()->getConnection();
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('twilio_sid', 'twilio_token', 'twilio_whatsapp_number', 'twilio_whatsapp_template_sid')");
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

        $twilioSid = $settings['twilio_sid'] ?? '';
        $twilioToken = $settings['twilio_token'] ?? '';
        $twilioWhatsAppNumber = $settings['twilio_whatsapp_number'] ?? '';
        $contentSid = $settings['twilio_whatsapp_template_sid'] ?? '';

        if (empty($twilioSid) || empty($twilioToken) || empty($twilioWhatsAppNumber) || empty($contentSid)) {
            throw new \Exception("Twilio or Template SID is not configured. Please ask the superadmin to configure Twilio settings in the Global Settings panel.");
        }

        // Format recipient number for WhatsApp
        $to = "whatsapp:" . preg_replace('/[^0-9+]/', '', $toPhone);
        $from = $twilioWhatsAppNumber;
        
        $url = "https://api.twilio.com/2010-04-01/Accounts/" . $twilioSid . "/Messages.json";
        
        $data = [
            'To' => $to,
            'From' => $from,
            'ContentSid' => $contentSid,
            'ContentVariables' => json_encode($contentVariables)
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERPWD, $twilioSid . ':' . $twilioToken);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \Exception("cURL Error: " . $error);
        }
        
        curl_close($ch);
        
        $responseData = json_decode($response, true);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return true;
        } else {
            $errorMsg = $responseData['message'] ?? 'Unknown Twilio API error';
            throw new \Exception("Twilio API Error ($httpCode): " . $errorMsg);
        }
    }
}
