<?php
// app/Helpers/SMSHelper.php

class SMSHelper {
    /**
     * Send SMS to a recipient
     */
    public static function send($to, $message) {
        $db = getDB();
        
        // Fetch SMS settings from system_settings
        $settings = [];
        try {
            $rows = $db->query('SELECT * FROM system_settings WHERE setting_key LIKE "sms_%"')->fetchAll();
            foreach ($rows as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Exception $e) {
            // Table might not exist or database query fails
        }
        
        $gateway = $settings['sms_gateway'] ?? 'mock';
        $status = 'failed';
        
        // Clean recipient number: keep only digits and optional leading +
        $toClean = preg_replace('/[^0-9+]/', '', $to);

        if ($gateway === 'twilio') {
            $sid   = $settings['sms_twilio_sid'] ?? '';
            $token = $settings['sms_twilio_token'] ?? '';
            $from  = $settings['sms_twilio_from'] ?? '';
            
            if ($sid && $token && $from) {
                $url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json";
                $postData = [
                    'To'   => $toClean,
                    '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($postData));
                curl_setopt($ch, CURLOPT_USERPWD, "$sid:$token");
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode >= 200 && $httpCode < 300) {
                    $status = 'sent';
                } else {
                    error_log("Twilio SMS send failure: HTTP $httpCode, response: $response");
                }
            } else {
                error_log("Twilio SMS config is incomplete.");
            }
        } elseif ($gateway === 'generic_http') {
            $apiUrl = $settings['sms_generic_url'] ?? '';
            if ($apiUrl) {
                // Replace placeholders
                $sendUrl = str_replace(
                    ['{to}', '{message}'],
                    [urlencode($toClean), urlencode($message)],
                    $apiUrl
                );
                
                $ch = curl_init($sendUrl);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode >= 200 && $httpCode < 300) {
                    $status = 'sent';
                } else {
                    error_log("Generic HTTP SMS failure: HTTP $httpCode, response: $response");
                }
            }
        } else {
            // Mock Mode
            $logFile = __DIR__ . '/../../scratch/sms_logs.txt';
            $logMsg = date('[Y-m-d H:i:s]') . " Sent Mock SMS to $toClean: $message\n";
            @file_put_contents($logFile, $logMsg, FILE_APPEND);
            $status = 'sent';
        }
        
        // Log in notifications table
        try {
            $stmt = $db->prepare('INSERT INTO notifications (title, message, type, status) VALUES (?, ?, "sms", ?)');
            $stmt->execute(["Promotional SMS to $toClean", $message, $status]);
        } catch (\Exception $ex) {
            // Ignore log failure
        }
        
        return ($status === 'sent');
    }
}
