<?php
/**
 * Name: Auto Image Upload Rename
 * Description: Automatically clean uploaded image filenames by converting to lowercase, replacing spaces and special characters with hyphens, and adding three-character unique ID for organization
 * Category: Media
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "SEO-Friendly Filenames",
 *     "description": "Automatically rename DSC_0001.jpg uploads to post-slug-based names for better image SEO instead of meaningless camera filenames."
 *   },
 *   {
 *     "title": "Client Upload Cleanup",
 *     "description": "Convert client uploads like 'Screenshot 2024-03-15 at 9.23.45 AM.png' to clean, readable filenames matching post titles."
 *   },
 *   {
 *     "title": "Server Compatibility",
 *     "description": "Remove spaces, special characters, and non-ASCII characters from filenames to prevent server issues and broken image paths."
 *   }
 * ]
 * Added: 2025-07-26
 * Tags: images, upload, rename, seo, media
 * WhereToFind: {
 *   "location": "Media Library",
 *   "url": "upload.php",
 *   "instructions": "Upload an image - filename will be cleaned and lowercase with unique ID",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardImageUploadRename {

    public function __construct() {
        add_filter('wp_handle_upload_prefilter', [$this, 'rename_uploaded_file']);
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }

    public function rename_uploaded_file($file) {
        // Only process images
        if (!isset($file['type']) || strpos($file['type'], 'image') === false) {
            return $file;
        }

        if (!isset($file['name']) || empty($file['name'])) {
            return $file;
        }

        $filename = $file['name'];
        $info = pathinfo($filename);
        $ext = isset($info['extension']) ? '.' . $info['extension'] : '';
        $name = basename($filename, $ext);

        // Clean the filename
        $name = $this->clean_filename($name);

        // Add short unique identifier to prevent collisions (3 chars)
        $name = $name . '-' . substr(md5(uniqid(wp_rand(), true)), 0, 3);

        // Reconstruct filename
        $file['name'] = $name . $ext;

        return $file;
    }

    private function clean_filename($filename) {
        // Convert to lowercase
        $filename = strtolower($filename);

        // Remove special characters (keep letters, numbers, hyphens, underscores, dots, and @)
        $filename = preg_replace('/[^a-z0-9-_.@]/', '-', $filename);

        // Remove multiple dashes
        $filename = preg_replace('/-+/', '-', $filename);

        // Trim dashes from ends
        $filename = trim($filename, '-');

        // Prevent empty filename
        if (empty($filename)) {
            $filename = 'image';
        }

        // Limit length
        if (strlen($filename) > 50) {
            $filename = substr($filename, 0, 50);
            // Re-trim in case we cut at a dash
            $filename = trim($filename, '-');
        }

        return $filename;
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardImageUploadRename();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
