<?php

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

class RIZWAN_IMAGE_ALT_TEXT_WEBP_OPTIMIZER_Image_Handler {
    public function __construct() {

add_action(
'add_attachment',
[$this,'rizwan_image_alt_text_webp_optimizer_process_uploaded_image']
);

add_action(
'edit_attachment',
[$this,'rizwan_image_alt_text_webp_optimizer_process_uploaded_image']
);

}

/**
 * Process Uploaded Image
 */
public function rizwan_image_alt_text_webp_optimizer_process_uploaded_image(
$attachment_id
) {


    /**
     * Only Process Images
     */
    $mime = get_post_mime_type(
        $attachment_id
    );

    if (
empty($mime) ||
strpos(
$mime,
'image/'
)!==0
){
return;
}

    /**
     * Get File Path
     */
    $file_path = get_attached_file(
        $attachment_id
    );

    if (
empty(
$file_path
)
) {
        return;
    }

    /**
 * Generate WebP For Original
 */
$this->generate_webp(
    $file_path
);

    /**
     * Generate WebP For Thumbnails
     */
    $metadata = wp_get_attachment_metadata(
        $attachment_id
    );

    if (
        isset($metadata['sizes']) &&
        is_array(
        $metadata['sizes']
        )
    ) {

        $base_dir = dirname(
            $file_path
        );

        foreach (
            $metadata['sizes']
            as $size
        ) {

            if (
                !isset($size['file'])
            ) {
                continue;
            }

            $thumbnail_path =
                $base_dir .
                '/' .
                $size['file'];

            if (
                file_exists(
                    $thumbnail_path
                )
            ) {

                 $this->generate_webp(
        $thumbnail_path
    );
}

}
}
        

        /**
         * Get Filename
         */
        $filename = pathinfo(
            $file_path,
            PATHINFO_FILENAME
        );

        /**
         * Clean Filename
         */
        $filename = strtolower($filename);

        $filename = str_replace(
            ['-', '_'],
            ' ',
            $filename
        );

        /**
         * Remove Numbers
         */
        $filename = preg_replace(
            '/\\d+/',
            '',
            $filename
        );

        /**
         * Remove Special Characters
         */
        $filename = preg_replace(
            '/[^a-zA-Z\\s]/',
            ' ',
            $filename
        );

        /**
         * Remove Extra Spaces
         */
        $filename = preg_replace(
            '/\\s+/',
            ' ',
            $filename
        );

        /**
         * Convert Filename To Words
         */
        $words = explode(
            ' ',
            trim($filename)
        );

        /**
         * Remove Empty Values
         */
        $words = array_filter($words);

        /**
         * Stop Words
         */
        $stop_words = [
            'img',
            'image',
            'photo',
            'pic',
            'untitled',
            'copy',
            'final',
            'new',
            'scaled',
            'pngtree',
            'freepik',
            'shutterstock',
            'adobestock',
            'images',
            'illustration',
            'vector',
            'jpg',
            'jpeg',
            'png',
            'webp',
            'upload',
            'stock'
        ];

        /**
         * Remove Junk Words
         */
        $words = array_diff(
            $words,
            $stop_words
        );

        /**
         * Clean Text
         */
        $clean_text = implode(
            ' ',
            $words
        );

        /**
         * Generate Base Text
         */
        $base_text = ucwords(
            trim($clean_text)
        );

        /**
         * Context Detection
         */
        $context = '';

        /**
         * Trading Keywords
         */
        $trading_keywords = [
            'chart',
            'trading',
            'candlestick',
            'nifty',
            'banknifty',
            'btc',
            'bitcoin',
            'bullish',
            'bearish',
            'pattern',
            'forex',
            'crypto'
        ];

        /**
         * Nature Keywords
         */
        $nature_keywords = [
            'nature',
            'mountain',
            'river',
            'forest',
            'waterfall',
            'sunset',
            'tree',
            'lake',
            'flower',
            'leaves',
            'tropical'
        ];

        /**
         * Food Keywords
         */
        $food_keywords = [
            'food',
            'burger',
            'pizza',
            'cake',
            'coffee',
            'tea',
            'restaurant'
        ];

        /**
         * Technology Keywords
         */
        $tech_keywords = [
            'laptop',
            'mobile',
            'computer',
            'keyboard',
            'gaming',
            'setup',
            'iphone',
            'technology'
        ];

        /**
         * Design Keywords
         */
        $design_keywords = [
            'abstract',
            'crystal',
            'backdrop',
            'background',
            'wallpaper',
            'texture',
            'art',
            'colorful',
            'gradient',
            'luxury',
            'modern'
        ];

        /**
         * Detect Context
         */
        foreach ($words as $word) {

            if (in_array($word, $trading_keywords, true)) {
                $context = 'Trading Chart Analysis';
                break;
            }

            if (in_array($word, $nature_keywords, true)) {
                $context = 'Nature Landscape';
                break;
            }

            if (in_array($word, $food_keywords, true)) {
                $context = 'Food Photography';
                break;
            }

            if (in_array($word, $tech_keywords, true)) {
                $context = 'Technology Product Image';
                break;
            }

            if (in_array($word, $design_keywords, true)) {
                $context = 'Abstract Background Design';
                break;
            }
        }

        /**
         * Default Context
         */
        if (
        trim(
        (string)
        $context
        ) === ''
        ) {
            $context = 'SEO Optimized Image';
        }

        /**
         * Final Alt Text
         */
        $alt_text = trim(
            $base_text . ' ' . $context
        );

        /**
         * Final Title
         */
        $title_text = $base_text;

        /**
         * Final Caption
         */
        $caption_text = sprintf(
            'Professional SEO optimized image related to %s.',
            strtolower($alt_text)
        );

        /**
         * Auto Alt Text
         */
        if (
absint(
get_option(
'rizwan_image_alt_text_webp_optimizer_auto_alt',
0
)
)
) {

            $existing_alt = get_post_meta(
                $attachment_id,
                '_wp_attachment_image_alt',
                true
            );

            if (
            trim(
            (string)
            $existing_alt
            ) === ''
            ) {

                update_post_meta(
                    $attachment_id,
                    '_wp_attachment_image_alt',
                    sanitize_text_field($alt_text)
                );
            }
        }

        /**
         * Get Attachment Post
         */
        $post = get_post($attachment_id);

        if (
        !$post
        ) {
            return;
        }

        /**
         * Auto Title
         */
        if (
            absint(
            get_option(
            'rizwan_image_alt_text_webp_optimizer_auto_title',
            0
            )
            ) &&
            trim(
            (string)
            $post->post_title
            ) === ''
        ) {

            wp_update_post([
                'ID'         => $attachment_id,
                'post_title' => sanitize_text_field($title_text)
            ]);
        }

        /**
         * Auto Caption
         */
        if (
            absint(
            get_option(
            'rizwan_image_alt_text_webp_optimizer_auto_caption',
            0
            )
            ) &&
            trim(
            (string)
            $post->post_excerpt
            ) === ''
        ) {

            wp_update_post([
                'ID'           => $attachment_id,
                'post_excerpt' => sanitize_text_field($caption_text)
            ]);
        }

        /**
 * SEO Score
 */
$score = 0;

/**
 * Alt Text
 */
if (
    get_post_meta(
        $attachment_id,
        '_wp_attachment_image_alt',
        true
    )
) {

    $score += 25;
}

/**
 * Title
 */
$title = get_the_title(
    $attachment_id
);

if (
trim(
(string)
$title
)!==''
) {

    $score += 25;
}

/**
 * Caption
 */
$caption =
    wp_get_attachment_caption(
        $attachment_id
    );

if (
trim(
(string)
$caption
)!==''
) {

    $score += 25;
}

/**
 * WebP
 */
if (
file_exists(
preg_replace(
'/\.(jpg|jpeg|png)$/i',
'.webp',
$file_path
)
)
){

$score += 25;

}

/**
 * Save SEO Score
 */
$score = min(
100,
max(
0,
$score
)
);

update_post_meta(
$attachment_id,
'rizwan_image_alt_text_webp_optimizer_score',
absint(
$score
)
);
    }

    /**
     * Generate WebP
     */
    private function generate_webp($image_path) {

    

    $image_info = pathinfo($image_path);

    if (!isset($image_info['extension'])) {
        return;
    }

    $extension = strtolower(
        $image_info['extension']
    );

    $webp_path =
        $image_info['dirname'] . '/' .
        $image_info['filename'] .
        '.webp';

    /**
     * Already Exists
     */
    if (
file_exists(
$webp_path
)
){


return;

}

    /**
     * Create Image Resource
     */
    switch ($extension) {

        case 'jpg':
        case 'jpeg':

            $image =
                imagecreatefromjpeg(
                    $image_path
                );

            break;

        case 'png':

            $image =
                imagecreatefrompng(
                    $image_path
                );

            if (
function_exists(
'imagepalettetotruecolor'
)
) {

imagepalettetotruecolor(
$image
);

}

            imagealphablending(
                $image,
                true
            );

            imagesavealpha(
                $image,
                true
            );

            break;

        default:
            return;
    }

    if (
    !$image
    ) {
    return;
}

    /**
 * Save WebP
 */
$result = imagewebp(
$image,
$webp_path,
85
);

imagedestroy(
$image
);

if (
!$result
){
return;
}

    /**
     * Register WebP In Media Library
     */
    $upload_dir = wp_upload_dir();

    $webp_url = str_replace(
    $upload_dir['basedir'],
    $upload_dir['baseurl'],
    $webp_path
    );

    $webp_url = esc_url($webp_url);

    /**
     * Check Existing Attachment
     */
    $existing = attachment_url_to_postid(
        $webp_url
    );

    if (
    $existing
    ) {
        return;
    }

    /**
     * Create Attachment
     */
    $attachment = [

        'guid' => esc_url($webp_url),
        'post_mime_type' => 'image/webp',
        'post_title'     => sanitize_file_name(
            $image_info['filename']
        ) . '-webp',

        'post_content'   => '',
        'post_status'    => 'inherit'
    ];

    /**
     * Insert Into Media Library
     */
    $attach_id =
wp_insert_attachment(
$attachment,
$webp_path
);

if(
is_wp_error(
$attach_id
)
){
return;
}

    /**
     * Generate Metadata
     */
    require_once ABSPATH .
        'wp-admin/includes/image.php';

    $attach_data =
        wp_generate_attachment_metadata(
            $attach_id,
            $webp_path
        );

    wp_update_attachment_metadata(
        $attach_id,
        $attach_data
    );
}

}