<?php
/**
 * Email Delivery Service
 * 
 * Routes WordPress emails through Brevo or Postmark API
 * when configured, falling back to default wp_mail() if not.
 *
 * @package Freelance_Studio
 * @since 8.6.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class FS_Email_Delivery {

    /**
     * Initialize the email delivery hooks
     */
    public static function init() {
        $provider = get_option( 'fs_email_delivery_provider', '' );
        $api_key  = get_option( 'fs_email_delivery_api_key', '' );

        if ( ! empty( $provider ) && ! empty( $api_key ) && $provider !== 'smtp_plugin' ) {
            add_filter( 'pre_wp_mail', array( __CLASS__, 'intercept_wp_mail' ), 10, 2 );
        }
    }

    /**
     * Intercept wp_mail and route through configured API
     *
     * @param null|bool $return Short-circuit return value
     * @param array     $atts   Email attributes
     * @return bool|null
     */
    public static function intercept_wp_mail( $return, $atts ) {
        $provider = get_option( 'fs_email_delivery_provider', '' );
        $api_key  = get_option( 'fs_email_delivery_api_key', '' );

        if ( empty( $provider ) || empty( $api_key ) ) {
            return null; // Fall back to default
        }

        $to      = $atts['to'];
        $subject = $atts['subject'];
        $message = $atts['message'];
        $headers = isset( $atts['headers'] ) ? $atts['headers'] : '';

        // Parse headers
        $parsed = self::parse_headers( $headers );

        // Determine from name/email
        $from_email = ! empty( $parsed['from_email'] ) ? $parsed['from_email'] : get_option( 'fs_business_email', get_option( 'admin_email' ) );
        $from_name  = ! empty( $parsed['from_name'] ) ? $parsed['from_name'] : get_option( 'fs_business_name', get_bloginfo( 'name' ) );
        $reply_to   = ! empty( $parsed['reply_to'] ) ? $parsed['reply_to'] : $from_email;
        $content_type = ! empty( $parsed['content_type'] ) ? $parsed['content_type'] : 'text/plain';

        // Normalize $to to array
        if ( ! is_array( $to ) ) {
            $to = array_map( 'trim', explode( ',', $to ) );
        }

        switch ( $provider ) {
            case 'brevo':
                $result = self::send_via_brevo( $api_key, $to, $subject, $message, $from_email, $from_name, $reply_to, $content_type, $parsed );
                break;
            case 'postmark':
                $result = self::send_via_postmark( $api_key, $to, $subject, $message, $from_email, $from_name, $reply_to, $content_type, $parsed );
                break;
            default:
                return null; // Unknown provider, fall back
        }

        if ( is_wp_error( $result ) ) {
            do_action( 'wp_mail_failed', $result );
            error_log( 'Freelance Studio Email Delivery Error (' . $provider . '): ' . $result->get_error_message() );
            
            // If API fails, fall back to default wp_mail
            $fallback = get_option( 'fs_email_delivery_fallback', '1' );
            if ( $fallback === '1' ) {
                return null; // Let WordPress try the default method
            }
            return false;
        }

        return true; // Email sent successfully via API
    }

    /**
     * Send email via Brevo (Sendinblue) API
     */
    private static function send_via_brevo( $api_key, $to, $subject, $message, $from_email, $from_name, $reply_to, $content_type, $parsed ) {
        $recipients = array();
        foreach ( $to as $email ) {
            $clean = self::extract_email( $email );
            if ( is_email( $clean ) ) {
                $recipients[] = array( 'email' => $clean );
            }
        }

        if ( empty( $recipients ) ) {
            return new WP_Error( 'no_recipients', __( 'No valid recipients', 'freelance-studio' ) );
        }

        $body = array(
            'sender'  => array(
                'name'  => $from_name,
                'email' => $from_email,
            ),
            'to'      => $recipients,
            'subject' => $subject,
            'replyTo' => array( 'email' => self::extract_email( $reply_to ) ),
        );

        if ( stripos( $content_type, 'text/html' ) !== false ) {
            $body['htmlContent'] = $message;
        } else {
            $body['textContent'] = $message;
        }

        // Add CC if present
        if ( ! empty( $parsed['cc'] ) ) {
            $cc_list = array();
            foreach ( $parsed['cc'] as $cc ) {
                $clean = self::extract_email( $cc );
                if ( is_email( $clean ) ) {
                    $cc_list[] = array( 'email' => $clean );
                }
            }
            if ( ! empty( $cc_list ) ) {
                $body['cc'] = $cc_list;
            }
        }

        $response = wp_remote_post( 'https://api.brevo.com/v3/smtp/email', array(
            'timeout' => 30,
            'headers' => array(
                'accept'       => 'application/json',
                'content-type' => 'application/json',
                'api-key'      => $api_key,
            ),
            'body'    => wp_json_encode( $body ),
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code >= 200 && $code < 300 ) {
            return true;
        }

        $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
        $error_msg     = isset( $response_body['message'] ) ? $response_body['message'] : __( 'Unknown Brevo API error', 'freelance-studio' );

        return new WP_Error( 'brevo_error', $error_msg );
    }

    /**
     * Send email via Postmark API
     */
    private static function send_via_postmark( $api_key, $to, $subject, $message, $from_email, $from_name, $reply_to, $content_type, $parsed ) {
        $to_addresses = array();
        foreach ( $to as $email ) {
            $clean = self::extract_email( $email );
            if ( is_email( $clean ) ) {
                $to_addresses[] = $clean;
            }
        }

        if ( empty( $to_addresses ) ) {
            return new WP_Error( 'no_recipients', __( 'No valid recipients', 'freelance-studio' ) );
        }

        $body = array(
            'From'    => $from_name . ' <' . $from_email . '>',
            'To'      => implode( ', ', $to_addresses ),
            'Subject' => $subject,
            'ReplyTo' => self::extract_email( $reply_to ),
        );

        if ( stripos( $content_type, 'text/html' ) !== false ) {
            $body['HtmlBody'] = $message;
        } else {
            $body['TextBody'] = $message;
        }

        // Add CC if present
        if ( ! empty( $parsed['cc'] ) ) {
            $cc_addresses = array();
            foreach ( $parsed['cc'] as $cc ) {
                $clean = self::extract_email( $cc );
                if ( is_email( $clean ) ) {
                    $cc_addresses[] = $clean;
                }
            }
            if ( ! empty( $cc_addresses ) ) {
                $body['Cc'] = implode( ', ', $cc_addresses );
            }
        }

        // Set MessageStream to transactional
        $body['MessageStream'] = 'outbound';

        $response = wp_remote_post( 'https://api.postmarkapp.com/email', array(
            'timeout' => 30,
            'headers' => array(
                'Accept'                  => 'application/json',
                'Content-Type'            => 'application/json',
                'X-Postmark-Server-Token' => $api_key,
            ),
            'body'    => wp_json_encode( $body ),
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code === 200 ) {
            return true;
        }

        $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
        $error_msg     = isset( $response_body['Message'] ) ? $response_body['Message'] : __( 'Unknown Postmark API error', 'freelance-studio' );

        return new WP_Error( 'postmark_error', $error_msg );
    }

    /**
     * Verify API key by sending a test request
     *
     * @param string $provider Provider name
     * @param string $api_key  API key
     * @return true|WP_Error
     */
    public static function verify_api_key( $provider, $api_key ) {
        switch ( $provider ) {
            case 'brevo':
                return self::verify_brevo_key( $api_key );
            case 'postmark':
                return self::verify_postmark_key( $api_key );
            default:
                return new WP_Error( 'invalid_provider', __( 'Invalid email provider', 'freelance-studio' ) );
        }
    }

    /**
     * Verify Brevo API key
     */
    private static function verify_brevo_key( $api_key ) {
        $response = wp_remote_get( 'https://api.brevo.com/v3/account', array(
            'timeout' => 15,
            'headers' => array(
                'accept'  => 'application/json',
                'api-key' => $api_key,
            ),
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code === 200 ) {
            $body = json_decode( wp_remote_retrieve_body( $response ), true );
            return true;
        }

        if ( $code === 401 ) {
            return new WP_Error( 'invalid_key', __( 'Invalid API key. Please check your Brevo API key and try again.', 'freelance-studio' ) );
        }

        return new WP_Error( 'api_error', sprintf(
            /* translators: %d: HTTP status code */
            __( 'Brevo API returned status %d. Please try again.', 'freelance-studio' ),
            $code
        ) );
    }

    /**
     * Verify Postmark API key
     */
    private static function verify_postmark_key( $api_key ) {
        $response = wp_remote_get( 'https://api.postmarkapp.com/server', array(
            'timeout' => 15,
            'headers' => array(
                'Accept'                  => 'application/json',
                'X-Postmark-Server-Token' => $api_key,
            ),
        ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        if ( $code === 200 ) {
            return true;
        }

        if ( $code === 401 ) {
            return new WP_Error( 'invalid_key', __( 'Invalid Server API Token. Please check your Postmark token and try again.', 'freelance-studio' ) );
        }

        return new WP_Error( 'api_error', sprintf(
            /* translators: %d: HTTP status code */
            __( 'Postmark API returned status %d. Please try again.', 'freelance-studio' ),
            $code
        ) );
    }

    /**
     * Send a test email through the configured provider
     *
     * @param string $to_email Recipient email
     * @return true|WP_Error
     */
    public static function send_test_email( $to_email ) {
        $business_name = get_option( 'fs_business_name', get_bloginfo( 'name' ) );

        $subject = sprintf(
            /* translators: %s: business name */
            __( 'Test Email from %s', 'freelance-studio' ),
            $business_name
        );

        $message = '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; max-width: 500px; margin: 0 auto; padding: 40px 20px;">';
        $message .= '<div style="text-align: center; margin-bottom: 30px;">';
        $message .= '<div style="width: 60px; height: 60px; background: linear-gradient(135deg, #1FBBA6, #2BA891); border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;">';
        $message .= '<span style="color: #fff; font-size: 28px;">&#10003;</span>';
        $message .= '</div>';
        $message .= '<h2 style="color: #1F2937; margin: 0 0 8px;">' . __( 'Email Delivery Working!', 'freelance-studio' ) . '</h2>';
        $message .= '<p style="color: #6B7280; margin: 0;">' . __( 'Your Freelance Studio email delivery is configured correctly.', 'freelance-studio' ) . '</p>';
        $message .= '</div>';

        $provider = get_option( 'fs_email_delivery_provider', '' );
        $provider_label = '';
        switch ( $provider ) {
            case 'brevo':
                $provider_label = 'Brevo';
                break;
            case 'postmark':
                $provider_label = 'Postmark';
                break;
            case 'smtp_plugin':
                $provider_label = __( 'SMTP Plugin', 'freelance-studio' );
                break;
            default:
                $provider_label = __( 'WordPress Default', 'freelance-studio' );
        }

        $message .= '<div style="background: #F9FAFB; border-radius: 8px; padding: 20px; margin-top: 20px;">';
        $message .= '<table style="width: 100%; font-size: 14px; color: #4B5563;">';
        $message .= '<tr><td style="padding: 6px 0; color: #9CA3AF;">' . __( 'Provider', 'freelance-studio' ) . '</td><td style="padding: 6px 0; text-align: right; font-weight: 600;">' . esc_html( $provider_label ) . '</td></tr>';
        $message .= '<tr><td style="padding: 6px 0; color: #9CA3AF;">' . __( 'Sent at', 'freelance-studio' ) . '</td><td style="padding: 6px 0; text-align: right;">' . wp_date( 'M j, Y g:i A' ) . '</td></tr>';
        $message .= '<tr><td style="padding: 6px 0; color: #9CA3AF;">' . __( 'From', 'freelance-studio' ) . '</td><td style="padding: 6px 0; text-align: right;">' . esc_html( $business_name ) . '</td></tr>';
        $message .= '</table>';
        $message .= '</div>';
        $message .= '</div>';

        $headers = array( 'Content-Type: text/html; charset=UTF-8' );

        $from_email = get_option( 'fs_business_email', get_option( 'admin_email' ) );
        $from_name  = $business_name;
        if ( ! empty( $from_email ) ) {
            $headers[] = 'From: ' . $from_name . ' <' . $from_email . '>';
        }

        $sent = wp_mail( $to_email, $subject, $message, $headers );

        if ( $sent ) {
            return true;
        }

        return new WP_Error( 'send_failed', __( 'Failed to send test email. Check your server error logs for details.', 'freelance-studio' ) );
    }

    /**
     * Get the current delivery status information
     *
     * @return array
     */
    public static function get_status() {
        $provider   = get_option( 'fs_email_delivery_provider', '' );
        $api_key    = get_option( 'fs_email_delivery_api_key', '' );
        $setup_complete = get_option( 'fs_email_delivery_setup_complete', '0' );
        $last_test  = get_option( 'fs_email_delivery_last_test', '' );

        return array(
            'provider'       => $provider,
            'has_api_key'    => ! empty( $api_key ),
            'setup_complete' => $setup_complete === '1',
            'last_test'      => $last_test,
            'provider_label' => self::get_provider_label( $provider ),
        );
    }

    /**
     * Get human-readable provider label
     */
    public static function get_provider_label( $provider ) {
        switch ( $provider ) {
            case 'brevo':
                return 'Brevo';
            case 'postmark':
                return 'Postmark';
            case 'smtp_plugin':
                return __( 'External SMTP Plugin', 'freelance-studio' );
            default:
                return __( 'Not configured', 'freelance-studio' );
        }
    }

    /**
     * Parse email headers into components
     */
    private static function parse_headers( $headers ) {
        $parsed = array(
            'from_email'   => '',
            'from_name'    => '',
            'reply_to'     => '',
            'content_type' => 'text/plain',
            'cc'           => array(),
        );

        if ( empty( $headers ) ) {
            return $parsed;
        }

        if ( ! is_array( $headers ) ) {
            $headers = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
        }

        foreach ( $headers as $header ) {
            $header = trim( $header );
            if ( empty( $header ) ) {
                continue;
            }

            list( $name, $value ) = array_pad( explode( ':', $header, 2 ), 2, '' );
            $name  = strtolower( trim( $name ) );
            $value = trim( $value );

            switch ( $name ) {
                case 'from':
                    if ( preg_match( '/^(.+?)\s*<(.+?)>$/', $value, $matches ) ) {
                        $parsed['from_name']  = trim( $matches[1], ' "' );
                        $parsed['from_email'] = $matches[2];
                    } else {
                        $parsed['from_email'] = $value;
                    }
                    break;
                case 'reply-to':
                    $parsed['reply_to'] = $value;
                    break;
                case 'content-type':
                    $parsed['content_type'] = $value;
                    break;
                case 'cc':
                    $parsed['cc'][] = $value;
                    break;
            }
        }

        return $parsed;
    }

    /**
     * Extract plain email from a "Name <email>" format
     */
    private static function extract_email( $value ) {
        if ( preg_match( '/<(.+?)>/', $value, $matches ) ) {
            return trim( $matches[1] );
        }
        return trim( $value );
    }
}
