<?php

/**
 * WhatsApp Channel - Example Implementation
 * 
 * This is a reference implementation showing how to create a custom notification channel.
 * Developers can use this as a template for implementing WhatsApp, SMS, Telegram, etc.
 * 
 * @package WooNooW\Core\Notifications\Channels
 */

namespace WooNooW\Core\Notifications\Channels;

/**
 * Example WhatsApp Channel Implementation
 * 
 * This channel sends notifications via WhatsApp Business API.
 * Replace API calls with your actual WhatsApp service provider (Twilio, MessageBird, etc.)
 */
class WhatsAppChannel implements ChannelInterface
{

    /**
     * Get channel ID
     */
    public function get_id()
    {
        return 'whatsapp';
    }

    /**
     * Get channel label
     */
    public function get_label()
    {
        return __('WhatsApp', 'woonoow');
    }

    /**
     * Check if channel is configured
     */
    public function is_configured()
    {
        $api_key = get_option('woonoow_whatsapp_api_key', '');
        $phone_number = get_option('woonoow_whatsapp_phone_number', '');

        return !empty($api_key) && !empty($phone_number);
    }

    /**
     * Send WhatsApp notification
     * 
     * @param string $event_id Event identifier
     * @param string $recipient Recipient type ('customer' or 'staff')
     * @param array $data Context data (order, user, etc.)
     * @return bool|array Success status
     */
    public function send($event_id, $recipient, $data)
    {
        // Get recipient phone number
        $phone = $this->get_recipient_phone($recipient, $data);

        if (empty($phone)) {
            return [
                'success' => false,
                'message' => 'No phone number available for recipient',
            ];
        }

        // Build message content based on event
        $message = $this->build_message($event_id, $data);

        if (empty($message)) {
            return [
                'success' => false,
                'message' => 'Could not build message for event: ' . $event_id,
            ];
        }

        // Send via WhatsApp API
        $result = $this->send_whatsapp_message($phone, $message);

        // Log the send attempt
        do_action('woonoow_whatsapp_sent', $event_id, $recipient, $phone, $result);

        return $result;
    }

    /**
     * Get configuration fields for admin settings
     */
    public function get_config_fields()
    {
        return [
            [
                'id' => 'woonoow_whatsapp_api_key',
                'label' => __('WhatsApp API Key', 'woonoow'),
                'type' => 'text',
                'description' => __('Your WhatsApp Business API key', 'woonoow'),
            ],
            [
                'id' => 'woonoow_whatsapp_phone_number',
                'label' => __('WhatsApp Business Number', 'woonoow'),
                'type' => 'text',
                'description' => __('Your WhatsApp Business phone number (with country code)', 'woonoow'),
                'placeholder' => '+1234567890',
            ],
            [
                'id' => 'woonoow_whatsapp_provider',
                'label' => __('Service Provider', 'woonoow'),
                'type' => 'select',
                'options' => [
                    'twilio' => 'Twilio',
                    'messagebird' => 'MessageBird',
                    'custom' => 'Custom',
                ],
                'default' => 'twilio',
            ],
        ];
    }

    /**
     * Get recipient phone number
     * 
     * @param string $recipient Recipient type
     * @param array $data Context data
     * @return string Phone number or empty string
     */
    private function get_recipient_phone($recipient, $data)
    {
        if ($recipient === 'customer') {
            // Get customer phone from order or user data
            if (isset($data['order'])) {
                return $data['order']->get_billing_phone();
            }
            if (isset($data['user_id'])) {
                return get_user_meta($data['user_id'], 'billing_phone', true);
            }
            if (isset($data['email'])) {
                $user = get_user_by('email', $data['email']);
                if ($user) {
                    return get_user_meta($user->ID, 'billing_phone', true);
                }
            }
        } elseif ($recipient === 'staff') {
            // Get admin phone from settings
            return get_option('woonoow_whatsapp_admin_phone', '');
        }

        return '';
    }

    /**
     * Build message content based on event
     * 
     * @param string $event_id Event identifier
     * @param array $data Context data
     * @return string Message text
     */
    private function build_message($event_id, $data)
    {
        // Allow filtering message content
        $message = apply_filters("woonoow_whatsapp_message_{$event_id}", '', $data);

        if (!empty($message)) {
            return $message;
        }

        // Default messages for common events
        $site_name = get_bloginfo('name');

        switch ($event_id) {
            case 'order_completed':
                if (isset($data['order'])) {
                    $order = $data['order'];
                    return sprintf(
                        "🎉 Your order #%s has been completed! Thank you for shopping with %s.",
                        $order->get_order_number(),
                        $site_name
                    );
                }
                break;

            case 'newsletter_confirm':
                if (isset($data['confirmation_url'])) {
                    return sprintf(
                        "Please confirm your newsletter subscription by clicking: %s",
                        $data['confirmation_url']
                    );
                }
                break;

                // Add more event templates as needed
        }

        return '';
    }

    /**
     * Send WhatsApp message via API
     * 
     * Replace this with actual API integration for your provider
     * 
     * @param string $phone Recipient phone number
     * @param string $message Message text
     * @return array Result with 'success' and 'message' keys
     */
    private function send_whatsapp_message($phone, $message)
    {
        $api_key = get_option('woonoow_whatsapp_api_key', '');
        $from_number = get_option('woonoow_whatsapp_phone_number', '');
        $provider = get_option('woonoow_whatsapp_provider', 'twilio');

        // Example: Twilio API (replace with your actual implementation)
        if ($provider === 'twilio') {
            $endpoint = 'https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID/Messages.json';

            $response = wp_remote_post($endpoint, [
                'headers' => [
                    'Authorization' => 'Basic ' . base64_encode($api_key),
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ],
                'body' => [
                    'From' => 'whatsapp:' . $from_number,
                    'To' => 'whatsapp:' . $phone,
                    'Body' => $message,
                ],
            ]);

            if (is_wp_error($response)) {
                return [
                    'success' => false,
                    'message' => $response->get_error_message(),
                ];
            }

            $status_code = wp_remote_retrieve_response_code($response);
            return [
                'success' => $status_code >= 200 && $status_code < 300,
                'message' => $status_code >= 200 && $status_code < 300
                    ? 'WhatsApp message sent successfully'
                    : 'Failed to send WhatsApp message',
            ];
        }

        // For custom providers, implement your own logic here
        return [
            'success' => false,
            'message' => 'Provider not configured',
        ];
    }
}
