<?php

namespace App\Libraries;

/**
 * Base Executor class for SMS and other notification services
 * Provides common functionality for sending messages via external providers
 */
if (!defined('BASEPATH') && !defined('SYSTEMPATH')) {
    define('CI_LEGACY', true);
}

class ExecutorBase {
        
        protected $serviceType;
        protected $config;
        
        public function __construct($serviceType = 'sms') {
            $this->serviceType = $serviceType;
            $this->loadConfig();
        }
        
        /**
         * Load configuration for the service
         */
        protected function loadConfig() {
            // Configuration is loaded from environment variables or config files
            // This method can be overridden by subclasses
        }
        
        /**
         * Format message as SMS payload
         */
        protected function asSms($message) {
            return $message;
        }
        
        /**
         * Validate and normalize phone number
         */
        protected function normalizePhoneNumber($phone) {
            // Remove any non-numeric characters except +
            $phone = preg_replace('/[^0-9+]/', '', $phone);
            
            // Add + prefix if not present
            if (substr($phone, 0, 1) !== '+') {
                // Assume Tanzanian number if starts with 255
                if (substr($phone, 0, 3) === '255') {
                    $phone = '+' . $phone;
                } elseif (substr($phone, 0, 1) === '0') {
                    // Convert 07xx to +2557xx
                    $phone = '+255' . substr($phone, 1);
                } else {
                    $phone = '+' . $phone;
                }
            }
            
            return $phone;
        }
        
        /**
         * Validate email address
         */
        protected function validateEmail($email) {
            return filter_var($email, FILTER_VALIDATE_EMAIL);
        }
        
        /**
         * Log message with service type prefix
         */
        protected function log($level, $message, $context = []) {
            $contextStr = !empty($context) ? ' ' . json_encode($context) : '';
            log_message($level, "[{$this->serviceType}] {$message}{$contextStr}");
        }
        
        /**
         * Execute the task - to be implemented by subclasses
         */
        protected function executeTask($messages, $isLast = true) {
            throw new \Exception('executeTask must be implemented by subclass');
        }
        
        /**
         * Get the last response from the provider
         */
        public function getLastResponse() {
            return null;
        }
        
        /**
         * Check if the service is properly configured
         */
        public function isConfigured() {
            return true; // Default implementation
        }
    }
