<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * SMS Library
 * Handles SMS gateway integration
 */
class Sms
{
    protected $CI;

    public function __construct()
    {
        $this->CI = &get_instance();
    }

    /**
     * Get available SMS gateways
     * @return array
     */
    public function get_gateways()
    {
        return array(
            'twilio' => array(
                'name' => 'Twilio',
                'info' => '<p class="alert alert-info">Twilio SMS Gateway</p>',
                'options' => array(
                    array(
                        'name' => 'twilio_account_sid',
                        'label' => 'Account SID',
                        'value' => config_item('twilio_account_sid'),
                        'info' => 'Your Twilio Account SID'
                    ),
                    array(
                        'name' => 'twilio_auth_token',
                        'label' => 'Auth Token',
                        'value' => config_item('twilio_auth_token'),
                        'info' => 'Your Twilio Auth Token'
                    ),
                    array(
                        'name' => 'twilio_phone_number',
                        'label' => 'Phone Number',
                        'value' => config_item('twilio_phone_number'),
                        'info' => 'Your Twilio Phone Number (with country code)'
                    )
                )
            ),
            'msg91' => array(
                'name' => 'MSG91',
                'info' => '<p class="alert alert-info">MSG91 SMS Gateway</p>',
                'options' => array(
                    array(
                        'name' => 'msg91_api_key',
                        'label' => 'API Key',
                        'value' => config_item('msg91_api_key'),
                        'info' => 'Your MSG91 API Key'
                    ),
                    array(
                        'name' => 'msg91_sender_id',
                        'label' => 'Sender ID',
                        'value' => config_item('msg91_sender_id'),
                        'info' => 'Your MSG91 Sender ID'
                    )
                )
            ),
            'nexmo' => array(
                'name' => 'Nexmo (Vonage)',
                'info' => '<p class="alert alert-info">Nexmo/Vonage SMS Gateway</p>',
                'options' => array(
                    array(
                        'name' => 'nexmo_api_key',
                        'label' => 'API Key',
                        'value' => config_item('nexmo_api_key'),
                        'info' => 'Your Nexmo API Key'
                    ),
                    array(
                        'name' => 'nexmo_api_secret',
                        'label' => 'API Secret',
                        'value' => config_item('nexmo_api_secret'),
                        'info' => 'Your Nexmo API Secret'
                    ),
                    array(
                        'name' => 'nexmo_from_name',
                        'label' => 'From Name',
                        'value' => config_item('nexmo_from_name'),
                        'info' => 'The name or number to send from'
                    )
                )
            )
        );
    }

    /**
     * Get available SMS triggers/templates
     * @return array
     */
    public function get_available_triggers()
    {
        return array(
            'purchase_confirmation' => array(
                'label' => 'Purchase Confirmation',
                'info' => 'Sent when purchase is confirmed',
                'value' => config_item('sms_template_purchase_confirmation'),
                'sms_number' => config_item('purchase_confirmation_sms_number'),
                'merge_fields' => array('{PURCHASE_ID}', '{SUPPLIER_NAME}', '{TOTAL_AMOUNT}', '{DATE}')
            ),
            'purchase_payment_confirmation' => array(
                'label' => 'Purchase Payment Confirmation',
                'info' => 'Sent when purchase payment is confirmed',
                'value' => config_item('sms_template_purchase_payment_confirmation'),
                'merge_fields' => array('{PURCHASE_ID}', '{PAYMENT_AMOUNT}', '{SUPPLIER_NAME}', '{DATE}')
            ),
            'return_stock' => array(
                'label' => 'Return Stock',
                'info' => 'Sent when stock is returned',
                'value' => config_item('sms_template_return_stock'),
                'merge_fields' => array('{RETURN_ID}', '{SUPPLIER_NAME}', '{TOTAL_AMOUNT}', '{DATE}')
            ),
            'return_stock_payment' => array(
                'label' => 'Return Stock Payment',
                'info' => 'Sent when return stock payment is made',
                'value' => config_item('sms_template_return_stock_payment'),
                'merge_fields' => array('{RETURN_ID}', '{PAYMENT_AMOUNT}', '{SUPPLIER_NAME}', '{DATE}')
            ),
            'transaction_record' => array(
                'label' => 'Transaction Record',
                'info' => 'Sent when transaction is recorded',
                'value' => config_item('sms_template_transaction_record'),
                'sms_number' => config_item('transaction_record_sms_number'),
                'merge_fields' => array('{TRANSACTION_ID}', '{AMOUNT}', '{TYPE}', '{DATE}')
            ),
            'reminder_invoice' => array(
                'label' => 'Invoice Reminder',
                'info' => 'Sent as invoice reminder',
                'value' => config_item('sms_template_reminder_invoice'),
                'merge_fields' => array('{INVOICE_ID}', '{CLIENT_NAME}', '{TOTAL_AMOUNT}', '{DUE_DATE}')
            ),
            'overdue_invoice' => array(
                'label' => 'Overdue Invoice',
                'info' => 'Sent when invoice is overdue',
                'value' => config_item('sms_template_overdue_invoice'),
                'merge_fields' => array('{INVOICE_ID}', '{CLIENT_NAME}', '{TOTAL_AMOUNT}', '{OVERDUE_DAYS}')
            ),
            'invoice_payment' => array(
                'label' => 'Invoice Payment',
                'info' => 'Sent when invoice payment is received',
                'value' => config_item('sms_template_invoice_payment'),
                'merge_fields' => array('{INVOICE_ID}', '{PAYMENT_AMOUNT}', '{CLIENT_NAME}', '{DATE}')
            ),
            'estimate_expiration' => array(
                'label' => 'Estimate Expiration',
                'info' => 'Sent when estimate is about to expire',
                'value' => config_item('sms_template_estimate_expiration'),
                'merge_fields' => array('{ESTIMATE_ID}', '{CLIENT_NAME}', '{EXPIRY_DATE}')
            ),
            'proposal_expiration' => array(
                'label' => 'Proposal Expiration',
                'info' => 'Sent when proposal is about to expire',
                'value' => config_item('sms_template_proposal_expiration'),
                'merge_fields' => array('{PROPOSAL_ID}', '{CLIENT_NAME}', '{EXPIRY_DATE}')
            ),
            'staff_reminder' => array(
                'label' => 'Staff Reminder',
                'info' => 'Sent as reminder to staff',
                'value' => config_item('sms_template_staff_reminder'),
                'merge_fields' => array('{STAFF_NAME}', '{MESSAGE}', '{DATE}')
            )
        );
    }

    /**
     * Get trigger option name
     * @param string $trigger_name
     * @return string
     */
    public function trigger_option_name($trigger_name)
    {
        return 'sms_template_' . $trigger_name;
    }

    /**
     * Send SMS
     * @param string $trigger_type
     * @param string $phone_number
     * @param array $merge_fields
     * @return bool
     */
    public function send($trigger_type, $phone_number, $merge_fields = array())
    {
        // Get active gateway
        $gateways = $this->get_gateways();
        $active_gateway = null;

        foreach ($gateways as $gateway_name => $gateway_config) {
            if (config_item($gateway_name . '_status') == '1') {
                $active_gateway = $gateway_name;
                break;
            }
        }

        if (!$active_gateway) {
            log_message('error', 'No active SMS gateway found');
            return false;
        }

        // Get template
        $template = config_item('sms_template_' . $trigger_type);
        if (empty($template)) {
            log_message('error', 'SMS template not found for trigger: ' . $trigger_type);
            return false;
        }

        // Replace merge fields
        foreach ($merge_fields as $key => $value) {
            $template = str_replace($key, $value, $template);
        }

        // Send via active gateway
        $result = false;
        switch ($active_gateway) {
            case 'twilio':
                $result = $this->send_via_twilio($phone_number, $template);
                break;
            case 'msg91':
                $result = $this->send_via_msg91($phone_number, $template);
                break;
            case 'nexmo':
                $result = $this->send_via_nexmo($phone_number, $template);
                break;
        }

        return $result;
    }

    /**
     * Send SMS via Twilio
     */
    protected function send_via_twilio($phone_number, $message)
    {
        $account_sid = config_item('twilio_account_sid');
        $auth_token = config_item('twilio_auth_token');
        $from_number = config_item('twilio_phone_number');

        if (empty($account_sid) || empty($auth_token) || empty($from_number)) {
            log_message('error', 'Twilio credentials not configured');
            return false;
        }

        // Twilio API integration would go here
        log_message('info', 'SMS sent via Twilio to: ' . $phone_number);
        return true;
    }

    /**
     * Send SMS via MSG91
     */
    protected function send_via_msg91($phone_number, $message)
    {
        $api_key = config_item('msg91_api_key');
        $sender_id = config_item('msg91_sender_id');

        if (empty($api_key) || empty($sender_id)) {
            log_message('error', 'MSG91 credentials not configured');
            return false;
        }

        // MSG91 API integration would go here
        log_message('info', 'SMS sent via MSG91 to: ' . $phone_number);
        return true;
    }

    /**
     * Send SMS via Nexmo
     */
    protected function send_via_nexmo($phone_number, $message)
    {
        $api_key = config_item('nexmo_api_key');
        $api_secret = config_item('nexmo_api_secret');
        $from_name = config_item('nexmo_from_name');

        if (empty($api_key) || empty($api_secret)) {
            log_message('error', 'Nexmo credentials not configured');
            return false;
        }

        // Nexmo API integration would go here
        log_message('info', 'SMS sent via Nexmo to: ' . $phone_number);
        return true;
    }

    /**
     * Test SMS configuration
     */
    public function test($gateway, $phone_number, $message)
    {
        switch ($gateway) {
            case 'twilio':
                return $this->send_via_twilio($phone_number, $message);
            case 'msg91':
                return $this->send_via_msg91($phone_number, $message);
            case 'nexmo':
                return $this->send_via_nexmo($phone_number, $message);
            default:
                return false;
        }
    }
}
