<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://ilmdesigns.com/
 * @since      1.0.0
 *
 * @package    Square_Thumbnails
 * @subpackage Square_Thumbnails/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Square_Thumbnails
 * @subpackage Square_Thumbnails/admin
 * @author     ILMDESIGNS <narcisbodea@gmail.com>
 */
class Square_Thumbnails_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;
        
        
        private $option_name = 'square_thumbnails';

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}

        public function display_admin_page(){
            add_submenu_page('upload.php',
                    'Square Thumbnails Options',
                    'Square Thumbnails',
                    'manage_options',
                    'square-thumbnails-admin-page',
                    array($this,'showPage')
           );
           do_action( 'square-thumbnails-settings');            
        }
        

        function donation_notice() {
            $coffee = 'https://buymeacoffee.com/narcisbodea'; 
            $revolut = 'https://revolut.me/nicunatymj'; 
            $paypal = 'https://paypal.me/narcisbodea'; 
            // translators: %s are opening and closing <a> tags respectively.
            $message = sprintf(__('If you find <b>Square Thumbnails</b> plugin useful, please consider making a donation to support its development and support. <a href="%1$s" target="_blank">Click here to donate by paypal.</a> or <a href="%2$s" target="_blank">Click here to donate by revolut.</a> or <a href="%3$s" target="_blank">Click here to buy me a coffee.</a>', 'utxi-textdomain'), $paypal, $revolut, $coffee);
            echo '<div class="notice notice-info"><p>' . wp_kses_post($message) . '</p></div>';
        }
        
	public function link_settings( $links ) {

		$links[] = sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'upload.php?page=square-thumbnails-admin-page' ) ), esc_html__( 'Settings', 'square-thumbnails' ) );

		return $links;

	} // link_settings()        
        
        
        public function showPage(){
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('You do not have sufficient permissions to access this page.'));
            }
            include 'partials/square-thumbnails-admin-display.php';
        }
            
        private function floodFill($newim){
//              $dofill=get_option($this->option_name.'_dofill');                                  
//              if(!empty($dofill)){
//                    $red=255;
//                    $green=255;
//                    $blue=255;
//                    $htmlcolor=get_option($this->option_name.'_bgcolor');
//                    $ret=$this->hex2RGB($htmlcolor);
//                        $red =  $ret['red'] ; 
//                        $green =  $ret['green']; 
//                        $blue =  $ret['blue'] ;     
//                    $white=imagecolorallocate($newim,$red,$green,$blue);  
//                    imagefill($newim, 0, 0, $white);
//              }              
        }
        
        /**
         * Get supported image formats based on available GD functions
         * 
         * @since 1.1.1
         * @return array List of supported MIME types
         */
        private function get_supported_formats(){
            $formats = array();
            
            // Always supported formats
            $formats[] = 'image/jpeg';
            $formats[] = 'image/jpg';
            $formats[] = 'image/png';
            $formats[] = 'image/gif';
            
            // Check for WebP support
            if(function_exists('imagecreatefromwebp') && function_exists('imagewebp')){
                $formats[] = 'image/webp';
            }
            
            // Check for AVIF support
            if(function_exists('imagecreatefromavif') && function_exists('imageavif')){
                $formats[] = 'image/avif';
            }
            
            // Check for BMP support
            if(function_exists('imagecreatefrombmp') && function_exists('imagebmp')){
                $formats[] = 'image/bmp';
                $formats[] = 'image/x-ms-bmp';
            }
            
            // WBMP support
            if(function_exists('imagecreatefromwbmp')){
                $formats[] = 'image/vnd.wap.wbmp';
            }
            
            return $formats;
        }
        
        private function getColor($im){
                  $rgb = imagecolorat($im, 0, 0);
                  $colors = imagecolorsforindex($im, $rgb);    
                  $red=$colors['red'];
                  $green=$colors['green'];
                  $blue=$colors['blue'];
                  
                  return array('red'=>$red,'green'=>$green,'blue'=>$blue);
        }
        
        private function getBackgroundColor(){
            $red=255;
            $green=255;
            $blue=255;
            $htmlcolor=get_option($this->option_name.'_bgcolor', '#ffffff');
            if(!empty($htmlcolor)){
                $ret=$this->hex2RGB($htmlcolor);
                $red =  $ret['red']; 
                $green =  $ret['green']; 
                $blue =  $ret['blue'];   
            }
            return array('red'=>$red,'green'=>$green,'blue'=>$blue);
        }
        
        

        
        private function getPaths($filename){
                $updir = wp_upload_dir();
                $file = trailingslashit($updir['basedir']).$filename;                
                $dir=trailingslashit(dirname($file));                  
                $path=new stdClass();
                $path->upload=$updir;
                $path->file=$file;
                $path->dir=$dir;
                return $path;                
        }
        
        
        private function createIm($mime,$file,&$im){
              if($mime=='image/png'){
                  $im= imagecreatefrompng($file);
              }
              elseif($mime=='image/jpeg' || $mime=='image/jpg'){
                  $im= imagecreatefromjpeg($file);
              }
              elseif($mime=='image/gif'){
                  $im= imagecreatefromgif($file);
              }
              elseif($mime=='image/webp'){
                  if(function_exists('imagecreatefromwebp')){
                      $im= imagecreatefromwebp($file);
                  }
              }
              elseif($mime=='image/avif'){
                  if(function_exists('imagecreatefromavif')){
                      $im= imagecreatefromavif($file);
                  }
              }
              elseif($mime=='image/bmp' || $mime=='image/x-ms-bmp'){
                  if(function_exists('imagecreatefrombmp')){
                      $im= imagecreatefrombmp($file);
                  }
              }
              elseif($mime=='image/vnd.wap.wbmp'){
                  $im= imagecreatefromwbmp($file);
              }             
        }
        
        private function saveIm($mime,&$newim,&$f){
                  error_log('Square Thumbnails - saveIm called with mime: ' . $mime . ', file: ' . $f);
                  
                  // Check if directory is writable
                  $dir = dirname($f);
                  if(!is_writable($dir)){
                      error_log('Square Thumbnails - ERROR: Directory not writable: ' . $dir);
                      return;
                  }
                  
                  // Check if we're saving with transparency
                  $bg_type = get_option($this->option_name.'_bg_type', 'color');
                  $preserve_transparency = ($bg_type === 'transparent' && in_array($mime, array('image/png', 'image/webp', 'image/avif')));
                  
                  // Convert JPEG to PNG if transparent background is selected
                  if(($mime=='image/jpeg' || $mime=='image/jpg') && $bg_type === 'transparent'){
                      $path_info = pathinfo($f);
                      $f = $path_info['dirname'] . '/' . $path_info['filename'] . '.png';
                      error_log('Square Thumbnails - Converting JPEG to PNG for transparency: ' . $f);
                      imagesavealpha($newim, true);
                      imagepng($newim, $f);
                      return; // Exit after saving as PNG
                  }
                  
                  if($mime=='image/png'){
                      if($preserve_transparency){
                          imagesavealpha($newim, true);
                      }
                      error_log('Square Thumbnails - Saving PNG: ' . $f);
                      $result = imagepng($newim, $f);
                      error_log('Square Thumbnails - PNG save result: ' . ($result ? 'success' : 'failed'));
                  }
                  elseif($mime=='image/jpeg' || $mime=='image/jpg'){
                      $jpeg_quality = get_option($this->option_name.'_jpeg_quality', 90);
                      error_log('Square Thumbnails - Saving JPEG with quality ' . $jpeg_quality . ': ' . $f);
                      $result = imagejpeg($newim, $f, $jpeg_quality);
                      error_log('Square Thumbnails - JPEG save result: ' . ($result ? 'success' : 'failed'));
                  }
                  elseif($mime=='image/webp'){
                      if(function_exists('imagewebp')){
                          if($preserve_transparency){
                              imagesavealpha($newim, true);
                          }
                          imagewebp($newim, $f, 85); // Quality 85
                      }
                  }
                  elseif($mime=='image/avif'){
                      if(function_exists('imageavif')){
                          if($preserve_transparency){
                              imagesavealpha($newim, true);
                          }
                          imageavif($newim, $f, 80); // Quality 80
                      }
                  }
                  elseif($mime=='image/bmp' || $mime=='image/x-ms-bmp'){
                      if(function_exists('imagebmp')){
                          imagebmp($newim, $f);
                      }
                  }
                  elseif($mime=='image/gif'){
                      imagegif($newim, $f);
                  }
                  elseif($mime=='image/vnd.wap.wbmp'){
                      imagewbmp($newim, $f);
                  }          
        }
        
        
        private  function getSizes($imw,$imh){
                $sizes=new stdClass();

                $originalW=$imw;
                $originalH=$imh;                    
                
                $sizes->originalW=$originalW;
                $sizes->originalH=$originalH;
                
                
                $sw=$imw;
                $sh=$imh;
                if($imw>$imh){
                    $sh=$imw;
                }
                else{
                    $sw=$imh;
                }     
                $sizes->sqW=$sw;
                $sizes->sqH=$sh;
                
                
                // Calculate dimensions to fit the entire image within the square (contain behavior)
                $square_size = $sw; // The target square size
                $original_ratio = $originalW / $originalH;
                
                if($originalW > $originalH){
                    // Landscape image - fit to width
                    $twidth = $square_size;
                    $theight = $square_size / $original_ratio;
                }
                else{
                    // Portrait or square image - fit to height
                    $theight = $square_size;
                    $twidth = $square_size * $original_ratio;
                }
                
                // If the calculated dimensions exceed the square, scale down
                if($twidth > $square_size || $theight > $square_size) {
                    $scale = min($square_size / $twidth, $square_size / $theight);
                    $twidth *= $scale;
                    $theight *= $scale;
                }

                $sizes->resizedW=$twidth;
                $sizes->resizedH=$theight;
                //end resize
          
                // Center the image within the square
                $halign= get_option($this->option_name.'_halign');
                $valign= get_option($this->option_name.'_valign');
                if(empty($halign)) $halign='center';
                if(empty($valign)) $valign='middle';
                
                $newimx = 0;
                $newimy = 0;
                
                // Always calculate centering based on the actual resized dimensions
                switch ($halign){
                    case 'left':
                        $newimx = 0;
                        break;
                    case 'center':
                        $newimx = ($square_size - $twidth) / 2;
                        break;
                    case 'right':
                        $newimx = $square_size - $twidth;
                        break;
                }
                
                switch ($valign){
                    case 'top':
                        $newimy = 0;
                        break;
                    case 'middle':
                        $newimy = ($square_size - $theight) / 2;
                        break;
                    case 'bottom':
                        $newimy = $square_size - $theight;
                        break;
                }
                
                $sizes->x=$newimx;
                $sizes->y=$newimy;
                return $sizes;
        }

        private function allSizes(){
                global $_wp_additional_image_sizes;
                $sizes=$_wp_additional_image_sizes;
                $allS= get_intermediate_image_sizes();
                              
               foreach($allS as $t){
                   if(!isset($sizes[$t])){
                        $sizes[$t]=array(
                            'width'=>get_option( "{$t}_size_w" ),
                            'height'=>get_option( "{$t}_size_h" ),
                            'crop'=>(bool)get_option( "{$t}_size_crop" ),      
                        );                       
                   }
                   
                   // Force WooCommerce sizes to be square
                   if((strpos($t, 'woocommerce') !== false || strpos($t, 'shop_') !== false) && 
                      $sizes[$t]['width'] > 0 && $sizes[$t]['height'] == 0) {
                       $sizes[$t]['height'] = $sizes[$t]['width'];
                       error_log("Square Thumbnails - Forcing WooCommerce size $t to be square: {$sizes[$t]['width']}x{$sizes[$t]['width']}");
                   }
               }  
               return $sizes;
        }
        
        /**
         * Clean up old square thumbnails when format changes
         * 
         * @param int $attachment_id
         * @param string $new_format 'transparent' or 'color'
         */
        private function cleanup_old_square_thumbnails($attachment_id, $new_format) {
            error_log('Square Thumbnails - Cleanup for attachment ' . $attachment_id . ', new format: ' . $new_format);
            
            $metadata = wp_get_attachment_metadata($attachment_id);
            if (!$metadata || !isset($metadata['sizes'])) {
                return;
            }
            
            $upload_dir = wp_upload_dir();
            $base_dir = dirname($upload_dir['basedir'] . '/' . $metadata['file']);
            
            // Determine what to clean based on new format
            if ($new_format === 'transparent') {
                // If switching to transparent, remove old JPG files
                $pattern_to_remove = '-sqt*.jpg';
            } else {
                // If switching to color/image, remove old PNG files (that were created for transparency)
                $pattern_to_remove = '-sqt*.png';
            }
            
            foreach ($metadata['sizes'] as $size => $data) {
                // Look for our square thumbnail files
                $file_basename = pathinfo($data['file'], PATHINFO_FILENAME);
                $files_to_check = glob($base_dir . '/' . $file_basename . $pattern_to_remove);
                
                foreach ($files_to_check as $file) {
                    if (file_exists($file)) {
                        error_log('Square Thumbnails - Deleting old file: ' . $file);
                        @unlink($file);
                    }
                }
            }
        }
        
        public function create_square($meta, $attachment_id = null){
                error_log('Square Thumbnails - create_square called with meta: ' . print_r($meta, true));
                error_log('Square Thumbnails - Attachment ID: ' . $attachment_id);
                
                if(!function_exists('imagecreatefromjpeg')) {
                    error_log('Square Thumbnails - imagecreatefromjpeg not available');
                    return false;
                }   
                
                //get paths
                $path=$this->getPaths($meta['file']);                
                // For individual sizes, use the full path, for original use the dir + basename
                $file = (strpos($meta['file'], '/') !== false) ? $meta['file'] : $this->dir. basename($meta['file']);
                
                error_log('Square Thumbnails - Meta file: ' . $meta['file']);
                error_log('Square Thumbnails - Path->file: ' . $path->file);
                error_log('Square Thumbnails - Path->dir: ' . $path->dir);
                error_log('Square Thumbnails - this->dir: ' . $this->dir);
                error_log('Square Thumbnails - Final file path: ' . $file);
                
                // Check if file exists
                if(!file_exists($file)){
                    error_log('Square Thumbnails - File not found: ' . $file);
                    // Try alternative path - the original file
                    $alt_file = $path->file;
                    error_log('Square Thumbnails - Trying alternative path: ' . $alt_file);
                    if(file_exists($alt_file)){
                        $file = $alt_file;
                        error_log('Square Thumbnails - Using alternative path');
                    } else {
                        // Try to use the original by removing size suffix
                        $original = preg_replace('/-\d+x\d+(\.[^.]+)$/', '$1', $file);
                        error_log('Square Thumbnails - Trying original without size: ' . $original);
                        if(file_exists($original)){
                            $file = $original;
                            error_log('Square Thumbnails - Using original file');
                        } else {
                            return false;
                        }
                    }
                }
                
                //set mime type if missing in $meta  
                $mime_type = '';
                if(isset($meta['type'])){
                    $mime_type = $meta['type'];
                } elseif(isset($meta['mime-type'])) {
                    $mime_type = $meta['mime-type'];
                }
                
                if(empty($mime_type) && file_exists($file)){
                    $mime_type = image_type_to_mime_type (exif_imagetype($file));
                }                

                // Check format support
                $supported_formats = $this->get_supported_formats();
                if(!in_array($mime_type, $supported_formats)){
                    error_log('Square Thumbnails - Unsupported format: ' . $mime_type);
                    return false;
                }

                
                // For thumbnails, load the original image instead
                $load_file = $file;
                
                // If we have attachment ID, use the centralized source function
                if($attachment_id){
                    $source_file = $this->get_source_for_regeneration($attachment_id);
                    if($source_file){
                        $load_file = $source_file;
                        error_log('Square Thumbnails - Using source from get_source_for_regeneration: ' . $load_file);
                    }
                } else {
                    // Try to determine original file from the path
                    $original_file = preg_replace('/-\d+x\d+(\.[^.]+)$/', '$1', $file);
                    if($original_file !== $file && file_exists($original_file)){
                        $load_file = $original_file;
                        error_log('Square Thumbnails - Using deduced original file: ' . $load_file);
                    } else {
                        // Try to find from the same directory
                        $path_info = pathinfo($file);
                        $base_name = preg_replace('/-\d+x\d+$/', '', $path_info['filename']);
                        $original_attempt = $path_info['dirname'] . '/' . $base_name . '.' . $path_info['extension'];
                        if(file_exists($original_attempt)){
                            $load_file = $original_attempt;
                            error_log('Square Thumbnails - Using original from directory: ' . $load_file);
                        }
                    }
                }
                
                if(isset($this->im) && is_resource($this->im)){
                    // If we already have the original loaded, use it
                    $im = $this->im;
                    error_log('Square Thumbnails - Reusing already loaded original image');
                } else {
                    // Load the original file
                    error_log('Square Thumbnails - Loading image from: ' . $load_file);
                    $this->createIm($mime_type, $load_file, $im);
                }
                
                if(!$im){
                    error_log('Square Thumbnails - Failed to load image: ' . $load_file);
                    return false;
                }
                
                
                //create image from file 
                //the image will be reurned as refference in $im
                //$this->createIm($meta['mime-type'], $file, $im);
                
                //create the canvas for the square
                $newim = imagecreatetruecolor($sizes->sqW, $sizes->sqH);	
                
                // Check if we should use transparent background
                $bg_type = get_option($this->option_name.'_bg_type', 'color');
                error_log('Square Thumbnails - Background type: ' . $bg_type);
                error_log('Square Thumbnails - MIME type: ' . $mime_type);
                
                // If transparent background is selected for JPEG, we'll convert to PNG later
                if($bg_type === 'transparent'){
                    if(in_array($mime_type, array('image/png', 'image/webp', 'image/avif'))){
                        error_log('Square Thumbnails - Setting up transparency for supported format');
                        // Set up transparency
                        imagealphablending($newim, false);
                        imagesavealpha($newim, true);
                        $transparent = imagecolorallocatealpha($newim, 0, 0, 0, 127);
                        imagefilledrectangle($newim, 0, 0, $sizes->sqW, $sizes->sqH, $transparent);
                        imagealphablending($newim, true);
                    } else if($mime_type === 'image/jpeg' || $mime_type === 'image/jpg'){
                        error_log('Square Thumbnails - JPEG with transparent background - will convert to PNG');
                        // For JPEG, we still set up transparency, will convert to PNG during save
                        imagealphablending($newim, false);
                        imagesavealpha($newim, true);
                        $transparent = imagecolorallocatealpha($newim, 0, 0, 0, 127);
                        imagefilledrectangle($newim, 0, 0, $sizes->sqW, $sizes->sqH, $transparent);
                        imagealphablending($newim, true);
                    }
                }
                else {
                    // Use background color or color from image
                    if($bg_type === 'image'){
                        $bgcolor = $this->getColor($im);
                    } else {
                        // Use custom color or fall back to white
                        $bgcolor = $this->getBackgroundColor();
                    }
                    //create color
                    $imcolor = imagecolorallocate($newim, $bgcolor['red'], $bgcolor['green'], $bgcolor['blue']);                                  
                    //set color
                    imagefilledrectangle($newim, 0, 0, $sizes->sqW, $sizes->sqH, $imcolor);
                }

                //aici era size dar o mutam sus
                imagecopyresampled ( $newim, $im, $sizes->x, $sizes->y, 0, 0 ,  $sizes->resizedW, $sizes->resizedH, $real_width, $real_height );
                //flood fill
                //echo '<pre>'.$file.'</pre>';
                
                // Make sure we save to the thumbnail file, not the original
                $save_file = $file;
                if($attachment_id && $load_file != $file){
                    // We loaded from original but need to save to thumbnail location
                    $save_file = $file;
                    error_log('Square Thumbnails - Saving to thumbnail location: ' . $save_file);
                }
                
                // Add suffix to identify our files and handle format conversion
                $path_info = pathinfo($save_file);
                $suffix = ($bg_type === 'transparent') ? '-sqt-transparent' : '-sqt';
                
                // If we need to convert JPEG to PNG for transparency
                if($bg_type === 'transparent' && ($mime_type === 'image/jpeg' || $mime_type === 'image/jpg')){
                    $save_file = $path_info['dirname'] . '/' . $path_info['filename'] . $suffix . '.png';
                    $mime_type = 'image/png'; // Change mime type for saveIm
                    error_log('Square Thumbnails - Converting JPEG to PNG for transparency: ' . $save_file);
                } else {
                    // Keep original extension but add our suffix
                    $extension = $path_info['extension'];
                    $save_file = $path_info['dirname'] . '/' . $path_info['filename'] . $suffix . '.' . $extension;
                    error_log('Square Thumbnails - Saving with suffix: ' . $save_file);
                }
                
                error_log('Square Thumbnails - Before saveIm, file: ' . $save_file);
                $this->saveIm($mime_type,$newim,$save_file);
                error_log('Square Thumbnails - After saveIm, file: ' . $save_file);
                
                // Check if file was created
                if(file_exists($save_file)){
                    error_log('Square Thumbnails - Success! File created: ' . $save_file);
                    error_log('Square Thumbnails - File size: ' . filesize($save_file) . ' bytes');
                    
                    // If we converted to PNG, update the sizes object with new filename
                    if($save_file !== $file){
                        $sizes->filename = basename($save_file);
                        error_log('Square Thumbnails - Updated filename in sizes: ' . $sizes->filename);
                    }
                } else {
                    error_log('Square Thumbnails - ERROR: File was not created: ' . $save_file);
                }
                
                imagedestroy($newim); 
                imagedestroy($im);
                return $sizes;
  
        }
        /**
         * Get the source file for thumbnail generation
         * Handles original vs scaled images consistently
         * 
         * @param int $attachment_id
         * @return string|false Path to source file or false on failure
         */
        private function get_source_for_regeneration($attachment_id) {
            error_log('Square Thumbnails - Getting source for attachment ID: ' . $attachment_id);
            
            // Get the original file path
            $original_file = get_attached_file($attachment_id);
            if (!$original_file || !file_exists($original_file)) {
                error_log('Square Thumbnails - Original file not found: ' . $original_file);
                return false;
            }
            
            // Check for scaled version
            $metadata = wp_get_attachment_metadata($attachment_id);
            if ($metadata && isset($metadata['original_image'])) {
                // WordPress created a scaled version
                $upload_dir = dirname($original_file);
                $scaled_file = $upload_dir . '/' . $metadata['original_image'];
                
                if (file_exists($scaled_file)) {
                    error_log('Square Thumbnails - Using original (pre-scaled) file: ' . $scaled_file);
                    return $scaled_file;
                }
            }
            
            error_log('Square Thumbnails - Using standard file: ' . $original_file);
            return $original_file;
        }
        
        public function make_square_size_image($meta, $attachment_id = null){
                error_log('=== Square Thumbnails - START make_square_size_image for attachment ID: ' . $attachment_id . ' ===');
                error_log('Square Thumbnails - Called from: ' . print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3), true));
                
                // Check if sizes array exists
                if (!isset($meta['sizes']) || !is_array($meta['sizes'])) {
                    error_log('Square Thumbnails - No sizes array in metadata!');
                    error_log('Square Thumbnails - Metadata structure: ' . print_r($meta, true));
                    return $meta;
                }
                
                // Force sizes with height=0 to be square
                foreach($meta['sizes'] as $size => &$size_data) {
                    if($size_data['width'] > 0 && $size_data['height'] == 0) {
                        error_log("Square Thumbnails - Size $size has height=0, making it square: {$size_data['width']}x{$size_data['width']}");
                        $size_data['height'] = $size_data['width'];
                    }
                    // Also check for WooCommerce specific sizes that might have incorrect dimensions
                    if(strpos($size, 'woocommerce') !== false || strpos($size, 'shop_') !== false) {
                        if($size_data['width'] > 0 && $size_data['height'] != $size_data['width']) {
                            error_log("Square Thumbnails - WooCommerce size $size is not square, forcing square: {$size_data['width']}x{$size_data['width']}");
                            $size_data['height'] = $size_data['width'];
                        }
                    }
                }
                
                // Check if image is already square
                $force = get_option($this->option_name.'_force', false);
                if(isset($meta['width']) && isset($meta['height']) && $meta['width'] == $meta['height']) {
                    error_log('Square Thumbnails - Main image is already square: ' . $meta['width'] . 'x' . $meta['height'] . ' (force=' . ($force ? 'true' : 'false') . ')');
                    // Don't skip processing entirely - still need to check thumbnails
                }
                
                // Add detailed debug logging
                error_log('Square Thumbnails - Full metadata before processing: ' . print_r($meta, true));
                
                if(!function_exists('imagecreatefromjpeg')){
                    error_log('Square Thumbnails - GD library function imagecreatefromjpeg not available');
                    error_log('Square Thumbnails - Available image functions: ' . print_r(get_extension_funcs('gd'), true));
                    return $meta;
                }
                
                // Get the mime type from the correct key
                $mime_type = '';
                if(isset($meta['type'])){
                    $mime_type = $meta['type'];
                } elseif(isset($meta['mime-type'])){
                    $mime_type = $meta['mime-type'];
                }
                
                // Try to get mime type from file if not found
                if(empty($mime_type) && isset($meta['file'])){
                    $file_path = $this->getPaths($meta['file']);
                    if(file_exists($file_path->file)){
                        $mime_type = wp_check_filetype($file_path->file)['type'];
                    }
                }
                
                // Check if GD library supports the image format
                $supported_formats = $this->get_supported_formats();
                if(!in_array($mime_type, $supported_formats)){
                    error_log('Square Thumbnails - Unsupported format: ' . $mime_type);
                    return $meta;
                }
                
                $force = get_option($this->option_name.'_force', false);
                if($meta['width']===$meta['height'] && !$force){
                    error_log('Square Thumbnails - Image already square, skipping (force=' . ($force ? 'true' : 'false') . ')');
                    return $meta;
                }  
                
                if($force && $meta['width']===$meta['height']){
                    error_log('Square Thumbnails - Image already square but FORCE is enabled, continuing processing');
                } 
                
                // Check for small images
                $min_size = get_option($this->option_name.'_min_size', 200);
                $small_action = get_option($this->option_name.'_small_action', 'skip');
                
                if(($meta['width'] < $min_size || $meta['height'] < $min_size)){
                    error_log('Square Thumbnails - Image is smaller than minimum size: ' . $meta['width'] . 'x' . $meta['height']);
                    
                    switch($small_action){
                        case 'skip':
                            error_log('Square Thumbnails - Skipping small image processing');
                            return $meta;
                            break;
                        case 'error':
                            error_log('Square Thumbnails - Error: Image too small to process');
                            // Add an admin notice for the user
                            add_filter('admin_notices', function() use ($meta) {
                                echo '<div class="notice notice-warning is-dismissible"><p>' . 
                                    esc_html__('Square Thumbnails: Image is smaller than minimum size (' . $meta['width'] . 'x' . $meta['height'] . '). Processing skipped.', 'square-thumbnails') . 
                                    '</p></div>';
                            });
                            return $meta;
                            break;
                        case 'process':
                            error_log('Square Thumbnails - Processing small image anyway');
                            // Continue processing
                            break;
                    }
                }

                $file=$meta['file'];                
                $path=$this->getPaths($file);    
                if(!isset($meta['type']) && !isset($meta['mime-type'])){
                    $meta['type'] = $mime_type;
                } 
                $this->file=$path->file;
                $this->dir=$path->dir;
                $this->width=$meta['width'];
                $this->height=$meta['height'];
                //load the original image in $this->im
                // Always use the original file, not the already processed one
                $original_file = $path->file;
                error_log('Square Thumbnails - Loading original image from: ' . $original_file);
                
                // Make sure we're using the original file, not a thumbnail
                if(!file_exists($original_file)){
                    error_log('Square Thumbnails - Original file not found, trying alternate paths');
                    // Try to find the original by removing size suffix
                    $original_file = preg_replace('/-\d+x\d+(\.[^.]+)$/', '$1', $original_file);
                    error_log('Square Thumbnails - Trying: ' . $original_file);
                }
                
                $this->createIm($mime_type, $original_file, $this->im);
                
                // Check if image was loaded successfully
                if(!$this->im){
                    error_log('Square Thumbnails - Failed to load image');
                    return $meta;
                }
                
                error_log('Square Thumbnails - Image loaded successfully');
                
                $allsizes=$this->allSizes();
                
                //create all sizes
                $isallsizes=get_option($this->option_name.'_addallsizes');
                error_log('Square Thumbnails - isallsizes option: ' . ($isallsizes ? 'true' : 'false'));
                error_log('Square Thumbnails - All available sizes: ' . print_r($allsizes, true));
                
                if(!empty($isallsizes)){
                    error_log('Square Thumbnails - Creating ALL sizes...');
                        $parts = pathinfo($file);             
                        $name=$parts['filename'];
                        $ext=$parts['extension'];
                        foreach($allsizes as $szname=>$sz){
                            if(!isset($meta['sizes'][$szname])){
                                if(empty($sz['width'])) $sz['width']=$sz['height'];
                                if(empty($sz['height'])) $sz['height']=$sz['width'];
                                $meta['sizes'][$szname]=array(
                                    'file'=>$name.'-'.$sz['width'].'x'.$sz['height'].'.'.$ext,
                                    'width'=>$sz['width'],
                                    'height'=>$sz['height'],
                                    'mime-type'=>$mime_type,
                                );
                            }
                        }
                }                
                
                //end create all sizes
                
                // Check if we need to cleanup old thumbnails (format change)
                if($attachment_id) {
                    $bg_type = get_option($this->option_name.'_bg_type', 'color');
                    $current_format = ($bg_type === 'transparent') ? 'transparent' : 'color';
                    
                    // Get current metadata to check existing files
                    $existing_meta = wp_get_attachment_metadata($attachment_id);
                    $format_changed = false;
                    
                    if($existing_meta && isset($existing_meta['sizes'])) {
                        foreach($existing_meta['sizes'] as $size => $data) {
                            $file_ext = pathinfo($data['file'], PATHINFO_EXTENSION);
                            if(($current_format === 'transparent' && $file_ext === 'jpg') ||
                               ($current_format !== 'transparent' && $file_ext === 'png' && strpos($data['file'], '-sqt') !== false)) {
                                $format_changed = true;
                                break;
                            }
                        }
                    }
                    
                    if($format_changed) {
                        error_log('Square Thumbnails - Format change detected, cleaning up old files');
                        $this->cleanup_old_square_thumbnails($attachment_id, $current_format);
                    }
                }
                
                // Get selected sizes
                $selected_sizes = get_option($this->option_name.'_selected_sizes', array());
                error_log('Square Thumbnails - Selected sizes from options: ' . print_r($selected_sizes, true));
                error_log('Square Thumbnails - Available sizes in meta: ' . print_r(array_keys($meta['sizes']), true));
                
                foreach($meta['sizes'] as $size=>$m){
                    // Skip if sizes are selected and this size is not in the selection
                    if(!empty($selected_sizes) && !in_array($size, $selected_sizes)){
                        // Always process WooCommerce sizes regardless of selection
                        if(!(strpos($size, 'woocommerce') !== false || strpos($size, 'shop_') !== false)) {
                            error_log('Square Thumbnails - Skipping size: ' . $size . ' (not in selected sizes)');
                            continue;
                        }
                        error_log('Square Thumbnails - Processing WooCommerce size despite not in selection: ' . $size);
                    }
                    
                    error_log('Square Thumbnails - Processing size: ' . $size);
                    
                    // Set the correct file path for this size
                    error_log('Square Thumbnails - Original file name for size ' . $size . ': ' . $m['file']);
                    
                    // Build the full path correctly
                    $size_file = $m['file'];
                    
                    // If file contains directory separator, it's a relative path
                    if(strpos($size_file, '/') !== false) {
                        // Get just the filename
                        $size_file = basename($size_file);
                    }
                    
                    // Build full path: upload_dir + year/month + filename
                    $full_dir = dirname($path->file) . '/';
                    $m['file'] = $full_dir . $size_file;
                    
                    error_log('Square Thumbnails - Full path for size ' . $size . ': ' . $m['file']);
                    
                    // Ensure mime type is set for each size
                    if(!isset($m['mime-type']) && !isset($m['type'])){
                        $m['mime-type'] = $mime_type;
                    }
                    
                    // Check if size already exists and is square
                    $force = get_option($this->option_name.'_force', false);
                    
                    // Always force processing for WooCommerce sizes
                    if(strpos($size, 'woocommerce') !== false || strpos($size, 'shop_') !== false) {
                        $force = true;
                        error_log('Square Thumbnails - Forcing processing for WooCommerce size: ' . $size);
                    }
                    
                    if($m['width'] === $m['height'] && !$force){
                        error_log('Square Thumbnails - Size ' . $size . ' is already square, skipping (force=' . ($force ? 'true' : 'false') . ')');
                        continue;
                    }
                    
                    if($force && $m['width'] === $m['height']){
                        error_log('Square Thumbnails - Size ' . $size . ' is already square but FORCE is enabled, regenerating');
                    }
                    
                    error_log('Square Thumbnails - Calling create_square for size: ' . $size);
                    $result=$this->create_square($m, $attachment_id);   
                    if($result){                 
                        error_log('Square Thumbnails - create_square returned: ' . print_r($result, true));
                        $meta['sizes'][$size]['width']=$result->sqW;
                        $meta['sizes'][$size]['height']=$result->sqH;
                        
                        // If filename was changed (JPEG to PNG conversion), update metadata
                        if(isset($result->filename)){
                            $meta['sizes'][$size]['file'] = $result->filename;
                            error_log('Square Thumbnails - Updated filename for size ' . $size . ': ' . $result->filename);
                        }
                        
                        error_log('Square Thumbnails - Updated size ' . $size . ' to: ' . $result->sqW . 'x' . $result->sqH);
                    } else {
                        error_log('Square Thumbnails - create_square returned FALSE for size: ' . $size);
                    }
                }
                

                
                // Disabled original image processing to prevent modifying source images
                $original=get_option($this->option_name.'_tooriginal');
                // Commented out to protect original images
                /*
                if(!empty($original)){
                    $result = $this->create_square($meta, $attachment_id);
                    if($result){                                       
                        if($meta['width']>$meta['height']){
                            $meta['height']=$meta['width'];
                        }
                        else{
                            $meta['width']=$meta['height'];
                        }
                    }                    
                }
                */  
                
                // Clean up memory
                if($this->im && is_resource($this->im)){
                    imagedestroy($this->im);
                }
                
                error_log('Square Thumbnails - END processing');
                return $meta;
        }

        
 function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); 
    $rgbArray = array();
    if (strlen($hexStr) == 6) { 
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { 
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; 
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; 
}       
        
	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
        
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Square_Thumbnails_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Square_Thumbnails_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
                wp_enqueue_style( 'wp-color-picker' ); 
		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/square-thumbnails-admin.css', array(), $this->version, 'all' );

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Square_Thumbnails_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Square_Thumbnails_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

         
        // Include our custom jQuery file with WordPress Color Picker dependency
                //wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/square-thumbnails-admin.js', array( 'wp-color-picker' ), false, true ); 
		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/square-thumbnails-admin.js', array( 'jquery','wp-color-picker','jquery-ui-tabs' ), $this->version, false );
		
		// Enqueue media script for media library pages
		$screen = get_current_screen();
		if ($screen && ($screen->id === 'upload' || $screen->id === 'attachment' || strpos($screen->id, 'attachment') !== false)) {
			wp_enqueue_script( $this->plugin_name . '-media', plugin_dir_url( __FILE__ ) . 'js/square-thumbnails-media.js', array( 'jquery' ), $this->version, false );
		}
		
		// Also enqueue on media modal and edit attachment pages
		global $pagenow;
		if (in_array($pagenow, array('post.php', 'post-new.php', 'media-new.php', 'media.php', 'upload.php'))) {
			wp_enqueue_script( $this->plugin_name . '-media', plugin_dir_url( __FILE__ ) . 'js/square-thumbnails-media.js', array( 'jquery' ), $this->version, false );
		}

	}
        
        
        function sqt_settings_save() {
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('You do not have sufficient permissions to perform this action.'));
            }
			
			if (!isset($_POST['sqt_nonce']) || !wp_verify_nonce($_POST['sqt_nonce'], 'sqt_save_settings')) {
				wp_die(esc_html__('Nonce verification failed.', 'square-thumbnails'));
			}
            // Do whatever you need with update_option() here.
            // You have full access to the $_POST object.
            update_option($this->option_name.'_halign', sanitize_text_field($_POST['halign']));
            update_option($this->option_name.'_valign', sanitize_text_field($_POST['valign']));
            // Ensure proper color format
            $color = sanitize_hex_color($_POST['bgcolor']);
            if (empty($color) && !empty($_POST['bgcolor'])) {
                // Try with # prefix if not present
                $color = sanitize_hex_color('#' . $_POST['bgcolor']);
            }
            update_option($this->option_name.'_bgcolor', $color);
            update_option($this->option_name.'_bg_type', sanitize_text_field($_POST['bg_type']));
            update_option($this->option_name.'_addallsizes', intval($_POST['addallsizes']));
            update_option($this->option_name.'_force', intval($_POST['force']));
            update_option($this->option_name.'_min_size', intval($_POST['min_size']));
            update_option($this->option_name.'_small_action', sanitize_text_field($_POST['small_action']));
            update_option($this->option_name.'_jpeg_quality', intval($_POST['jpeg_quality']));
            
            // Handle selected_sizes array properly
            $selected_sizes = isset($_POST['selected_sizes']) ? array_map('sanitize_text_field', $_POST['selected_sizes']) : array();
            update_option($this->option_name.'_selected_sizes', $selected_sizes);
            
            // Debug log
            error_log('Square Thumbnails - Selected sizes saved: ' . print_r($selected_sizes, true));
            
            wp_send_json_success('Settings saved successfully!');
        }
        
        public function regenerate_thumbnails() {
            if (!current_user_can('manage_options')) {
                wp_send_json_error('You do not have sufficient permissions to perform this action.');
            }
            
            if (!isset($_POST['sqt_nonce']) || !wp_verify_nonce($_POST['sqt_nonce'], 'sqt_save_settings')) {
                wp_send_json_error('Nonce verification failed.');
            }
            
            $sizes = isset($_POST['sizes']) ? array_map('sanitize_text_field', $_POST['sizes']) : array();
            // Handle force parameter - JS sends 1/0, not true/false
            $force = isset($_POST['force']) ? ($_POST['force'] == '1' || $_POST['force'] === 1) : false;
            $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
            $batch_size = isset($_POST['batch_size']) ? intval($_POST['batch_size']) : 5;
            
            error_log('Square Thumbnails - Regenerate called with:');
            error_log('Sizes: ' . print_r($sizes, true));
            error_log('Force: ' . ($force ? 'true' : 'false'));
            error_log('Offset: ' . $offset);
            error_log('Batch size: ' . $batch_size);
            
            // Get all image attachments
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/bmp'),
                'post_status' => 'inherit',
                'posts_per_page' => $batch_size,
                'offset' => $offset,
                'orderby' => 'ID',
                'order' => 'ASC'
            );
            
            $attachments = get_posts($args);
            error_log('Found ' . count($attachments) . ' attachments in this batch');
            
            // Get total count
            $count_args = $args;
            unset($count_args['posts_per_page']);
            unset($count_args['offset']);
            $count_args['fields'] = 'ids';
            $count_args['posts_per_page'] = -1; // Get ALL posts, not just default limit
            $total_attachments = count(get_posts($count_args));
            error_log('Total attachments in media library: ' . $total_attachments);
            
            $processed = $offset;
            $items_in_batch = 0;
            
            foreach ($attachments as $attachment) {
                $items_in_batch++;
                $attachment_id = $attachment->ID;
                $metadata = wp_get_attachment_metadata($attachment_id);
                
                if (!$metadata) {
                    continue;
                }
                
                // Check which sizes need regeneration
                $regenerate_needed = false;
                if ($force) {
                    // With force=true, always regenerate
                    $regenerate_needed = true;
                } else {
                    foreach ($sizes as $size) {
                        if (!isset($metadata['sizes'][$size]) || 
                            $metadata['sizes'][$size]['width'] !== $metadata['sizes'][$size]['height']) {
                            $regenerate_needed = true;
                            break;
                        }
                        // Also regenerate if this size exists and is square (settings might have changed)
                        if (isset($metadata['sizes'][$size]) && 
                            $metadata['sizes'][$size]['width'] === $metadata['sizes'][$size]['height']) {
                            // Check if the file has an -sqt suffix, if so, it needs regeneration with new settings
                            if (isset($metadata['sizes'][$size]['file']) && strpos($metadata['sizes'][$size]['file'], '-sqt') !== false) {
                                $regenerate_needed = true;
                                break;
                            }
                        }
                    }
                }
                
                if ($regenerate_needed) {
                    error_log("Image $attachment_id needs regeneration");
                    
                    // Store current selected_sizes option temporarily
                    $original_selected_sizes = get_option($this->option_name.'_selected_sizes', array());
                    
                    // Set temporary selected sizes for regeneration
                    update_option($this->option_name.'_selected_sizes', $sizes);
                    
                    // First regenerate WordPress thumbnails with our square dimensions
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    $file = get_attached_file($attachment_id);
                    
                    // Generate fresh metadata (this creates the files)
                    $fresh_metadata = wp_generate_attachment_metadata($attachment_id, $file);
                    
                    // Now process with our square thumbnails logic
                    $new_metadata = $this->make_square_size_image($fresh_metadata, $attachment_id);
                    
                    // Update attachment metadata
                    wp_update_attachment_metadata($attachment_id, $new_metadata);
                    
                    // Restore original selected_sizes option
                    update_option($this->option_name.'_selected_sizes', $original_selected_sizes);
                    
                    error_log("Image $attachment_id regenerated successfully");
                } else {
                    error_log("Image $attachment_id does not need regeneration");
                }
                
            }
            
            // Update processed count based on items in this batch
            $processed += $items_in_batch;
            
            $completed = ($processed >= $total_attachments);
            
            wp_send_json_success(array(
                'processed' => $processed,
                'total' => $total_attachments,
                'offset' => $processed,
                'completed' => $completed
            ));
        }
        
        /**
         * Add regenerate button to attachment details
         */
        public function add_regenerate_button($form_fields, $post) {
            error_log('Square Thumbnails: Adding regenerate button for attachment ID: ' . $post->ID);
            
            if (!wp_attachment_is_image($post->ID)) {
                error_log('Square Thumbnails: Attachment is not an image, skipping button');
                return $form_fields;
            }
            
            // Generate nonce for security
            $nonce = wp_create_nonce('sqt_regenerate_single_' . $post->ID);
            
            $form_fields['sqt_regenerate'] = array(
                'label' => __('Square Thumbnails', 'square-thumbnails'),
                'input' => 'html',
                'html' => '<button type="button" class="button sqt-regenerate-single" data-attachment-id="' . $post->ID . '" data-nonce="' . $nonce . '">' . 
                         __('Regenerate Square Thumbnails', 'square-thumbnails') . '</button>' .
                         '<span class="sqt-single-spinner spinner" style="float: none; margin-left: 5px;"></span>' .
                         '<span class="sqt-single-message" style="margin-left: 10px;"></span>' .
                         '<script>console.log("Square Thumbnails: Button added for attachment ID ' . $post->ID . '");</script>',
                'helps' => __('Regenerate square thumbnails for this image using current settings.', 'square-thumbnails')
            );
            
            error_log('Square Thumbnails: Button HTML added to form fields');
            return $form_fields;
        }
        
        /**
         * Add bulk action to media library
         */
        public function add_bulk_action($bulk_actions) {
            $bulk_actions['sqt_regenerate'] = __('Regenerate Square Thumbnails', 'square-thumbnails');
            return $bulk_actions;
        }
        
        /**
         * Handle bulk action
         */
        public function handle_bulk_action($redirect_to, $action, $post_ids) {
            if ($action !== 'sqt_regenerate') {
                return $redirect_to;
            }
            
            $processed = 0;
            foreach ($post_ids as $post_id) {
                if (wp_attachment_is_image($post_id)) {
                    $metadata = wp_get_attachment_metadata($post_id);
                    if ($metadata) {
                        $new_metadata = $this->make_square_size_image($metadata, $post_id);
                        wp_update_attachment_metadata($post_id, $new_metadata);
                        $processed++;
                    }
                }
            }
            
            $redirect_to = add_query_arg('sqt_regenerated', $processed, $redirect_to);
            return $redirect_to;
        }
        
        /**
         * Regenerate single image via AJAX
         */
        public function regenerate_single_image() {
            error_log('=== Square Thumbnails: regenerate_single_image called ===');
            error_log('Square Thumbnails: POST data: ' . print_r($_POST, true));
            
            if (!current_user_can('upload_files')) {
                error_log('Square Thumbnails: Insufficient permissions.');
                wp_send_json_error('Insufficient permissions.');
            }
            
            $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;
            $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : '';
            
            error_log('Square Thumbnails: Attachment ID: ' . $attachment_id);
            error_log('Square Thumbnails: Nonce: ' . $nonce);
            
            // Get the original file path
            $original_file = get_attached_file($attachment_id);
            error_log('Square Thumbnails: Original file path: ' . $original_file);
            
            // Verify nonce if provided
            if (!empty($nonce) && !wp_verify_nonce($nonce, 'sqt_regenerate_single_' . $attachment_id)) {
                error_log('Square Thumbnails: Invalid nonce.');
                wp_send_json_error('Security check failed.');
            }
            
            if (!$attachment_id || !wp_attachment_is_image($attachment_id)) {
                error_log('Square Thumbnails: Invalid attachment ID or not an image.');
                wp_send_json_error('Invalid attachment ID.');
            }
            
            $metadata = wp_get_attachment_metadata($attachment_id);
            if (!$metadata) {
                error_log('Square Thumbnails: Could not get attachment metadata.');
                wp_send_json_error('Could not get attachment metadata.');
            }
            
            error_log('Square Thumbnails: Original metadata: ' . print_r($metadata, true));
            
            // Check plugin options
            $selected_sizes = get_option($this->option_name.'_selected_sizes', array());
            $isallsizes = get_option($this->option_name.'_addallsizes');
            error_log('Square Thumbnails: Selected sizes setting: ' . print_r($selected_sizes, true));
            error_log('Square Thumbnails: All sizes setting: ' . ($isallsizes ? 'true' : 'false'));
            
            // Force regeneration by temporarily setting force flag
            $old_force = get_option($this->option_name.'_force', false);
            update_option($this->option_name.'_force', true);
            error_log('Square Thumbnails: Forcing regeneration for single image');
            
            // Regenerate thumbnails
            $new_metadata = $this->make_square_size_image($metadata, $attachment_id);
            
            // Restore original force setting
            update_option($this->option_name.'_force', $old_force);
            
            error_log('Square Thumbnails: Returned metadata: ' . print_r($new_metadata, true));
            
            // Check if metadata actually changed
            if($new_metadata === $metadata) {
                error_log('Square Thumbnails: WARNING - Metadata unchanged!');
            } else {
                error_log('Square Thumbnails: Metadata has changed, updating...');
            }
            
            wp_update_attachment_metadata($attachment_id, $new_metadata);
            
            error_log('Square Thumbnails: Successfully completed single regeneration');
            wp_send_json_success('Square thumbnails regenerated successfully.');
        }
        
        /**
         * Show admin notice after bulk action
         */
        public function bulk_action_admin_notice() {
            if (!empty($_REQUEST['sqt_regenerated'])) {
                $count = intval($_REQUEST['sqt_regenerated']);
                $message = sprintf(
                    _n(
                        'Square thumbnails regenerated for %s image.',
                        'Square thumbnails regenerated for %s images.',
                        $count,
                        'square-thumbnails'
                    ),
                    number_format_i18n($count)
                );
                
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($message) . '</p></div>';
            }
        }
        
        /**
         * Cleanup square thumbnails when attachment is deleted
         * This ensures no orphaned files remain
         * 
         * @param int $attachment_id The attachment being deleted
         */
        public function cleanup_on_attachment_delete($attachment_id) {
            error_log('Square Thumbnails - Cleaning up files for deleted attachment: ' . $attachment_id);
            
            $metadata = wp_get_attachment_metadata($attachment_id);
            if (!$metadata || !isset($metadata['sizes'])) {
                return;
            }
            
            $upload_dir = wp_upload_dir();
            $base_dir = dirname($upload_dir['basedir'] . '/' . $metadata['file']);
            
            // Clean up all our custom square thumbnail files
            foreach ($metadata['sizes'] as $size => $data) {
                // Look for any files with -sqt suffix
                $file_basename = pathinfo($data['file'], PATHINFO_FILENAME);
                $files_to_check = glob($base_dir . '/' . $file_basename . '-sqt*');
                
                foreach ($files_to_check as $file) {
                    if (file_exists($file)) {
                        error_log('Square Thumbnails - Deleting file on attachment delete: ' . $file);
                        @unlink($file);
                    }
                }
            }
            
            // Also clean up scaled versions if they exist
            if (isset($metadata['original_image'])) {
                $scaled_path = $base_dir . '/' . $metadata['original_image'];
                if (file_exists($scaled_path)) {
                    // Check for square versions of the scaled file
                    $scaled_basename = pathinfo($metadata['original_image'], PATHINFO_FILENAME);
                    $scaled_files = glob($base_dir . '/' . $scaled_basename . '-sqt*');
                    
                    foreach ($scaled_files as $file) {
                        if (file_exists($file)) {
                            error_log('Square Thumbnails - Deleting scaled square file: ' . $file);
                            @unlink($file);
                        }
                    }
                }
            }
        }
        
        
        public function square_settings(){
            //$this->enqueue_scripts();


            
        
        }
        public function old_wp_version_error(){
            return;
            ?>
                <div class="notice-dismiss">

                </div>
                <?php
        }
}
