/home/awneajlw/www/codestechvista.com/includes/sms_service.php
<?php
/**
 * SMS Service using Twilio
 * Handle all SMS notifications for the application
 */

require_once __DIR__ . '/../config/twilio_config.php';

class SMSService {
    private $account_sid;
    private $auth_token;
    private $twilio_number;
    private $twilio_whatsapp_number;
    private $admin_number;
    private $admin_whatsapp_number;
    private $sms_enabled;
    private $whatsapp_enabled;
    private $sms_debug;
    private $whatsapp_debug;
    
    public function __construct() {
        $this->account_sid = TWILIO_ACCOUNT_SID;
        $this->auth_token = TWILIO_AUTH_TOKEN;
        $this->twilio_number = TWILIO_PHONE_NUMBER;
        $this->twilio_whatsapp_number = TWILIO_WHATSAPP_NUMBER;
        $this->admin_number = ADMIN_PHONE_NUMBER;
        $this->admin_whatsapp_number = ADMIN_WHATSAPP_NUMBER;
        $this->sms_enabled = SMS_ENABLED;
        $this->whatsapp_enabled = WHATSAPP_ENABLED;
        $this->sms_debug = SMS_DEBUG;
        $this->whatsapp_debug = WHATSAPP_DEBUG;
    }
    
    /**
     * Send WhatsApp Message using Twilio API
     */
    public function sendWhatsApp($to, $message) {
        if (!$this->whatsapp_enabled) {
            $this->log("WhatsApp disabled - would send to $to: $message");
            return false;
        }
        
        if ($this->whatsapp_debug) {
            $this->log("DEBUG MODE - WhatsApp to $to: $message");
            return true;
        }
        
        // Format WhatsApp number if not already formatted
        if (strpos($to, 'whatsapp:') !== 0) {
            $to = 'whatsapp:' . $to;
        }
        
        try {
            // Twilio API endpoint
            $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->account_sid}/Messages.json";
            
            // POST data
            $data = [
                'From' => $this->twilio_whatsapp_number,
                'To' => $to,
                'Body' => $message
            ];
            
            // Initialize cURL
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $this->account_sid . ':' . $this->auth_token);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/x-www-form-urlencoded'
            ]);
            
            // Execute request
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code == 201) {
                $this->log("WhatsApp sent successfully to $to");
                return true;
            } else {
                $this->log("WhatsApp failed to $to. HTTP Code: $http_code. Response: $response");
                return false;
            }
            
        } catch (Exception $e) {
            $this->log("WhatsApp Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send SMS using Twilio API
     */
    public function sendSMS($to, $message) {
        if (!$this->sms_enabled) {
            $this->log("SMS disabled - would send to $to: $message");
            return false;
        }
        
        if ($this->sms_debug) {
            $this->log("DEBUG MODE - SMS to $to: $message");
            return true;
        }
        
        try {
            // Twilio API endpoint
            $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->account_sid}/Messages.json";
            
            // POST data
            $data = [
                'From' => $this->twilio_number,
                'To' => $to,
                'Body' => $message
            ];
            
            // Initialize cURL
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $this->account_sid . ':' . $this->auth_token);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/x-www-form-urlencoded'
            ]);
            
            // Execute request
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code == 201) {
                $this->log("SMS sent successfully to $to");
                return true;
            } else {
                $this->log("SMS failed to $to. HTTP Code: $http_code. Response: $response");
                return false;
            }
            
        } catch (Exception $e) {
            $this->log("SMS Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send New Order Notification (WhatsApp + SMS)
     */
    public function sendNewOrderNotification($order_id, $customer_name, $total_amount, $phone_number = null) {
        // WhatsApp messages
        $whatsapp_message = WhatsAppTemplates::newOrder($order_id, $customer_name, $total_amount);
        $customer_whatsapp_message = WhatsAppTemplates::customerOrderConfirmation($order_id, $customer_name, $total_amount);
        
        // SMS messages (backup)
        $sms_message = SMSTemplates::newOrder($order_id, $customer_name, $total_amount);
        
        // Send WhatsApp to admin
        $this->sendWhatsApp($this->admin_whatsapp_number, $whatsapp_message);
        
        // Send WhatsApp to customer if phone number provided
        if ($phone_number) {
            $customer_whatsapp = 'whatsapp:' . $phone_number;
            $this->sendWhatsApp($customer_whatsapp, $customer_whatsapp_message);
        }
        
        // Backup SMS to admin
        $this->sendSMS($this->admin_number, $sms_message);
        
        // Log notification
        $this->logNotification('new_order', $order_id, $customer_name);
    }
    
    /**
     * Send Order Completed Notification (WhatsApp + SMS)
     */
    public function sendOrderCompletedNotification($order_id, $customer_name, $total_amount, $phone_number = null) {
        // WhatsApp messages
        $whatsapp_message = WhatsAppTemplates::orderCompleted($order_id, $customer_name, $total_amount);
        
        // SMS messages (backup)
        $sms_message = SMSTemplates::orderCompleted($order_id, $customer_name, $total_amount);
        
        // Send WhatsApp to admin
        $this->sendWhatsApp($this->admin_whatsapp_number, $whatsapp_message);
        
        // Send WhatsApp to customer if phone number provided
        if ($phone_number) {
            $customer_whatsapp = 'whatsapp:' . $phone_number;
            $this->sendWhatsApp($customer_whatsapp, $whatsapp_message);
        }
        
        // Backup SMS to admin
        $this->sendSMS($this->admin_number, $sms_message);
        
        // Log notification
        $this->logNotification('order_completed', $order_id, $customer_name);
    }
    
    /**
     * Send Order Status Update Notification (WhatsApp + SMS)
     */
    public function sendOrderStatusUpdateNotification($order_id, $customer_name, $old_status, $new_status, $phone_number = null) {
        // WhatsApp messages
        $whatsapp_message = WhatsAppTemplates::orderStatusUpdate($order_id, $customer_name, $old_status, $new_status);
        
        // SMS messages (backup)
        $sms_message = SMSTemplates::orderStatusUpdate($order_id, $customer_name, $old_status, $new_status);
        
        // Send WhatsApp to admin
        $this->sendWhatsApp($this->admin_whatsapp_number, $whatsapp_message);
        
        // Send WhatsApp to customer if phone number provided
        if ($phone_number) {
            $customer_whatsapp = 'whatsapp:' . $phone_number;
            $this->sendWhatsApp($customer_whatsapp, $whatsapp_message);
        }
        
        // Backup SMS to admin
        $this->sendSMS($this->admin_number, $sms_message);
        
        // Log notification
        $this->logNotification('status_update', $order_id, $customer_name);
    }
    
    /**
     * Send Daily Summary (WhatsApp + SMS)
     */
    public function sendDailySummary($total_orders, $total_amount, $pending_orders) {
        // WhatsApp message
        $whatsapp_message = WhatsAppTemplates::dailySummary($total_orders, $total_amount, $pending_orders);
        
        // SMS message (backup)
        $sms_message = SMSTemplates::dailySummary($total_orders, $total_amount, $pending_orders);
        
        // Send WhatsApp to admin
        $this->sendWhatsApp($this->admin_whatsapp_number, $whatsapp_message);
        
        // Backup SMS to admin
        $this->sendSMS($this->admin_number, $sms_message);
        
        // Log notification
        $this->logNotification('daily_summary', null, null);
    }
    
    /**
     * Log SMS activities
     */
    private function log($message) {
        $timestamp = date('Y-m-d H:i:s');
        $log_message = "[$timestamp] SMS Service: $message\n";
        
        // Log to file
        $log_file = __DIR__ . '/../logs/sms_log.txt';
        if (!is_dir(dirname($log_file))) {
            mkdir(dirname($log_file), 0755, true);
        }
        file_put_contents($log_file, $log_message, FILE_APPEND | LOCK_EX);
        
        // Also log to PHP error log
        error_log($log_message);
    }
    
    /**
     * Log notifications to database
     */
    private function logNotification($type, $order_id, $customer_name) {
        try {
            $database = new Database();
            $db = $database->getConnection();
            
            $query = "INSERT INTO sms_notifications (notification_type, order_id, customer_name, sent_at) VALUES (?, ?, ?, NOW())";
            $stmt = $db->prepare($query);
            $stmt->execute([$type, $order_id, $customer_name]);
        } catch (Exception $e) {
            $this->log("Failed to log notification: " . $e->getMessage());
        }
    }
    
    /**
     * Get SMS statistics
     */
    public function getSMSStats() {
        try {
            $database = new Database();
            $db = $database->getConnection();
            
            $query = "SELECT 
                        notification_type,
                        COUNT(*) as count,
                        DATE(sent_at) as date
                      FROM sms_notifications 
                      WHERE sent_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                      GROUP BY notification_type, DATE(sent_at)
                      ORDER BY sent_at DESC";
            
            $stmt = $db->prepare($query);
            $stmt->execute();
            
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            $this->log("Failed to get SMS stats: " . $e->getMessage());
            return [];
        }
    }
}
?>