<?php
namespace ZS_SEO\AuditOptimization\Admin;

defined( 'ABSPATH' ) || exit;

class Ajax {

    public function __construct() {
        add_action( 'wp_ajax_zs_seo_analyze_post',    [ $this, 'analyze_post'    ] );
        add_action( 'wp_ajax_zs_seo_analyze_all',     [ $this, 'analyze_all'     ] );
        add_action( 'wp_ajax_zs_seo_save_redirect',   [ $this, 'save_redirect'   ] );
        add_action( 'wp_ajax_zs_seo_delete_redirect',  [ $this, 'delete_redirect' ] );
    }


    // ── Analyze single post ────────────────────────────────────────────────────
    public function analyze_post(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __('Unauthorized.', 'zs-seo-audit-optimization') ], 403 );
        }
        $post_id = absint( $_POST['post_id'] ?? 0 );
        if ( ! $post_id ) {
            wp_send_json_error( [ 'message' => __('Invalid post ID.', 'zs-seo-audit-optimization') ] );
        }

        $analyzer = new \ZS_SEO\AuditOptimization\Analyzers\SeoAnalyzer( $post_id );
        $result   = $analyzer->run();

        // Calculate score
        $total_issues = 0;
        $sections = [ 'on_page', 'headings', 'images', 'performance', 'accessibility', 'geo' ];
        foreach ( $sections as $s ) {
            if ( isset( $result[ $s ]['issues'] ) ) {
                foreach ( $result[ $s ]['issues'] as $issue ) {
                    if ( $issue['type'] === 'error' )   $total_issues += 3;
                    if ( $issue['type'] === 'warning' ) $total_issues += 2;
                    if ( $issue['type'] === 'info' )    $total_issues += 1;
                }
            }
        }
        $result['score'] = max( 0, 100 - $total_issues );

        wp_send_json_success( $result );
    }

    // ── Analyze all posts ──────────────────────────────────────────────────────
    public function analyze_all(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __('Unauthorized.', 'zs-seo-audit-optimization') ], 403 );
        }

        $posts = get_posts( [
            'post_type'      => [ 'post', 'page' ],
            'post_status'    => 'publish',
            'posts_per_page' => 50,
            'fields'         => 'ids',
        ] );

        $results = [];
        foreach ( $posts as $post_id ) {
            $analyzer    = new \ZS_SEO\AuditOptimization\Analyzers\SeoAnalyzer( $post_id );
            $result      = $analyzer->run();
            $total_issues = 0;
            $sections     = [ 'on_page', 'headings', 'images', 'performance', 'accessibility', 'geo' ];
            foreach ( $sections as $s ) {
                if ( isset( $result[ $s ]['issues'] ) ) {
                    foreach ( $result[ $s ]['issues'] as $issue ) {
                        if ( $issue['type'] === 'error' )   $total_issues += 3;
                        if ( $issue['type'] === 'warning' ) $total_issues += 2;
                        if ( $issue['type'] === 'info' )    $total_issues += 1;
                    }
                }
            }
            $score = max( 0, 100 - $total_issues );
            $results[] = [
                'post_id'    => $post_id,
                'title'      => get_the_title( $post_id ),
                'edit_url'   => get_edit_post_link( $post_id ),
                'view_url'   => get_permalink( $post_id ),
                'score'      => $score,
                'issues'     => $total_issues,
            ];
        }

        usort( $results, fn( $a, $b ) => $a['score'] <=> $b['score'] );
        wp_send_json_success( $results );
    }

    // ── Save redirect ─────────────────────────────────────────────────────────
    public function save_redirect(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __('Unauthorized.', 'zs-seo-audit-optimization') ], 403 );
        }
        global $wpdb;

        $source = sanitize_text_field( wp_unslash( $_POST['source'] ?? '' ) );
        $target = esc_url_raw( wp_unslash( $_POST['target'] ?? '' ) );
        $type   = absint( $_POST['type'] ?? 301 );

        if ( ! $source || ! $target ) {
            wp_send_json_error( [ 'message' => __('Source and target URLs are required.', 'zs-seo-audit-optimization') ] );
        }

        $table = $wpdb->prefix . 'zs_seo_redirects';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->replace( $table, [
            'source_url' => $source,
            'target_url' => $target,
            'type'       => $type,
        ], [ '%s', '%s', '%d' ] );

        if ( $result === false ) {
            wp_send_json_error( [ 'message' => __('Failed to save redirect.', 'zs-seo-audit-optimization') ] );
        }

        wp_send_json_success( [ 'message' => __('Redirect saved.', 'zs-seo-audit-optimization'), 'id' => $wpdb->insert_id ] );
    }

    // ── Delete redirect ───────────────────────────────────────────────────────
    public function delete_redirect(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __('Unauthorized.', 'zs-seo-audit-optimization') ], 403 );
        }
        global $wpdb;

        $id    = absint( $_POST['id'] ?? 0 );
        $table = $wpdb->prefix . 'zs_seo_redirects';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete( $table, [ 'id' => $id ], [ '%d' ] );

        wp_send_json_success( [ 'message' => __('Redirect deleted.', 'zs-seo-audit-optimization') ] );
    }
}
