<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\SEO;

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

final class OrganicLandingAudit
{
    private const URLS = 'h4bs_organic_landing_urls';
    private const RESULTS = 'h4bs_organic_landing_results';

    public function boot(): void
    {
        add_action('admin_menu', [$this, 'menu']);
        add_action('admin_post_h4bs_save_organic_landings', [$this, 'save']);
        add_filter('attachment_fields_to_edit', [$this, 'attachmentFields'], 10, 2);
        add_filter('attachment_fields_to_save', [$this, 'saveAttachmentFields'], 10, 2);
    }

    public function menu(): void
    {
        add_submenu_page('h4bs-settings', __('Organic Landing Audit', 'help4-builder-suite'), __('Organic Landings', 'help4-builder-suite'), 'manage_options', 'h4bs-organic-landings', [$this, 'page']);
    }

    public function page(): void
    {
        if (! current_user_can('manage_options')) return;
        $urls = (array) get_option(self::URLS, []);
        $results = (array) get_option(self::RESULTS, []);
        ?><div class="wrap"><h1><?php esc_html_e('Organic Landing Audit', 'help4-builder-suite'); ?></h1><p><?php esc_html_e('Track proven organic landing pages without importing private Search Console metrics. The audit flags redirects, PDF-only destinations, errors, and pages without a standard meta description.', 'help4-builder-suite'); ?></p><form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"><?php wp_nonce_field('h4bs_save_organic_landings'); ?><input type="hidden" name="action" value="h4bs_save_organic_landings"><label for="h4bs-organic-urls"><strong><?php esc_html_e('Verified landing URLs (one same-site URL per line, maximum 100)', 'help4-builder-suite'); ?></strong></label><textarea id="h4bs-organic-urls" name="urls" class="large-text code" rows="10"><?php echo esc_textarea(implode("\n", $urls)); ?></textarea><?php submit_button(__('Save and audit', 'help4-builder-suite')); ?></form><h2><?php esc_html_e('Results', 'help4-builder-suite'); ?></h2><table class="widefat striped"><thead><tr><th><?php esc_html_e('URL', 'help4-builder-suite'); ?></th><th><?php esc_html_e('HTTP', 'help4-builder-suite'); ?></th><th><?php esc_html_e('Type', 'help4-builder-suite'); ?></th><th><?php esc_html_e('Finding', 'help4-builder-suite'); ?></th></tr></thead><tbody><?php foreach ($results as $row) : ?><tr><td><code><?php echo esc_html((string) ($row['url'] ?? '')); ?></code></td><td><?php echo esc_html((string) ($row['status'] ?? '')); ?></td><td><?php echo esc_html((string) ($row['content_type'] ?? '')); ?></td><td><?php echo esc_html((string) ($row['finding'] ?? '')); ?></td></tr><?php endforeach; ?><?php if ($results === []) : ?><tr><td colspan="4"><?php esc_html_e('No audit has been run.', 'help4-builder-suite'); ?></td></tr><?php endif; ?></tbody></table><p><?php esc_html_e('For content currently living only in a PDF, keep the document downloadable and create an accessible HTML landing page with equivalent factual content, metadata, headings, and a link to the file.', 'help4-builder-suite'); ?></p></div><?php
    }

    public function save(): void
    {
        if (! current_user_can('manage_options')) wp_die(esc_html__('Unauthorized request.', 'help4-builder-suite'));
        check_admin_referer('h4bs_save_organic_landings');
        $rawUrls = isset($_POST['urls']) ? sanitize_textarea_field(wp_unslash((string) $_POST['urls'])) : '';
        $rows = preg_split('/\r?\n/', $rawUrls) ?: [];
        $urls = [];
        foreach ($rows as $row) {
            $url = esc_url_raw(trim($row));
            if ($url === '' || strtolower((string) wp_parse_url($url, PHP_URL_HOST)) !== strtolower((string) wp_parse_url(home_url('/'), PHP_URL_HOST))) continue;
            $urls[] = $url;
            if (count($urls) >= 100) break;
        }
        $urls = array_values(array_unique($urls));
        update_option(self::URLS, $urls, false);
        update_option(self::RESULTS, array_map([$this, 'auditUrl'], $urls), false);
        wp_safe_redirect(admin_url('admin.php?page=h4bs-organic-landings'));
        exit;
    }

    /** @return array<string, int|string> */
    private function auditUrl(string $url): array
    {
        $response = wp_safe_remote_get($url, ['timeout'=>8, 'redirection'=>0, 'limit_response_size'=>262144, 'headers'=>['Accept'=>'text/html,application/pdf;q=0.9']]);
        if (is_wp_error($response)) return ['url'=>$url,'status'=>0,'content_type'=>'','finding'=>$response->get_error_message()];
        $status = wp_remote_retrieve_response_code($response);
        $type = strtolower((string) wp_remote_retrieve_header($response, 'content-type'));
        $body = wp_remote_retrieve_body($response);
        $finding = 'healthy_html';
        if ($status >= 300 && $status < 400) $finding = 'redirect_landing';
        elseif ($status >= 400) $finding = 'http_error';
        elseif (str_contains($type, 'application/pdf') || preg_match('/\.pdf(?:$|[?#])/i', $url)) $finding = 'pdf_only_landing';
        elseif (! preg_match('/<meta\s+[^>]*name\s*=\s*(["\'])description\1[^>]*content\s*=\s*(["\'])\s*[^"\']+\2/i', $body) && ! preg_match('/<meta\s+[^>]*content\s*=\s*(["\'])\s*[^"\']+\1[^>]*name\s*=\s*(["\'])description\2/i', $body)) $finding = 'missing_meta_description';
        return ['url'=>$url,'status'=>$status,'content_type'=>$type,'finding'=>$finding];
    }

    /** @param array<string, mixed> $fields @return array<string, mixed> */
    public function attachmentFields(array $fields, \WP_Post $post): array
    {
        if (get_post_mime_type($post) !== 'application/pdf') return $fields;
        $fields['h4_document_public_title'] = ['label'=>__('Document public title', 'help4-builder-suite'),'input'=>'text','value'=>(string) get_post_meta($post->ID, '_h4_document_public_title', true)];
        $fields['h4_document_summary'] = ['label'=>__('Accessible document summary', 'help4-builder-suite'),'input'=>'textarea','value'=>(string) get_post_meta($post->ID, '_h4_document_summary', true)];
        $fields['h4_document_landing_url'] = ['label'=>__('Preferred HTML landing URL', 'help4-builder-suite'),'input'=>'text','value'=>(string) get_post_meta($post->ID, '_h4_document_landing_url', true)];
        return $fields;
    }

    /** @param array<string, mixed> $post @param array<string, mixed> $attachment @return array<string, mixed> */
    public function saveAttachmentFields(array $post, array $attachment): array
    {
        $id = absint($post['ID'] ?? 0);
        if ($id <= 0 || ! current_user_can('edit_post', $id)) return $post;
        update_post_meta($id, '_h4_document_public_title', sanitize_text_field((string) ($attachment['h4_document_public_title'] ?? '')));
        update_post_meta($id, '_h4_document_summary', sanitize_textarea_field((string) ($attachment['h4_document_summary'] ?? '')));
        update_post_meta($id, '_h4_document_landing_url', esc_url_raw((string) ($attachment['h4_document_landing_url'] ?? '')));
        return $post;
    }
}
