<?php
/**
 * Support ticket client (maca.se Fluent Support via license server REST API).
 *
 * @package Maca_Menu_List_Pro
 */

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

class Maca_MenuList_Pro_Support {

    /**
     * Support API URL on maca.se.
     *
     * @return string
     */
    public static function get_api_url() {
        return untrailingslashit(
            apply_filters(
                'maca_menulist_support_api_url',
                'https://maca.se/wp-json/maca-menulist/v1/support'
            )
        );
    }

    /**
     * Optional shared secret (must match MACA_MENULIST_LS_SUPPORT_SECRET on maca.se).
     *
     * @return string
     */
    public static function get_shared_secret() {
        if (defined('MACA_MENULIST_SUPPORT_SECRET')) {
            return (string) MACA_MENULIST_SUPPORT_SECRET;
        }

        return (string) apply_filters('maca_menulist_support_secret', '');
    }

    /**
     * Build diagnostic footer appended to ticket messages.
     *
     * @return string
     */
    public static function build_system_info_block() {
        global $wp_version;

        $license = Maca_MenuList_License::instance()->get_stored_license();
        $lines   = array(
            '---',
            'Site: ' . untrailingslashit(home_url()),
            'Plugin: maca Restu Pro ' . MACA_MENULIST_VERSION,
            'WordPress: ' . (string) $wp_version,
            'PHP: ' . PHP_VERSION,
            'Locale: ' . get_locale(),
        );

        if (!empty($license['license_key'])) {
            $masked = self::mask_license_key($license['license_key']);
            $lines[] = 'License: ' . $masked . (!empty($license['status']) ? ' (' . $license['status'] . ')' : '');
        } else {
            $lines[] = 'License: none';
        }

        if (!empty($license['plan'])) {
            $lines[] = 'Plan: ' . $license['plan'];
        }

        return implode("\n", $lines);
    }

    /**
     * @param string $key License key.
     * @return string
     */
    private static function mask_license_key($key) {
        $key = trim((string) $key);
        if (strlen($key) <= 8) {
            return str_repeat('*', strlen($key));
        }

        return substr($key, 0, 4) . str_repeat('*', max(4, strlen($key) - 8)) . substr($key, -4);
    }

    /**
     * Submit a support ticket to maca.se.
     *
     * @param array<string, string> $args subject, message, email, name.
     * @return true|WP_Error
     */
    public static function submit_ticket(array $args) {
        $subject = isset($args['subject']) ? sanitize_text_field($args['subject']) : '';
        $message = isset($args['message']) ? sanitize_textarea_field($args['message']) : '';
        $email   = isset($args['email']) ? sanitize_email($args['email']) : '';
        $name    = isset($args['name']) ? sanitize_text_field($args['name']) : '';

        if ($subject === '' || $message === '' || $email === '' || !is_email($email)) {
            return new WP_Error('invalid_input', __('Subject, message, and a valid email are required.', 'maca-restu-pro'));
        }

        $body = array(
            'subject'  => $subject,
            'message'  => $message,
            'email'    => $email,
            'name'     => $name,
            'site_url' => untrailingslashit(home_url()),
        );

        $secret = self::get_shared_secret();
        if ($secret !== '') {
            $body['support_secret'] = $secret;
        }

        $license = Maca_MenuList_License::instance()->get_stored_license();
        if (!empty($license['license_key'])) {
            $body['license_key'] = $license['license_key'];
        }

        $response = wp_remote_post(
            self::get_api_url(),
            array(
                'timeout' => 20,
                'headers' => array(
                    'Content-Type' => 'application/json; charset=utf-8',
                    'Accept'       => 'application/json',
                ),
                'body'    => wp_json_encode($body),
            )
        );

        if (is_wp_error($response)) {
            return self::submit_ticket_via_email($args);
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $raw  = wp_remote_retrieve_body($response);
        $data = json_decode($raw, true);

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

        // maca.se endpoint not deployed yet — fall back to direct e-mail from this site.
        if ($code === 404) {
            $email_result = self::submit_ticket_via_email($args);
            if (!is_wp_error($email_result)) {
                return true;
            }
        }

        // Server reachable but ticket delivery failed — try e-mail as last resort.
        if ($code >= 500) {
            $email_result = self::submit_ticket_via_email($args);
            if (!is_wp_error($email_result)) {
                return true;
            }
        }

        $message_text = is_array($data) && !empty($data['message'])
            ? (string) $data['message']
            : __('Support request failed. Please try again or email support@maca.se.', 'maca-restu-pro');

        return new WP_Error('support_failed', $message_text, array('status' => $code));
    }

    /**
     * Send support request directly by e-mail (fallback when maca.se API is unavailable).
     *
     * @param array<string, string> $args subject, message, email, name.
     * @return true|WP_Error
     */
    public static function submit_ticket_via_email(array $args) {
        $subject  = isset($args['subject']) ? sanitize_text_field($args['subject']) : '';
        $message  = isset($args['message']) ? sanitize_textarea_field($args['message']) : '';
        $email    = isset($args['email']) ? sanitize_email($args['email']) : '';
        $name     = isset($args['name']) ? sanitize_text_field($args['name']) : '';
        $site_url = untrailingslashit(home_url());

        if ($subject === '' || $message === '' || $email === '' || !is_email($email)) {
            return new WP_Error('invalid_input', __('Subject, message, and a valid email are required.', 'maca-restu-pro'));
        }

        $to = sanitize_email(
            apply_filters('maca_menulist_support_fallback_email', 'support@maca.se')
        );
        if (!is_email($to)) {
            $to = 'support@maca.se';
        }

        $lines = array(
            __('New support request from maca Restu Pro', 'maca-restu-pro'),
            '',
            sprintf(
                /* translators: 1: sender name, 2: sender email */
                __('From: %1$s <%2$s>', 'maca-restu-pro'),
                $name !== '' ? $name : $email,
                $email
            ),
            sprintf(
                /* translators: %s: site URL */
                __('Site: %s', 'maca-restu-pro'),
                $site_url
            ),
            '',
            __('Message:', 'maca-restu-pro'),
            $message,
            '',
            '---',
            sprintf(
                /* translators: %s: date and time */
                __('Sent via Restu Pro support form at %s', 'maca-restu-pro'),
                wp_date('Y-m-d H:i:s')
            ),
        );

        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'Reply-To: ' . ($name !== '' ? sprintf('%1$s <%2$s>', $name, $email) : $email),
        );

        if (!wp_mail($to, '[Restu Pro] ' . $subject, implode("\n", $lines), $headers)) {
            return new WP_Error(
                'email_failed',
                __('Could not send support e-mail. Please contact support@maca.se directly.', 'maca-restu-pro')
            );
        }

        return true;
    }
}
