<?php
/**
 * PRO Support page.
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/admin/partials/pages
 */

if (!defined('WPINC')) {
    die;
}

// Check paid plan status
$is_pro = ttswp_has_paid_plan();
if (!$is_pro) {
    wp_die(__('Access denied. This page is only available for paid plan users.', 'text-to-speech-tts'));
}

// Get current user info
$current_user = wp_get_current_user();
$user_email = (string) ($current_user->user_email ?? '');
$user_first_name = (string) ($current_user->first_name ?? '');
$user_last_name = (string) ($current_user->last_name ?? '');
$user_login = (string) ($current_user->user_login ?? '');
$site_url = (string) get_site_url();

// Capture mail errors
add_action('wp_mail_failed', function($error) {
    error_log('wp_mail_failed error: ' . print_r($error, true));
});

// Handle form submission
$form_submitted = false;
$form_toast_message = '';
$form_toast_type = '';
if (isset($_POST['submit_pro_help']) && wp_verify_nonce(sanitize_key(wp_unslash($_POST['pro_help_nonce'])), 'pro_help_form')) {
    $first_name = sanitize_text_field(wp_unslash($_POST['first_name'] ?? ''));
    $email = sanitize_email(wp_unslash($_POST['email'] ?? ''));
    $website = esc_url_raw(wp_unslash($_POST['website'] ?? ''));
    $wp_username = sanitize_text_field(wp_unslash($_POST['wp_username'] ?? ''));
    $wp_password = sanitize_text_field(wp_unslash($_POST['wp_password'] ?? ''));
    $subject = sanitize_text_field(wp_unslash($_POST['subject'] ?? ''));
    $message = sanitize_textarea_field(wp_unslash($_POST['message'] ?? ''));

    if (empty($first_name) || empty($email) || empty($subject) || empty($message)) {
        $form_toast_message = __('Please fill in all required fields.', 'text-to-speech-tts');
        $form_toast_type = 'error';
    } else {
        $to = 'plugin-support@mementor.no';
        $email_subject = 'Pro Plugin Support - ' . $subject;

        $email_message = "From: " . $first_name . "\n";
        $email_message .= "Email: " . $email . "\n";
        $email_message .= "Subject: Pro Plugin Support - " . $subject . "\n\n";
        $email_message .= "Message:\n" . $message . "\n\n";
        $email_message .= "Website URL: " . $website . "\n";

        $credentials_line = "Username / Password: ";
        $credentials_line .= !empty($wp_username) ? $wp_username : "[Not provided]";
        $credentials_line .= " / ";
        $credentials_line .= !empty($wp_password) ? $wp_password : "[Not provided]";
        $email_message .= $credentials_line . "\n";

        $email_message .= "WordPress Version: " . get_bloginfo('version') . "\n";
        $email_message .= "TTS FREE Version: " . MEMENTOR_TTS_VERSION . "\n";
        $email_message .= "TTS Plan: " . (ttswp_has_paid_plan() ? 'Paid' : 'Free') . "\n";

        $from_email = get_option('admin_email');
        if (strpos($from_email, '.local') !== false || strpos($from_email, 'localhost') !== false || !filter_var($from_email, FILTER_VALIDATE_EMAIL)) {
            $fluent_settings = get_option('fluentmail-settings');
            if ($fluent_settings && isset($fluent_settings['sender_email']) && filter_var($fluent_settings['sender_email'], FILTER_VALIDATE_EMAIL)) {
                $from_email = $fluent_settings['sender_email'];
            } else {
                $from_email = 'noreply@mementor.no';
            }
        }

        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . $from_email . '>',
            'Reply-To: ' . $first_name . ' <' . $email . '>'
        );

        $email_sent = wp_mail($to, $email_subject, $email_message, $headers);

        if ($email_sent) {
            $form_submitted = true;
            $form_toast_message = __('Your support request has been submitted successfully. Our PRO support team will get back to you within 24 hours.', 'text-to-speech-tts');
            $form_toast_type = 'success';

            // Send confirmation to submitter
            $confirmation_subject = 'Confirmation: ' . $email_subject;
            $confirmation_message = "Thank you for contacting Mementor PRO Support.\n\nWe have received your support request and will respond within 24 hours.\n\nYour message:\n------------------------\n" . $message . "\n------------------------\n\nBest regards,\nMementor Support Team";
            $confirmation_headers = array(
                'Content-Type: text/plain; charset=UTF-8',
                'From: ' . get_bloginfo('name') . ' <' . $from_email . '>',
                'Reply-To: Mementor Support <plugin-support@mementor.no>'
            );
            wp_mail($email, $confirmation_subject, $confirmation_message, $confirmation_headers);
        } else {
            $form_toast_message = __('There was an error sending your support request. Please try again or contact us directly at plugin-support@mementor.no', 'text-to-speech-tts');
            $form_toast_type = 'error';
        }
    }
}
?>

<?php
$tts_page_title = __('PRO Support', 'text-to-speech-tts');
$tts_topbar_actions = '<button type="submit" form="pro-help-form" class="tts-btn tts-btn-primary">' . esc_html__('Submit Request', 'text-to-speech-tts') . '</button>';
include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'); ?>

            <div class="tts-support-layout">

            <!-- Support Form -->
            <div class="tts-card">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('PRO Support Request', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('We typically respond within 24 hours', 'text-to-speech-tts'); ?></p>
                </div>

                <form method="post" action="" id="pro-help-form" class="tts-support-form">
                    <?php wp_nonce_field('pro_help_form', 'pro_help_nonce'); ?>

                    <!-- Name & Email -->
                    <div class="tts-support-row tts-support-grid-2">
                        <div class="tts-support-field">
                            <label for="first_name"><?php esc_html_e('First Name', 'text-to-speech-tts'); ?> <span class="tts-required">*</span></label>
                            <input type="text" id="first_name" name="first_name" value="<?php echo esc_attr($form_submitted ? '' : $user_first_name); ?>" required>
                        </div>
                        <div class="tts-support-field">
                            <label for="email"><?php esc_html_e('Email Address', 'text-to-speech-tts'); ?> <span class="tts-required">*</span></label>
                            <input type="email" id="email" name="email" value="<?php echo esc_attr($form_submitted ? '' : $user_email); ?>" required>
                        </div>
                    </div>

                    <!-- System info (read-only) -->
                    <div class="tts-support-row tts-support-grid-5">
                        <div class="tts-support-field">
                            <label><?php esc_html_e('Website', 'text-to-speech-tts'); ?></label>
                            <input type="url" name="website" value="<?php echo esc_attr($site_url); ?>" readonly class="tts-readonly">
                        </div>
                        <div class="tts-support-field">
                            <label><?php esc_html_e('WP', 'text-to-speech-tts'); ?></label>
                            <input type="text" value="<?php echo esc_attr(get_bloginfo('version')); ?>" readonly class="tts-readonly">
                        </div>
                        <div class="tts-support-field">
                            <label><?php esc_html_e('TTS Free', 'text-to-speech-tts'); ?></label>
                            <input type="text" value="<?php echo esc_attr(MEMENTOR_TTS_VERSION); ?>" readonly class="tts-readonly">
                        </div>
                        <div class="tts-support-field">
                            <label><?php esc_html_e('Plan Status', 'text-to-speech-tts'); ?></label>
                            <input type="text" value="<?php echo esc_attr(ttswp_has_paid_plan() ? 'Paid' : 'Free'); ?>" readonly class="tts-readonly">
                        </div>
                    </div>

                    <!-- Optional credentials -->
                    <div class="tts-support-row tts-support-grid-2">
                        <div class="tts-support-field">
                            <label for="wp_username"><?php esc_html_e('WordPress Username', 'text-to-speech-tts'); ?></label>
                            <input type="text" id="wp_username" name="wp_username" value="<?php echo esc_attr($form_submitted ? '' : $user_login); ?>">
                            <span class="tts-support-hint"><?php esc_html_e('Optional — helps us help you faster.', 'text-to-speech-tts'); ?></span>
                        </div>
                        <div class="tts-support-field">
                            <label for="wp_password"><?php esc_html_e('WordPress Password', 'text-to-speech-tts'); ?></label>
                            <input type="password" id="wp_password" name="wp_password" value="">
                            <span class="tts-support-hint"><?php esc_html_e('Optional — helps us help you faster.', 'text-to-speech-tts'); ?></span>
                        </div>
                    </div>

                    <!-- Subject -->
                    <div class="tts-support-row">
                        <div class="tts-support-field">
                            <label for="subject"><?php esc_html_e('Subject', 'text-to-speech-tts'); ?> <span class="tts-required">*</span></label>
                            <input type="text" id="subject" name="subject" value="" required placeholder="<?php esc_attr_e('Brief description of your issue', 'text-to-speech-tts'); ?>">
                        </div>
                    </div>

                    <!-- Message -->
                    <div class="tts-support-row">
                        <div class="tts-support-field">
                            <label for="message"><?php esc_html_e('Message', 'text-to-speech-tts'); ?> <span class="tts-required">*</span></label>
                            <textarea id="message" name="message" rows="6" required placeholder="<?php esc_attr_e('Please describe your issue in detail...', 'text-to-speech-tts'); ?>"></textarea>
                        </div>
                    </div>

                    <input type="hidden" name="submit_pro_help" value="1">
                </form>
            </div>

            <!-- Help info (sidebar column) -->
            <div class="tts-support-sidebar">
                <div class="tts-card">
                    <div class="tts-card-header">
                        <h3 class="tts-card-title"><?php esc_html_e('Support Information', 'text-to-speech-tts'); ?></h3>
                    </div>

                    <div class="tts-support-info-section">
                        <div class="tts-setting-label"><?php esc_html_e('What to Include', 'text-to-speech-tts'); ?></div>
                        <ul class="tts-support-list">
                            <li><?php esc_html_e('Detailed description of the issue', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Steps to reproduce the problem', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Error messages (if any)', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Other active plugins (if relevant)', 'text-to-speech-tts'); ?></li>
                        </ul>
                    </div>

                    <div class="tts-support-info-section">
                        <div class="tts-setting-label"><?php esc_html_e('PRO Support Benefits', 'text-to-speech-tts'); ?></div>
                        <ul class="tts-support-list">
                            <li><?php esc_html_e('Priority response within 24 hours', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Direct access to our development team', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Advanced troubleshooting', 'text-to-speech-tts'); ?></li>
                            <li><?php esc_html_e('Plugin compatibility support', 'text-to-speech-tts'); ?></li>
                        </ul>
                    </div>

                    <div class="tts-support-privacy">
                        <span class="dashicons dashicons-lock"></span>
                        <?php esc_html_e('Your information is transmitted securely. Credentials are only used for troubleshooting.', 'text-to-speech-tts'); ?>
                    </div>
                </div>
            </div>

            </div><!-- /.tts-support-layout -->

            <style>
            /* 3/1 grid layout */
            .tts-support-layout {
                display: grid;
                grid-template-columns: 3fr 1fr;
                gap: 16px;
                align-items: start;
            }

            .tts-support-sidebar .tts-card {
                position: sticky;
                top: 48px;
            }

            .tts-support-row {
                padding-bottom: 16px;
                margin-bottom: 16px;
                border-bottom: 1px solid #f0f0f0;
            }

            .tts-support-row:last-child {
                border-bottom: none;
                margin-bottom: 0;
                padding-bottom: 0;
            }

            .tts-support-grid-2 {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 16px;
            }

            .tts-support-grid-5 {
                display: grid;
                grid-template-columns: 3fr 1fr 1fr 1fr;
                gap: 12px;
            }

            /* Fields */
            .tts-support-field label {
                display: block;
                font-size: 13px;
                font-weight: 500;
                color: var(--tts-text-primary);
                margin-bottom: 4px;
            }

            .tts-support-field input,
            .tts-support-field textarea {
                width: 100% !important;
                max-width: 100% !important;
                box-sizing: border-box;
                font-size: 13px;
                padding: 7px 10px;
                border: var(--tts-border);
                border-radius: var(--tts-radius-sm);
            }

            .tts-support-field input:focus,
            .tts-support-field textarea:focus {
                border-color: var(--tts-purple);
                outline: none;
                box-shadow: 0 0 0 2px var(--tts-purple-bg);
            }

            .tts-readonly {
                background: var(--tts-bg-secondary) !important;
                color: var(--tts-text-secondary) !important;
                cursor: not-allowed;
            }

            .tts-required {
                color: #dc2626;
            }

            .tts-support-hint {
                font-size: 11px;
                color: var(--tts-text-secondary, #757575);
                margin-top: 4px;
                display: block;
            }

            /* Info sections */
            .tts-support-info-section {
                padding: 0 16px 12px;
            }

            .tts-support-info-section .tts-setting-label {
                margin-bottom: 8px;
            }

            .tts-support-list {
                margin: 0;
                padding: 0;
                list-style: none;
            }

            .tts-support-list li {
                position: relative;
                padding-left: 18px;
                margin-bottom: 6px;
                font-size: 13px;
                color: var(--tts-text-secondary, #646970);
                line-height: 1.5;
            }

            .tts-support-list li::before {
                content: '\2713';
                position: absolute;
                left: 0;
                color: var(--tts-purple, #7c3aed);
                font-weight: bold;
            }

            /* Privacy notice */
            .tts-support-privacy {
                padding: 12px 16px;
                border-top: var(--tts-border);
                font-size: 12px;
                color: var(--tts-text-secondary, #646970);
                margin-top: 16px;
            }

            .tts-support-privacy .dashicons {
                font-size: 14px;
                width: 14px;
                height: 14px;
                vertical-align: middle;
                margin-right: 4px;
                color: var(--tts-purple);
            }

            /* Responsive */
            @media screen and (max-width: 1024px) {
                .tts-support-grid-5 {
                    grid-template-columns: 1fr 1fr;
                }
            }

            @media screen and (max-width: 1200px) {
                .tts-support-layout {
                    grid-template-columns: 1fr;
                }
            }

            @media screen and (max-width: 782px) {
                .tts-support-grid-2,
                .tts-support-grid-5 {
                    grid-template-columns: 1fr;
                }
            }
            </style>

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<?php if (!empty($form_toast_message)) : ?>
<script>
if (typeof mementorTTSShowNotification === 'function') {
    mementorTTSShowNotification('<?php echo esc_js($form_toast_message); ?>', '<?php echo esc_js($form_toast_type); ?>');
}
</script>
<?php endif; ?>
