<?php
/**
 * Admin: support ticket form (Fluent Support on maca.se).
 *
 * @package Maca_Menu_List_Pro
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/pro/support.php';

class Maca_MenuList_Pro_Admin_Support {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'register_menu'), 98);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_maca_menulist_submit_support', array($this, 'ajax_submit'));
    }

    /**
     * Register support submenu.
     */
    public function register_menu() {
        add_submenu_page(
            'maca-restu',
            __('Support', 'maca-restu-pro'),
            __('Support', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-support',
            array($this, 'render_page')
        );
    }

    /**
     * @param string $hook Hook suffix.
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-support') {
            return;
        }

        wp_enqueue_script(
            'maca-menulist-pro-support',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/pro-support.js',
            array('jquery'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_localize_script(
            'maca-menulist-pro-support',
            'macaMenulistProSupport',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('maca_menulist_support'),
                'strings' => array(
                    'sending'    => __('Skickar…', 'maca-restu-pro'),
                    'success'    => __('Tack! Ditt ärende har skickats. Vi svarar på e-postadressen ovan — läs svaret i inkorgen (kolla även skräppost).', 'maca-restu-pro'),
                    'error'      => __('Något gick fel. Försök igen eller maila support@maca.se.', 'maca-restu-pro'),
                    'validation' => __('Fyll i ämne, meddelande och e-post.', 'maca-restu-pro'),
                ),
            )
        );
    }

    /**
     * AJAX: submit support ticket.
     */
    public function ajax_submit() {
        if (!maca_menulist_user_can_manage_plugin()) {
            wp_send_json_error(array('message' => __('Permission denied.', 'maca-restu-pro')), 403);
        }

        check_ajax_referer('maca_menulist_support', 'nonce');

        $subject = isset($_POST['subject']) ? sanitize_text_field(wp_unslash($_POST['subject'])) : '';
        $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
        $email   = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
        $include = !empty($_POST['include_system_info']);

        if ($include) {
            $message = trim($message) . "\n\n" . Maca_MenuList_Pro_Support::build_system_info_block();
        }

        $result = Maca_MenuList_Pro_Support::submit_ticket(
            array(
                'subject' => $subject,
                'message' => $message,
                'email'   => $email,
                'name'    => $name,
            )
        );

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }

        wp_send_json_success(
            array(
                'message' => __('Tack! Ditt ärende har skickats. Vi svarar på e-postadressen ovan — läs svaret i inkorgen (kolla även skräppost).', 'maca-restu-pro'),
            )
        );
    }

    /**
     * Render support page.
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $user       = wp_get_current_user();
        $user_name  = $user instanceof WP_User ? $user->display_name : '';
        $user_email = $user instanceof WP_User ? $user->user_email : '';
        $portal_url = apply_filters('maca_menulist_support_portal_url', 'https://maca.se/restu-pro/support/');

        ?>
        <div class="wrap maca-pro-support-wrap">
            <h1><?php esc_html_e('Support', 'maca-restu-pro'); ?></h1>

            <p class="description">
                <?php esc_html_e('Skicka ett supportärende till Maca Development. Vi svarar på e-postadressen nedan — du behöver inte logga in på maca.se.', 'maca-restu-pro'); ?>
            </p>

            <div class="maca-pro-support-grid" style="display:flex;gap:24px;flex-wrap:wrap;margin-top:20px;align-items:flex-start;">
                <div class="card" style="flex:1;min-width:320px;max-width:640px;padding:20px;">
                    <form id="maca-support-form" novalidate>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row">
                                    <label for="maca-support-name"><?php esc_html_e('Namn', 'maca-restu-pro'); ?></label>
                                </th>
                                <td>
                                    <input type="text" class="regular-text" id="maca-support-name" name="name" value="<?php echo esc_attr($user_name); ?>" required>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="maca-support-email"><?php esc_html_e('E-post', 'maca-restu-pro'); ?></label>
                                </th>
                                <td>
                                    <input type="email" class="regular-text" id="maca-support-email" name="email" value="<?php echo esc_attr($user_email); ?>" required>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="maca-support-subject"><?php esc_html_e('Ämne', 'maca-restu-pro'); ?></label>
                                </th>
                                <td>
                                    <input type="text" class="large-text" id="maca-support-subject" name="subject" required>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="maca-support-body"><?php esc_html_e('Meddelande', 'maca-restu-pro'); ?></label>
                                </th>
                                <td>
                                    <textarea class="large-text" rows="8" id="maca-support-body" name="message" required></textarea>
                                    <p class="description">
                                        <?php esc_html_e('Beskriv problemet eller frågan så tydligt du kan.', 'maca-restu-pro'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Systeminfo', 'maca-restu-pro'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" id="maca-support-include-info" name="include_system_info" value="1" checked>
                                        <?php esc_html_e('Bifoga webbadress, pluginversion och licensstatus (rekommenderas)', 'maca-restu-pro'); ?>
                                    </label>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <button type="submit" class="button button-primary" id="maca-support-submit">
                                <?php esc_html_e('Skicka ärende', 'maca-restu-pro'); ?>
                            </button>
                        </p>

                        <p class="description" id="maca-support-status" aria-live="polite"></p>
                    </form>
                </div>

                <div class="card" style="flex:0 1 280px;padding:20px;">
                    <h2 style="margin-top:0;"><?php esc_html_e('Mer hjälp', 'maca-restu-pro'); ?></h2>
                    <ul style="list-style:disc;margin-left:20px;">
                        <li>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-guide')); ?>">
                                <?php esc_html_e('Guide i wp-admin', 'maca-restu-pro'); ?>
                            </a>
                        </li>
                        <?php if ($portal_url !== '') : ?>
                        <li>
                            <a href="<?php echo esc_url($portal_url); ?>" target="_blank" rel="noopener noreferrer">
                                <?php esc_html_e('FAQ & dokumentation (maca.se)', 'maca-restu-pro'); ?>
                            </a>
                        </li>
                        <?php endif; ?>
                        <li>
                            <a href="mailto:support@maca.se?subject=<?php echo rawurlencode('maca Restu Pro support'); ?>">
                                support@maca.se
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <?php
    }
}
