<?php

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

class RIZWAN_IMAGE_ALT_TEXT_WEBP_OPTIMIZER_WebP_Serving {

    public function __construct() {

        add_filter(
            'wp_get_attachment_url',
            [$this, 'serve_webp']
        );

        add_filter(
            'the_content',
            [$this, 'replace_content_images']
        );
    }

    /**
     * Replace Attachment URL
     */
    public function serve_webp(
        $url
    ) {

        $upload_dir = wp_upload_dir();

        if (
            strpos(
                $url,
                $upload_dir['baseurl']
            ) !== 0
        ) {
            return $url;
        }

        /**
         * Only JPG / JPEG / PNG
         */
        if (
            !preg_match(
                '/\.(jpg|jpeg|png)$/i',
                $url
            )
        ) {
            return $url;
        }

        /**
         * Create WebP URL
         */
        $webp_url = preg_replace(
            '/\.(jpg|jpeg|png)$/i',
            '.webp',
            $url
        );

        if (
            empty(
                $webp_url
            )
        ) {
            return $url;
        }

        /**
         * Convert URL → Path
         */
        $webp_path = str_replace(
            $upload_dir['baseurl'],
            $upload_dir['basedir'],
            $webp_url
        );

        if (
            file_exists(
                $webp_path
            )
        ) {

            return esc_url(
                $webp_url
            );
        }

        return $url;
    }

    /**
     * Replace Images In Content
     */
    public function replace_content_images(
        $content
    ) {

        return preg_replace_callback(
            '/<img[^>]+src=["\']([^"\']+)["\']/i',
            [$this, 'replace_single_image'],
            $content
        );
    }

    /**
     * Replace Single Image
     */
    private function replace_single_image(
        $matches
    ) {

        $image_url =
            $matches[1];

        $upload_dir =
            wp_upload_dir();

        if (
            strpos(
                $image_url,
                $upload_dir['baseurl']
            ) !== 0
        ) {
            return $matches[0];
        }

        /**
         * Only JPG / JPEG / PNG
         */
        if (
            !preg_match(
                '/\.(jpg|jpeg|png)$/i',
                $image_url
            )
        ) {
            return $matches[0];
        }

        /**
         * Convert URL
         */
        $webp_url =
            preg_replace(
                '/\.(jpg|jpeg|png)$/i',
                '.webp',
                $image_url
            );

        if (
            empty(
                $webp_url
            )
        ) {
            return $matches[0];
        }

        /**
         * Convert URL → Path
         */
        $webp_path =
            str_replace(
                $upload_dir['baseurl'],
                $upload_dir['basedir'],
                $webp_url
            );

        if (
            file_exists(
                $webp_path
            )
        ) {

            return str_replace(
                $image_url,
                esc_url(
                    $webp_url
                ),
                $matches[0]
            );
        }

        return $matches[0];
    }
}