<?php

/**
 * User Profile Fields
 *
 * Adds E-E-A-T (Experience, Expertise, Authoritativeness, Trustworthiness) fields
 * to WordPress user profiles for better author schema output.
 *
 * @package ProRank\SEO\Admin
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Admin;

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


/**
 * UserProfileFields class
 */


class UserProfileFields {

    /**
     * Initialize user profile fields
     *
     * @return void
     */
    public function init(): void {
        // Add fields to user profile edit form
        add_action('show_user_profile', [$this, 'render_author_seo_fields']);
        add_action('edit_user_profile', [$this, 'render_author_seo_fields']);

        // Save the custom fields
        add_action('personal_options_update', [$this, 'save_author_seo_fields']);
        add_action('edit_user_profile_update', [$this, 'save_author_seo_fields']);
    }

    /**
     * Render author SEO fields on profile page
     *
     * @param \WP_User $user The user object.
     * @return void
     */
    public function render_author_seo_fields(\WP_User $user): void {
        if (!$this->is_author_seo_enabled()) {
            return;
        }

        // Check if current user can edit this profile
        if (!current_user_can('edit_user', $user->ID)) {
            return;
        }

        // Get current values
        $job_title = get_user_meta($user->ID, 'prorank_job_title', true);
        $works_for = get_user_meta($user->ID, 'prorank_works_for', true);
        $knows_about = get_user_meta($user->ID, 'prorank_knows_about', true);
        $alumni_of = get_user_meta($user->ID, 'prorank_alumni_of', true);
        $credentials = get_user_meta($user->ID, 'prorank_credentials', true);
        ?>
        <h2><?php esc_html_e('ProRank SEO - Author E-E-A-T Settings', 'prorank-seo'); ?></h2>
        <p class="description">
            <?php esc_html_e('These fields help search engines understand your expertise and authority. They appear in the Article schema when you publish content.', 'prorank-seo'); ?>
        </p>

        <table class="form-table" role="presentation">
            <tr>
                <th>
                    <label for="prorank_job_title">
                        <?php esc_html_e('Job Title', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="prorank_job_title"
                        id="prorank_job_title"
                        value="<?php echo esc_attr($job_title); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Your professional title (e.g., "Senior Developer", "Marketing Director", "CEO").', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="prorank_works_for">
                        <?php esc_html_e('Works For (Organization)', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="prorank_works_for"
                        id="prorank_works_for"
                        value="<?php echo esc_attr($works_for); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('The organization you work for. Leave blank to use the site\'s organization name.', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="prorank_knows_about">
                        <?php esc_html_e('Areas of Expertise', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="prorank_knows_about"
                        id="prorank_knows_about"
                        value="<?php echo esc_attr($knows_about); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Topics you are knowledgeable about, separated by commas (e.g., "SEO, Content Marketing, Web Development").', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="prorank_alumni_of">
                        <?php esc_html_e('Alumni Of (Education)', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="prorank_alumni_of"
                        id="prorank_alumni_of"
                        value="<?php echo esc_attr($alumni_of); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('University or educational institution you attended (e.g., "Stanford University").', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="prorank_credentials">
                        <?php esc_html_e('Professional Credentials', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="prorank_credentials"
                        id="prorank_credentials"
                        value="<?php echo esc_attr($credentials); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Certifications or credentials (e.g., "CPA, MBA, Google Certified").', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>
        </table>

        <h3><?php esc_html_e('Social Profiles', 'prorank-seo'); ?></h3>
        <p class="description">
            <?php esc_html_e('Your social profiles will be included in the author schema for better search visibility.', 'prorank-seo'); ?>
        </p>

        <table class="form-table" role="presentation">
            <tr>
                <th>
                    <label for="twitter">
                        <?php esc_html_e('Twitter/X Username', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="twitter"
                        id="twitter"
                        value="<?php echo esc_attr(get_user_meta($user->ID, 'twitter', true)); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Your Twitter/X username without the @ symbol.', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="linkedin">
                        <?php esc_html_e('LinkedIn Profile URL', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="url"
                        name="linkedin"
                        id="linkedin"
                        value="<?php echo esc_attr(get_user_meta($user->ID, 'linkedin', true)); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Full URL to your LinkedIn profile.', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="facebook">
                        <?php esc_html_e('Facebook Profile URL', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="url"
                        name="facebook"
                        id="facebook"
                        value="<?php echo esc_attr(get_user_meta($user->ID, 'facebook', true)); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Full URL to your Facebook profile.', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th>
                    <label for="instagram">
                        <?php esc_html_e('Instagram Username', 'prorank-seo'); ?>
                    </label>
                </th>
                <td>
                    <input
                        type="text"
                        name="instagram"
                        id="instagram"
                        value="<?php echo esc_attr(get_user_meta($user->ID, 'instagram', true)); ?>"
                        class="regular-text"
                    />
                    <p class="description">
                        <?php esc_html_e('Your Instagram username without the @ symbol.', 'prorank-seo'); ?>
                    </p>
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Save author SEO fields
     *
     * @param int $user_id The user ID.
     * @return void
     */
    public function save_author_seo_fields(int $user_id): void {
        if (!$this->is_author_seo_enabled()) {
            return;
        }

        // Check permissions
        if (!current_user_can('edit_user', $user_id)) {
            return;
        }

        // Verify nonce (WP handles this for profile updates)
        $nonce = (string) prorank_get_input_value($_POST, '_wpnonce', '');
        if (!wp_verify_nonce($nonce, 'update-user_' . $user_id)) {
            return;
        }

        // E-E-A-T fields
        $fields = [
            'prorank_job_title',
            'prorank_works_for',
            'prorank_knows_about',
            'prorank_alumni_of',
            'prorank_credentials',
        ];

        foreach ($fields as $field) {
            if (prorank_has_input($_POST, $field)) {
                update_user_meta($user_id, $field, sanitize_text_field((string) prorank_get_input_value($_POST, $field, '')));
            }
        }

        // Social profiles
        $social_fields = ['twitter', 'linkedin', 'facebook', 'instagram'];

        foreach ($social_fields as $field) {
            if (prorank_has_input($_POST, $field)) {
                $value = sanitize_text_field((string) prorank_get_input_value($_POST, $field, ''));

                // Clean up Twitter/Instagram usernames
                if (in_array($field, ['twitter', 'instagram'], true)) {
                    $value = ltrim($value, '@');
                }

                // Validate URLs for LinkedIn and Facebook
                if (in_array($field, ['linkedin', 'facebook'], true) && !empty($value)) {
                    $value = esc_url_raw($value);
                }

                update_user_meta($user_id, $field, $value);
            }
        }
    }

    /**
     * Check whether author SEO profile controls are enabled.
     */
    private function is_author_seo_enabled(): bool {
        $settings = get_option('prorank_titles_meta_settings', []);
        if (!is_array($settings) || empty($settings)) {
            $settings = get_option('prorank_seo_titles_meta', []);
        }

        if (!is_array($settings)) {
            return true;
        }

        return !isset($settings['author_seo_meta_box']) || (bool) $settings['author_seo_meta_box'];
    }
}
