<?php
namespace ZS_SEO\AuditOptimization\Admin;

defined( 'ABSPATH' ) || exit;

class ImageFixer {

    public function __construct() {
        add_action( 'wp_ajax_zs_seo_auto_alt',      [ $this, 'auto_generate_alt' ] );
        add_action( 'wp_ajax_zs_seo_save_alt',       [ $this, 'save_alt'          ] );
        add_action( 'wp_ajax_zs_seo_bulk_auto_alt',  [ $this, 'bulk_auto_alt'     ] );
        add_action( 'wp_ajax_zs_seo_bulk_save_alts', [ $this, 'bulk_save_alts'    ] );
    }


    // ── Auto generate alt text from filename + title ───────────────────────────
    public function auto_generate_alt(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ], 403 );
        }

        $attachment_id = absint( $_POST['attachment_id'] ?? 0 );
        $filename      = sanitize_text_field( wp_unslash( $_POST['filename'] ?? '' ) );
        $title         = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );

        if ( ! $attachment_id ) {
            wp_send_json_error( [ 'message' => 'Invalid attachment ID.' ] );
        }

        $alt = $this->generate_alt_from_metadata( $attachment_id, $filename, $title );
        wp_send_json_success( [ 'alt' => $alt, 'attachment_id' => $attachment_id ] );
    }

    // ── Save single alt text ───────────────────────────────────────────────────
    public function save_alt(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ], 403 );
        }

        $attachment_id = absint( $_POST['attachment_id'] ?? 0 );
        $alt           = sanitize_text_field( wp_unslash( $_POST['alt'] ?? '' ) );

        if ( ! $attachment_id ) {
            wp_send_json_error( [ 'message' => 'Invalid attachment ID.' ] );
        }

        update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt );
        wp_send_json_success( [ 'message' => 'Alt text saved!', 'alt' => $alt ] );
    }

    // ── Bulk auto-generate for multiple images ────────────────────────────────
    public function bulk_auto_alt(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ], 403 );
        }

        $ids = isset( $_POST['ids'] ) ? array_map( 'absint', (array) $_POST['ids'] ) : [];
        if ( empty( $ids ) ) {
            wp_send_json_error( [ 'message' => 'No images selected.' ] );
        }

        $results = [];
        foreach ( $ids as $id ) {
            $post     = get_post( $id );
            $filename = basename( get_attached_file( $id ) );
            $title    = $post ? $post->post_title : '';
            $alt      = $this->generate_alt_from_metadata( $id, $filename, $title );
            $results[ $id ] = $alt;
        }

        wp_send_json_success( [ 'alts' => $results ] );
    }

    // ── Bulk save all edited alt texts ────────────────────────────────────────
    public function bulk_save_alts(): void {
        check_ajax_referer( 'zs_seo_nonce', 'nonce' );
        if ( ! current_user_can( 'upload_files' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ], 403 );
        }

        $alts = isset( $_POST['alts'] ) ? (array) wp_unslash( $_POST['alts'] ) : []; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        if ( empty( $alts ) ) {
            wp_send_json_error( [ 'message' => 'No data to save.' ] );
        }

        $saved = 0;
        foreach ( $alts as $id => $alt ) {
            $id  = absint( $id );
            $alt = sanitize_text_field( $alt );
            if ( $id && $alt ) {
                update_post_meta( $id, '_wp_attachment_image_alt', $alt );
                $saved++;
            }
        }

        wp_send_json_success( [
            'message' => sprintf( '%d alt text(s) saved successfully!', $saved ),
            'saved'   => $saved,
        ] );
    }

    // ── Smart alt text generator ──────────────────────────────────────────────
    private function generate_alt_from_metadata( int $id, string $filename, string $title ): string {

        // 1. Try existing WordPress attachment title (often descriptive)
        if ( $title && ! preg_match( '/^[0-9a-f\-]{10,}$/i', $title ) ) {
            // Clean up title — remove numbers, dashes, underscores
            $clean = ucwords( str_replace( [ '-', '_', '  ' ], ' ', $title ) );
            if ( strlen( $clean ) > 5 ) {
                return $this->add_brand( $clean );
            }
        }

        // 2. Generate from filename
        $name = pathinfo( $filename, PATHINFO_FILENAME );

        // Remove common WP size suffixes like -150x150, -700x600
        $name = preg_replace( '/-\d+x\d+$/', '', $name );

        // Remove timestamps/IDs (e.g. img_20230415)
        $name = preg_replace( '/[-_]?\d{6,}/', '', $name );

        // Replace separators with spaces
        $name = str_replace( [ '-', '_', '.' ], ' ', $name );

        // Remove extra spaces
        $name = preg_replace( '/\s+/', ' ', trim( $name ) );

        // Title case
        $name = ucwords( strtolower( $name ) );

        if ( strlen( $name ) < 3 ) {
            return get_bloginfo( 'name' ) . ' Image';
        }

        return $this->add_brand( $name );
    }

    // ── Append brand name for better SEO ──────────────────────────────────────
    private function add_brand( string $text ): string {
        $brand = get_bloginfo( 'name' );
        // Only add brand if not already there
        if ( $brand && stripos( $text, $brand ) === false ) {
            return $text . ' — ' . $brand;
        }
        return $text;
    }
}
