/*
 Theme Name:   GeneratePress Child
 Theme URI:    https://generatepress.com
 Description:  Default GeneratePress child theme
 Author:       Tom Usborne
 Author URI:   https://tomusborne.com
 Template:     generatepress
 Version:      0.1
*/

// Shortcodes för telefonnummer - [telefon_william] eller [telefon_nikola]
// Tillåt shortcodes i paragrafblock
add_filter( 'the_content', 'do_shortcode' );

add_shortcode( 'telefon_william', function() {
    return '<a href="tel:+46703056749">0703-056 74 69</a>';
} );

add_shortcode( 'telefon_nikola', function() {
    return '<a href="tel:+46707160702">070-716 07 02</a>';
} );

// Skala ned, konvertera till WebP och komprimera vid uppladdning
add_filter( 'wp_handle_upload', function( $upload ) {
    if ( strpos( $upload['type'], 'image' ) === false ) return $upload;
    if ( current_user_can( 'administrator' ) ) return $upload;
    if ( $upload['type'] === 'image/webp' ) return $upload;

    $max_width  = 1920;
    $max_height = 1080;
    $file_path  = $upload['file'];

    $image = wp_get_image_editor( $file_path );
    if ( is_wp_error( $image ) ) return $upload;

    // Skala endast ned om bilden är för stor
    $size = $image->get_size();
    if ( $size['width'] > $max_width || $size['height'] > $max_height ) {
        $image->resize( $max_width, $max_height, false );
    }

    // Spara som WebP med hög kvalitet först för att mäta filstorlek
    $new_path = preg_replace( '/\.[^.]+$/', '.webp', $file_path );
    $saved = $image->save( $new_path, 'image/webp' );
    if ( is_wp_error( $saved ) ) return $upload;

    // Mät filstorleken och komprimera vid behov
    $file_size = filesize( $new_path );

    if ( $file_size > 500 * 1024 ) {
        $image->set_quality( 55 );
        $image->save( $new_path, 'image/webp' );
    } elseif ( $file_size > 200 * 1024 ) {
        $image->set_quality( 70 );
        $image->save( $new_path, 'image/webp' );
    }

    // Ta bort originalfilen om den hade annan ändelse
    if ( $file_path !== $new_path ) {
        @unlink( $file_path );
    }

    $upload['file'] = $new_path;
    $upload['url']  = str_replace( basename( $file_path ), basename( $new_path ), $upload['url'] );
    $upload['type'] = 'image/webp';

    return $upload;
} );

// Uppdatera texten i media uploader för icke-admins
add_action( 'admin_footer', function() {
    if ( current_user_can( 'administrator' ) ) return;
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.max-upload-size').forEach(function(el) {
            el.textContent = 'Maximal filstorlek för uppladdning: 10 MB';
        });
    });
    </script>
    <?php
} );

