<?php

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

add_action( 'admin_post_tw_lem_send_support_email', 'tw_lem_handle_support_form' );
add_action( 'admin_post_nopriv_tw_lem_send_support_email', 'tw_lem_handle_support_form' );
add_action( 'admin_enqueue_scripts', 'tw_lem_support_page_styles' );

/**
 * Enqueue support page CSS.
 */
function tw_lem_support_page_styles( $hook ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

    if ( ! $page || strpos( $page, 'tw-lem' ) !== 0 ) {
        return;
    }

    wp_enqueue_style(
        'tw-lem-support',
        TW_LEM_PLUGIN_URL . 'assets/css/support-page.css',
        array(),
        TW_LEM_PLUGIN_VERSION
    );
}

/**
 * Render the Rate Us sticky banner.
 */
function tw_lem_render_rate_us_banner() {
    ?>
    <div class="tw-lem-review-us">
        <p>
            <span class="dashicons dashicons-star-filled" style="vertical-align: middle;"></span>
            <?php
            echo wp_kses_post(
                sprintf(
                    'Your feedback helps us improve. <a href="%s" target="_blank" rel="noopener noreferrer">Rate Us</a>',
                    esc_url( 'https://wordpress.org/support/plugin/tw-link-expiration-manager/reviews/' )
                )
            );
            ?>
        </p>
    </div>
    <?php
}

/**
 * Handle support form submission.
 */
function tw_lem_handle_support_form() {
    if ( ! isset( $_POST['tw_lem_support_nonce'] ) ||
        ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tw_lem_support_nonce'] ) ), 'tw_lem_support_form' ) ) {
        wp_die( esc_html__( 'Security check failed. Please try again.', 'tw-link-expiration-manager' ) );
    }

    $name    = isset( $_POST['support_name'] ) ? sanitize_text_field( wp_unslash( $_POST['support_name'] ) ) : '';
    $email   = isset( $_POST['support_email'] ) ? sanitize_email( wp_unslash( $_POST['support_email'] ) ) : '';
    $website = isset( $_POST['support_website'] ) ? esc_url_raw( wp_unslash( $_POST['support_website'] ) ) : '';
    $issue   = isset( $_POST['support_issue'] ) ? sanitize_textarea_field( wp_unslash( $_POST['support_issue'] ) ) : '';

    $errors = array();

    if ( empty( $name ) ) {
        $errors[] = 'name';
    }

    if ( empty( $email ) || ! is_email( $email ) ) {
        $errors[] = 'email';
    }

    if ( empty( $issue ) ) {
        $errors[] = 'issue';
    }

    if ( ! empty( $errors ) ) {
        $error_params = implode( ',', $errors );
        wp_safe_redirect(
            add_query_arg(
                array(
                    'support_status' => 'error',
                    'fields'         => $error_params,
                ),
                wp_get_referer()
            )
        );
        exit;
    }

    $support_email = 'pluginsupport@technologywisdom.com';
    $site_name     = get_bloginfo( 'name' );
    $site_url      = get_bloginfo( 'url' );
    $plugin_name   = tw_lem_get_plugin_name();

    $subject = sprintf(
        '[%s] Support Request via %s',
        $site_name,
        $plugin_name
    );

    $message = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>' . esc_html__( 'Support Request', 'tw-link-expiration-manager' ) . '</title>
    </head>
    <body style="margin: 0; padding: 20px; background-color: #f0f4f8; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;">
        <div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <div style="background: linear-gradient(135deg, #1460ac 0%, #1e7ecc 100%); padding: 30px; text-align: center;">
                <h1 style="color: #ffffff; font-size: 22px; margin: 0; font-weight: 600;">' . esc_html__( 'New Support Request', 'tw-link-expiration-manager' ) . '</h1>
                <p style="color: rgba(255,255,255,0.9); font-size: 14px; margin: 8px 0 0 0;">' . esc_html__( 'A user has submitted a support ticket from your plugin', 'tw-link-expiration-manager' ) . '</p>
            </div>
            <div style="padding: 30px;">
                <div style="margin-bottom: 25px;">
                    <h2 style="font-size: 16px; font-weight: 700; color: #1460ac; margin: 0 0 12px 0; padding-bottom: 8px; border-bottom: 2px solid #e8f0fe;">' . esc_html__( 'Submitter Information', 'tw-link-expiration-manager' ) . '</h2>
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="padding: 6px 12px 6px 0; color: #64748b; font-size: 13px; font-weight: 500; width: 100px; vertical-align: top;">' . esc_html__( 'Name:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 6px 0; color: #1e293b; font-size: 14px; font-weight: 600;">' . esc_html( $name ) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 6px 12px 6px 0; color: #64748b; font-size: 13px; font-weight: 500; vertical-align: top;">' . esc_html__( 'Email:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 6px 0; color: #1e293b; font-size: 14px;"><a href="mailto:' . esc_attr( $email ) . '" style="color: #1460ac; text-decoration: none;">' . esc_html( $email ) . '</a></td>
                        </tr>';

    if ( ! empty( $website ) ) {
        $message .= '
                        <tr>
                            <td style="padding: 6px 12px 6px 0; color: #64748b; font-size: 13px; font-weight: 500; vertical-align: top;">' . esc_html__( 'Website:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 6px 0; color: #1e293b; font-size: 14px;"><a href="' . esc_url( $website ) . '" style="color: #1460ac; text-decoration: none;">' . esc_html( $website ) . '</a></td>
                        </tr>';
    }

    $message .= '
                        <tr>
                            <td style="padding: 6px 12px 6px 0; color: #64748b; font-size: 13px; font-weight: 500; vertical-align: top;">' . esc_html__( 'Plugin:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 6px 0; color: #1e293b; font-size: 14px; font-weight: 600;">' . esc_html( $plugin_name ) . '</td>
                        </tr>
                    </table>
                </div>
                <div style="margin-bottom: 25px;">
                    <h2 style="font-size: 16px; font-weight: 700; color: #1460ac; margin: 0 0 12px 0; padding-bottom: 8px; border-bottom: 2px solid #e8f0fe;">' . esc_html__( 'Issue Reported', 'tw-link-expiration-manager' ) . '</h2>
                    <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px;">
                        <p style="color: #1e293b; font-size: 14px; line-height: 1.6; margin: 0; white-space: pre-wrap;">' . esc_html( $issue ) . '</p>
                    </div>
                </div>
                <div style="margin-bottom: 25px;">
                    <h2 style="font-size: 16px; font-weight: 700; color: #1460ac; margin: 0 0 12px 0; padding-bottom: 8px; border-bottom: 2px solid #e8f0fe;">' . esc_html__( 'System Information', 'tw-link-expiration-manager' ) . '</h2>
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="padding: 8px 12px 8px 0; color: #64748b; font-size: 13px; font-weight: 500; width: 170px; vertical-align: top; border-bottom: 1px solid #f1f5f9;">' . esc_html__( 'Site URL:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 8px 0; color: #1e293b; font-size: 13px; font-weight: 600; border-bottom: 1px solid #f1f5f9;">' . esc_html( $site_url ) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px 8px 0; color: #64748b; font-size: 13px; font-weight: 500; border-bottom: 1px solid #f1f5f9;">' . esc_html__( 'Site Name:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 8px 0; color: #1e293b; font-size: 13px; font-weight: 600; border-bottom: 1px solid #f1f5f9;">' . esc_html( $site_name ) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px 8px 0; color: #64748b; font-size: 13px; font-weight: 500; border-bottom: 1px solid #f1f5f9;">' . esc_html__( 'Plugin Version:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 8px 0; color: #1e293b; font-size: 13px; font-weight: 600; border-bottom: 1px solid #f1f5f9;">' . esc_html( TW_LEM_PLUGIN_VERSION ) . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 8px 12px 8px 0; color: #64748b; font-size: 13px; font-weight: 500; border-bottom: 1px solid #f1f5f9;">' . esc_html__( 'WordPress Version:', 'tw-link-expiration-manager' ) . '</td>
                            <td style="padding: 8px 0; color: #1e293b; font-size: 13px; font-weight: 600; border-bottom: 1px solid #f1f5f9;">' . esc_html( get_bloginfo( 'version' ) ) . '</td>
                        </tr>
                    </table>
                </div>
            </div>
            <div style="background: #f8fafc; padding: 20px 30px; border-top: 1px solid #e2e8f0; text-align: center;">
                <p style="color: #94a3b8; font-size: 12px; margin: 0;">' . sprintf(
                    /* translators: %s: Site name */
                    esc_html__( 'This email was sent from %s via TW Link Expiration Manager', 'tw-link-expiration-manager' ),
                    '<strong>' . esc_html( $site_name ) . '</strong>'
                ) . '</p>
            </div>
        </div>
    </body>
    </html>';

    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        "From: {$site_name} <{$support_email}>",
        "Reply-To: {$name} <{$email}>",
    );

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

    if ( $sent ) {
        wp_safe_redirect( add_query_arg( 'support_status', 'success', wp_get_referer() ) );
    } else {
        wp_safe_redirect( add_query_arg( 'support_status', 'failed', wp_get_referer() ) );
    }
    exit;
}

/**
 * Render the support page.
 */
function tw_lem_support_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'tw-link-expiration-manager' ) );
    }

    $current_user = wp_get_current_user();
    $user_name    = $current_user->display_name;
    $user_email   = $current_user->user_email;
    $site_url     = get_bloginfo( 'url' );

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $status = isset( $_GET['support_status'] ) ? sanitize_text_field( wp_unslash( $_GET['support_status'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $fields = isset( $_GET['fields'] ) ? explode( ',', sanitize_text_field( wp_unslash( $_GET['fields'] ) ) ) : array();
    ?>
    <div class="wrap tw-lem-wrap">
        <h1><?php esc_html_e( 'Support', 'tw-link-expiration-manager' ); ?></h1>

        <?php tw_lem_render_rate_us_banner(); ?>

        <?php if ( 'success' === $status ) : ?>
            <div class="notice notice-success is-dismissible" style="margin: 15px 0;">
                <p>
                    <strong><?php esc_html_e( 'Email Sent Successfully!', 'tw-link-expiration-manager' ); ?></strong><br>
                    <?php esc_html_e( 'Thank you for contacting us. Further support will be provided via email.', 'tw-link-expiration-manager' ); ?>
                </p>
            </div>
        <?php endif; ?>

        <?php if ( 'failed' === $status ) : ?>
            <div class="notice notice-error is-dismissible" style="margin: 15px 0;">
                <p>
                    <strong><?php esc_html_e( 'Email Failed to Send', 'tw-link-expiration-manager' ); ?></strong><br>
                    <?php esc_html_e( 'There was an issue sending your email. Please try again or contact us directly at pluginsupport@technologywisdom.com', 'tw-link-expiration-manager' ); ?>
                </p>
            </div>
        <?php endif; ?>

        <?php if ( 'error' === $status ) : ?>
            <div class="notice notice-error is-dismissible" style="margin: 15px 0;">
                <p>
                    <strong><?php esc_html_e( 'Please fill in all required fields.', 'tw-link-expiration-manager' ); ?></strong>
                </p>
            </div>
        <?php endif; ?>

        <div class="tw-lem-support-form-section">
            <h2><?php esc_html_e( 'Submit a Support Request', 'tw-link-expiration-manager' ); ?></h2>

            <div class="tw-lem-support-form-card">
                <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <input type="hidden" name="action" value="tw_lem_send_support_email">
                    <?php wp_nonce_field( 'tw_lem_support_form', 'tw_lem_support_nonce' ); ?>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="support_name">
                                    <?php esc_html_e( 'Name', 'tw-link-expiration-manager' ); ?>
                                    <span class="required">*</span>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    name="support_name"
                                    id="support_name"
                                    class="regular-text <?php echo in_array( 'name', $fields, true ) ? 'tw-lem-field-error' : ''; ?>"
                                    value="<?php echo esc_attr( $user_name ); ?>"
                                    placeholder="<?php esc_attr_e( 'Your full name', 'tw-link-expiration-manager' ); ?>"
                                    required
                                >
                                <?php if ( in_array( 'name', $fields, true ) ) : ?>
                                    <p class="tw-lem-field-error-message"><?php esc_html_e( 'Please enter your name.', 'tw-link-expiration-manager' ); ?></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="support_email">
                                    <?php esc_html_e( 'Email', 'tw-link-expiration-manager' ); ?>
                                    <span class="required">*</span>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="email"
                                    name="support_email"
                                    id="support_email"
                                    class="regular-text <?php echo in_array( 'email', $fields, true ) ? 'tw-lem-field-error' : ''; ?>"
                                    value="<?php echo esc_attr( $user_email ); ?>"
                                    placeholder="<?php esc_attr_e( 'your@email.com', 'tw-link-expiration-manager' ); ?>"
                                    required
                                >
                                <?php if ( in_array( 'email', $fields, true ) ) : ?>
                                    <p class="tw-lem-field-error-message"><?php esc_html_e( 'Please enter a valid email address.', 'tw-link-expiration-manager' ); ?></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="support_website">
                                    <?php esc_html_e( 'Website URL', 'tw-link-expiration-manager' ); ?>
                                </label>
                                <span class="required">*</span>
                            </th>
                            <td>
                                <input
                                    type="url"
                                    name="support_website"
                                    id="support_website"
                                    class="regular-text"
                                    readonly
                                    required
                                    value="<?php echo esc_url( $site_url ); ?>"
                                    placeholder="<?php esc_attr_e( 'https://your-site.com', 'tw-link-expiration-manager' ); ?>"
                                >
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="support_issue">
                                    <?php esc_html_e( 'Report Issue', 'tw-link-expiration-manager' ); ?>
                                    <span class="required">*</span>
                                </label>
                            </th>
                            <td>
                                <textarea
                                    name="support_issue"
                                    id="support_issue"
                                    class="large-text <?php echo in_array( 'issue', $fields, true ) ? 'tw-lem-field-error' : ''; ?>"
                                    rows="10"
                                    placeholder="<?php esc_attr_e( 'Please describe your issue in detail. What feature were you trying to use? What happened? What did you expect to happen?', 'tw-link-expiration-manager' ); ?>"
                                    required
                                ></textarea>
                                <?php if ( in_array( 'issue', $fields, true ) ) : ?>
                                    <p class="tw-lem-field-error-message"><?php esc_html_e( 'Please describe your issue.', 'tw-link-expiration-manager' ); ?></p>
                                <?php endif; ?>
                                <p class="description">
                                    <span class="dashicons dashicons-info-outline"></span>
                                    <?php esc_html_e( 'Include as much detail as possible. Error messages, and steps to reproduce help us resolve your issue faster.', 'tw-link-expiration-manager' ); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"></th>
                            <td>
                                <label class="tw-lem-consent-label <?php echo in_array( 'consent', $fields, true ) ? 'tw-lem-consent-error' : ''; ?>">
                                    <input
                                        type="checkbox"
                                        name="support_consent"
                                        id="support_consent"
                                        value="1"
                                        required
                                    >
                                    <span><?php esc_html_e( 'I agree to send my support request along with my site information (site URL, WordPress version, plugin version, and admin email) to the plugin developer for support purposes.', 'tw-link-expiration-manager' ); ?></span>
                                </label>
                                <?php if ( in_array( 'consent', $fields, true ) ) : ?>
                                    <p class="tw-lem-field-error-message"><?php esc_html_e( 'You must agree to the terms before submitting.', 'tw-link-expiration-manager' ); ?></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" class="button button-primary button-large">
                            <?php esc_html_e( 'Submit Support Request', 'tw-link-expiration-manager' ); ?>
                        </button>
                    </p>
                </form>
            </div>
        </div>
    </div>
    <?php
}
