<?php
use gateways\SMSIRGateway;
use gateways\IPPANELGateway;
use gateways\MELLIPAYAMAKGateway;
use gateways\KAVEHNEGARGateway;


class KavehSMSHandler
{
    private $smsManager;
    private $settingsPrefix;

    public $options;
    public $smsoptions;
    public $input_data;

    public function __construct($prefix)
    {
        $this->settingsPrefix = $prefix;
        $this->options = kaveh_get_options();

        $this->smsoptions = get_option('kaveh_sms');
        if (kavehwooSMSmanger::are_any_sms_notifications_enabled()) {
            add_action('woocommerce_order_status_changed', [$this, 'handleOrderStatusChange'], 10, 3);
        } 
    }


    

    public function handleOrderStatusChange($order_id, $old_status, $new_status)
    {
        $statusTitle = $this->getOrderStatusTitle($new_status);

        $order = wc_get_order($order_id);
        $tags = $this->getTags($order, $new_status, $statusTitle);
        $input_data = $this->getData($tags, $new_status);
        $input_manager_data = $this->getmanagerData($tags, $new_status);
        $customer_id = $order->get_user_id();
        $customer_mobile = get_user_meta($customer_id, 'billing_phone', true);



        if (!$customer_mobile || empty($customer_mobile)) {
            return;
        }
        $statusKey = $new_status;

        $isCustomerActive = $this->smsoptions['kaveh_smson_customer_' . $statusKey];
        $customerPattern = $this->smsoptions['smstaboption']['kaveh_banner_patern_' . $statusKey];
        $managerMobiles = $this->smsoptions['smstaboption']['kaveh_manager_tel_' . $statusKey];
        $managerPattern = $this->smsoptions['smstaboption']['kaveh_manager_patern_' . $statusKey];







        if ($isCustomerActive) {
            $this->sendSMS($customer_mobile, $customerPattern, 'customer', $input_data);
        }

        if (!empty($managerMobiles)) {
            $this->sendSMSForManagers($managerMobiles, $managerPattern, 'manager', $input_manager_data);
        }

    }

    private function getOrderStatusTitle($statusKey)
    {
        $statuses = wc_get_order_statuses();

        return isset($statuses['wc-' . $statusKey]) ? $statuses['wc-' . $statusKey] : $statusKey;
    }

    private function getTags($order, $new_status, $statusTitle)
    {
        $billing_info = [
            "order_id" => $order->get_id(),
            "status" => $statusTitle,
            "transaction_id" => $order->get_transaction_id() ? $order->get_transaction_id() : 'بدون تراکنش',
            "customerdescription" => $order->get_customer_note(),
            "paymentmethod" => $order->get_payment_method_title(),
            "price" => number_format($order->get_total()),
            "shipping" => number_format($order->get_shipping_total()),
            "discount" => number_format($order->get_discount_total()),

            // اطلاعات مشتری
            "mobile" => get_user_meta($order->get_user_id(), 'billing_phone', true),
            "phone" => get_user_meta($order->get_user_id(), 'billing_phone', true),
            "email" => $order->get_billing_email(),

            // جزئیات محصولات
            "all_items" => implode(' - ', array_map(fn($item) => $item->get_name(), $order->get_items())),
            "all_items_qty" => implode(' - ', array_map(fn($item) => $item->get_quantity(), $order->get_items())),
            "count_items" => $order->get_item_count(),

            // جزئیات آدرس
            "first_name" => $order->get_billing_first_name(),
            "last_name" => $order->get_billing_last_name(),
            "company" => $order->get_billing_company(),
            "country" => WC()->countries->countries[$order->get_billing_country()],
            "state" => WC()->countries->states[$order->get_billing_country()][$order->get_billing_state()],
            "city" => $order->get_billing_city(),
            "address_1" => $order->get_billing_address_1(),
            "address_2" => $order->get_billing_address_2(),
            "postcode" => $order->get_billing_postcode(),

            "date" => $order->get_date_created()->date('Y-m-d H:i:s'),
            "post_id" => $order->get_id(),
            "shippingmethod" => $order->get_shipping_method(),
        ];

        $shipping_info = [
            "first_name" => $order->get_shipping_first_name(),
            "last_name" => $order->get_shipping_last_name(),
            "company" => $order->get_shipping_company(),
            "country" => WC()->countries->countries[$order->get_shipping_country()],
            "state" => WC()->countries->states[$order->get_shipping_country()][$order->get_shipping_state()],
            "city" => $order->get_shipping_city(),
            "address_1" => $order->get_shipping_address_1(),
            "address_2" => $order->get_shipping_address_2(),
            "postcode" => $order->get_shipping_postcode(),
        ];

        // Get the country names
        $country = WC()->countries;
        $billing_country_name = isset($country->countries[$billing_info['country']]) ? $country->countries[$billing_info['country']] : $billing_info['country'];
        $billing_state_name = (isset($country->states[$billing_info['country']][$billing_info['state']]) ? $country->states[$billing_info['country']][$billing_info['state']] : $billing_info['state']);

        $shipping_country_name = isset($country->countries[$shipping_info['country']]) ? $country->countries[$shipping_info['country']] : $shipping_info['country'];
        $shipping_state_name = (isset($country->states[$shipping_info['country']][$shipping_info['state']]) ? $country->states[$shipping_info['country']][$shipping_info['state']] : $shipping_info['state']);

        // Create the tags array
        $tags = [
            'customer_first_name' => $billing_info['first_name'],
            'customer_last_name' => $billing_info['last_name'],
            'customer_company' => $billing_info['company'],
            'customer_address_1' => $billing_info['address_1'],
            'customer_address_2' => $billing_info['address_2'],
            'customer_state' => $billing_state_name,
            'customer_city' => $billing_info['city'],
            'customer_postcode' => $billing_info['postcode'],
            'customer_country' => $billing_country_name,
            'receiver_first_name' => $shipping_info['first_name'],
            'receiver_last_name' => $shipping_info['last_name'],
            'receiver_company' => $shipping_info['company'],
            'receiver_address_1' => $shipping_info['address_1'],
            'receiver_address_2' => $shipping_info['address_2'],
            'receiver_state' => $shipping_state_name,
            'receiver_city' => $shipping_info['city'],
            'receiver_postcode' => $shipping_info['postcode'],
            'receiver_country' => $shipping_country_name,
            'mobile' => $billing_info['mobile'],
            'phone' => $billing_info['phone'],
            'email' => $billing_info['email'],
            'status' => $billing_info['status'],
            'all_items' => $billing_info['all_items'],
            'all_items_qty' => $billing_info['all_items_qty'],
            'count_items' => $billing_info['count_items'],
            'price' => $billing_info['price'],
            'post_id' => $billing_info['post_id'],
            'order_id' => $billing_info['order_id'],
            'transaction_id' => $billing_info['transaction_id'],
            'date' => $billing_info['date'],
            'customerdescription' => $billing_info['customerdescription'],
            'paymentmethod' => $billing_info['paymentmethod'],
            'shippingmethod' => $billing_info['shippingmethod'],
        ];

        return $tags;
    }

    private function getData($tags, $new_status)
    {
        $smsPanel = $this->options['kaveh_sms_gateway'];
        $statusKey = $new_status;
        $messagetextarea = $this->smsoptions['smstaboption']['kaveh_pattern_paragraph_' . $statusKey];

        preg_match_all('/\{([^}]+)\}/', $messagetextarea, $matches);

        switch ($smsPanel) {
            case 'option-2':
                $variablesArray = $matches[1];
                $input_data = array();

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_data[] = array(
                            "name" => strtoupper($variable),  
                            "value" => $tags[$variable]
                        );
                    }
                }

                return $input_data;

                break;
            case 'option-1':
                $variablesArray = $matches[1];
                $input_data = array();

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_data[$variable] = $tags[$variable];
                    }
                }

                return $input_data;
                break;
            case 'option-3':
                $variablesArray = $matches[1];
                $para = array();
                $input_data = ''; // Initialize as empty string

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $para[$variable] = $tags[$variable];
                    }
                }

                foreach ($para as $key => $value) {
                    $input_data .= $value . ';';
                }

                $input_data = rtrim($input_data, ';');
                return $input_data;

                break;
            case 'option-5':
                // Empty case
                break;
            case 'option-4':
                $variablesArray = $matches[1];
                $input_data = array();

                // ایجاد پارامترها از متغیرهای موجود
                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_data[] = $tags[$variable];
                    }
                }
                return $input_data;

                break;
        }
    }

    private function getmanagerData($tags, $new_status)
    {
        $smsPanel = $this->options['kaveh_sms_gateway'];
        $statusKey = $new_status;
        $messagetextarea = $this->smsoptions['smstaboption']['kaveh_pattern_manager_paragraph_' . $statusKey];

        preg_match_all('/\{([^}]+)\}/', $messagetextarea, $matches);

        switch ($smsPanel) {
            case 'option-2':
                $variablesArray = $matches[1];
                $input_manager_data = array();

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_manager_data[] = array(
                            "name" => strtoupper($variable),  
                            "value" => $tags[$variable]
                        );
                    }
                }

                return $input_manager_data;

                break;
            case 'option-1':
                $variablesArray = $matches[1];
                $input_manager_data = array();

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_manager_data[$variable] = $tags[$variable];
                    }
                }

                return $input_manager_data;
                break;
            case 'option-3':
                $variablesArray = $matches[1];
                $para = array();
                $input_manager_data = ''; // Initialize as empty string

                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $para[$variable] = $tags[$variable];
                    }
                }

                foreach ($para as $key => $value) {
                    $input_manager_data .= $value . ';';
                }

                $input_manager_data = rtrim($input_manager_data, ';');
                return $input_manager_data;

                break;
            case 'option-5':
                // Empty case
                break;
            case 'option-4':
                $variablesArray = $matches[1];
                $input_manager_data = array();

                // ایجاد پارامترها از متغیرهای موجود
                foreach ($variablesArray as $variable) {
                    if (isset($tags[$variable])) {
                        $input_manager_data[] = $tags[$variable];
                    }
                }
                return $input_manager_data;

                break;
        }
    }

    private function sendSMSForManagers($mobiles, $pattern, $recipient, $input_data)
    {
        $managerNumbers = strpos($mobiles, ',') !== false ? explode(',', $mobiles) : [$mobiles];


        foreach ($managerNumbers as $mobile) {
            $mobile = trim($mobile);
            if (!empty($mobile)) {
                $this->sendSMS($mobile, $pattern, 'manager', $input_data);
            }
        }
    }

    private function sendSMS($mobile, $pattern, $recipient, $input_data)
    {
        // اطلاعات پنل پیامک از تنظیمات
        $smsPanel = $this->options['kaveh_sms_gateway'];
        $apiKey = $this->options['kaveh_password_api'];
        $username = $this->options['kaveh_username_sms'];
        $password = $this->options['kaveh_password_sms'];
        $from = $this->options['kaveh_number_sms'];

        switch ($smsPanel) {
            case 'option-2':

                SMSIRGateway::sendSMS($apiKey, $mobile, $pattern, $input_data);
                break;
            case 'option-1':

                IPPANELGateway::sendSMS($from, $mobile, $username, $password, $pattern, $input_data);

                break;
            case 'option-3':
                MELLIPAYAMAKGateway::sendSMS($username, $password, $mobile, $pattern, $input_data);

                break;
            case 'option-5':
                Raygansms::raygansms($username, $password, $mobile, $pattern, '');
                break;
            case 'option-4':

                KAVEHNEGARGateway::sendSMS($apiKey, $mobile, $pattern, $input_data);

                break;
        }
    }
}
