<?php
/**
 * Plugin Name: SmartProductSEO Media Library Cleanup
 * Plugin URI: https://smartproductseo.com/product/smart-media-cleanup-for-wordpress/
 * Description: Scan, review, trash, restore, and permanently delete unused WordPress media files with a conservative, review-first cleanup workflow.
 * Version: 1.2.1
 * Author: Jolizzie
 * Author URI: https://smartproductseo.com/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: smart-media-cleanup-media-library-cleanup
 * Domain Path: /languages
 * Requires at least: 6.0
 * Requires PHP: 7.4
 */

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

/* -------------------------------------------------------
   SMARTPRODUCTSEO MEDIA LIBRARY CLEANUP CONSTANTS
------------------------------------------------------- */

if (!defined('SMCMLC_VERSION')) {
    define('SMCMLC_VERSION', '1.2.1');
}

if (!defined('SMCMLC_PLUGIN_FILE')) {
    define('SMCMLC_PLUGIN_FILE', __FILE__);
}

if (!defined('SMCMLC_PLUGIN_DIR')) {
    define('SMCMLC_PLUGIN_DIR', plugin_dir_path(__FILE__));
}

if (!defined('SMCMLC_PLUGIN_URL')) {
    define('SMCMLC_PLUGIN_URL', plugin_dir_url(__FILE__));
}

if (!defined('SMCMLC_PLUGIN_BASENAME')) {
    define('SMCMLC_PLUGIN_BASENAME', plugin_basename(__FILE__));
}

if (!defined('SMCMLC_MENU_SLUG')) {
    define('SMCMLC_MENU_SLUG', 'smartproductseo-media-cleanup');
}

/* -------------------------------------------------------
   SAFE HELPERS
------------------------------------------------------- */

if (!function_exists('smcmlc_get_current_admin_request_page')) {
    function smcmlc_get_current_admin_request_page() {
        if (!is_admin() || !isset($_GET['page'])) {
            return '';
        }

        return sanitize_key(wp_unslash($_GET['page']));
    }
}

if (!function_exists('smcmlc_require_plugin_file')) {
    function smcmlc_require_plugin_file($relative_path) {
        $relative_path = ltrim((string) $relative_path, '/');
        $path          = SMCMLC_PLUGIN_DIR . $relative_path;

        if (file_exists($path) && is_readable($path)) {
            require_once $path;
            return true;
        }

        return false;
    }
}

/* -------------------------------------------------------
   LOAD PLUGIN FILES
------------------------------------------------------- */

if (!function_exists('smcmlc_load_plugin_files')) {
    function smcmlc_load_plugin_files() {
        $plugin_files = array(
            'includes/helpers.php',
            'includes/media-scanner.php',
            'includes/scan-history.php',
            'includes/free-trash.php',
            'includes/free-permanent-delete.php',
            'includes/admin-dashboard.php',
        );

        foreach ($plugin_files as $file) {
            smcmlc_require_plugin_file($file);
        }
    }
}
add_action('plugins_loaded', 'smcmlc_load_plugin_files');

/* -------------------------------------------------------
   ACTIVATION / DEACTIVATION
------------------------------------------------------- */

if (!function_exists('smcmlc_activate_plugin')) {
    function smcmlc_activate_plugin() {
        update_option('smcmlc_version', SMCMLC_VERSION, false);

        add_option('smcmlc_last_scan_results', array());
        add_option('smcmlc_cleanup_log', array());

        add_option('smcmlc_cleanup_stats', array(
            'images_trashed'    => 0,
            'images_restored'   => 0,
            'images_deleted'    => 0,
            'bytes_moved_trash' => 0,
            'bytes_restored'    => 0,
            'bytes_deleted'     => 0,
            'last_action'       => '',
            'last_action_time'  => '',
        ));

        flush_rewrite_rules();
    }
}
register_activation_hook(__FILE__, 'smcmlc_activate_plugin');

if (!function_exists('smcmlc_deactivate_plugin')) {
    function smcmlc_deactivate_plugin() {
        flush_rewrite_rules();
    }
}
register_deactivation_hook(__FILE__, 'smcmlc_deactivate_plugin');

/* -------------------------------------------------------
   ADMIN MENU
------------------------------------------------------- */

if (!function_exists('smcmlc_register_admin_menu')) {
    function smcmlc_register_admin_menu() {
        add_menu_page(
            'SmartProductSEO Media Cleanup',
            'SmartProductSEO Media Cleanup',
            'manage_options',
            SMCMLC_MENU_SLUG,
            'smcmlc_render_admin_dashboard',
            'dashicons-format-gallery',
            58
        );

        add_submenu_page(
            SMCMLC_MENU_SLUG,
            'Dashboard / Scan Media Library',
            'Dashboard / Scan',
            'manage_options',
            SMCMLC_MENU_SLUG,
            'smcmlc_render_admin_dashboard'
        );

        add_submenu_page(
            SMCMLC_MENU_SLUG,
            'Media Library Trash Review',
            'Media Library Trash',
            'manage_options',
            'smartproductseo-media-cleanup-trash',
            'smcmlc_render_trash_review_page'
        );

        add_submenu_page(
            SMCMLC_MENU_SLUG,
            'Media Library Delete Permanently',
            'Media Library Delete',
            'manage_options',
            'smartproductseo-media-cleanup-delete',
            'smcmlc_render_delete_permanently_page'
        );
    }
}
add_action('admin_menu', 'smcmlc_register_admin_menu');

/* -------------------------------------------------------
   ADMIN ASSETS
------------------------------------------------------- */

if (!function_exists('smcmlc_is_plugin_admin_page')) {
    function smcmlc_is_plugin_admin_page($hook = '') {
        $page = smcmlc_get_current_admin_request_page();

        if ($page && strpos($page, 'smartproductseo-media-cleanup') === 0) {
            return true;
        }

        return strpos((string) $hook, 'smartproductseo-media-cleanup') !== false;
    }
}

if (!function_exists('smcmlc_enqueue_admin_assets')) {
    function smcmlc_enqueue_admin_assets($hook) {
        if (!smcmlc_is_plugin_admin_page($hook)) {
            return;
        }

        wp_enqueue_style(
            'smcmlc-admin-css',
            SMCMLC_PLUGIN_URL . 'assets/admin.css',
            array(),
            SMCMLC_VERSION
        );

        wp_enqueue_script(
            'smcmlc-admin-js',
            SMCMLC_PLUGIN_URL . 'assets/admin.js',
            array('jquery'),
            SMCMLC_VERSION,
            true
        );

        wp_localize_script(
            'smcmlc-admin-js',
            'smcmlcAdmin',
            array(
                'ajaxUrl'                         => admin_url('admin-ajax.php'),
                'nonce'                           => wp_create_nonce('smcmlc_admin_nonce'),
                'mainVersion'                     => SMCMLC_VERSION,
                'currentPage'                     => smcmlc_get_current_admin_request_page(),
                'confirmTrash'                    => 'Move selected image(s) to Trash? You can restore them from the Trash Review page.',
                'confirmDelete'                   => 'Permanent deletion cannot be undone. Please check the product/page first before deleting permanently.',
                'confirmBulkTrash'                => 'Move selected image(s) to Trash? You can restore them from the Trash Review page.',
                'confirmBulkDelete'               => 'Permanently delete selected image(s)? This cannot be undone.',
                'scanButtonText'                  => 'Scan Media Library',
                'scanningText'                    => 'Scanning...',
                'bulkTrashText'                   => 'Move Selected to Trash',
                'bulkTrashRunningText'            => 'Moving selected images...',
                'noImagesSelectedText'            => 'Please select at least one image first.',
                'bulkTrashSuccessText'            => 'Selected image(s) moved to Trash.',
                'bulkTrashErrorText'              => 'Could not move selected images to Trash.',
                'wooUsageLabel'                   => 'WooCommerce Usage',
                'protectedStatusText'             => 'Protected',
                'cleanupCandidateText'            => 'Cleanup Candidate',
                'reviewStatusText'                => 'Review',
                'bottomBulkTrashText'             => 'Move Selected to Trash',
                'stickyBulkTrashText'             => 'Move Selected to Trash',
                'selectedImagesText'              => 'image(s) selected',
                'usedInLabel'                     => 'Used In',
                'likelyUsedStatusText'            => 'Likely Used',
                'contentUsedStatusText'           => 'Used In Content',
                'contentUsageLabel'               => 'Page/Post Content',
                'usedInNoneText'                  => 'No content usage detected',
                'usedInConfidenceText'            => 'Content match found',
                'contentScannerText'              => 'Content Scanner',
                'galleryDetectedText'             => 'Product Gallery Image detected',
                'featuredDetectedText'            => 'Featured Product Image detected',
                'variationDetectedText'           => 'Variation Image detected',
                'protectedWooText'                => 'Protected WooCommerce image',
                'brokenImageStatusText'           => 'Broken Image',
                'missingFileStatusText'           => 'Missing File',
                'fileHealthText'                  => 'File Health',
                'attachmentRelationshipOnlyText'  => 'Attachment relationship only — review before deleting',
                'conservativeScannerText'         => 'Conservative safety scanner active',
                'cleanupCandidateSafetyText'      => 'Only images with no detected WooCommerce or real content usage should be treated as cleanup candidates',
                'siteLogoDetectedText'            => 'Site Logo detected',
                'customizerLogoDetectedText'      => 'Customizer Logo detected',
                'themeCustomizerText'             => 'Theme / Customizer Detection',
                'protectedLogoText'               => 'Protected site logo image',
                'headerLogoDetectedText'          => 'Header Logo detected',
                'footerLogoDetectedText'          => 'Footer Logo detected',
                'themeOptionDetectedText'         => 'Theme Option image detected',
                'themeOptionScannerText'          => 'Theme Option Scanner',
                'protectedThemeOptionText'        => 'Protected theme option image',
                'protectedHeaderLogoText'         => 'Protected header logo image',
                'protectedFooterLogoText'         => 'Protected footer logo image',
                'bulkRestoreText'                 => 'Restore Selected',
                'bulkRestoreRunningText'          => 'Restoring selected images...',
                'bulkRestoreSuccessText'          => 'Selected image(s) restored.',
                'bulkRestoreErrorText'            => 'Could not restore selected images.',
                'bulkPermanentDeleteText'         => 'Permanent Delete Selected',
                'bulkPermanentDeleteRunningText'  => 'Deleting selected images...',
                'bulkPermanentDeleteSuccessText'  => 'Selected image(s) permanently deleted.',
                'bulkPermanentDeleteErrorText'    => 'Could not permanently delete selected images.',
                'trashReviewSelectAllText'        => 'Select all trashed images',
                'storageRecoveredText'            => 'Storage Recovered',
                'imagesCleanedText'               => 'Images Cleaned',
                'trashReviewSafetyText'           => 'Trash review keeps images restorable before final cleanup.',
            )
        );
    }
}
add_action('admin_enqueue_scripts', 'smcmlc_enqueue_admin_assets');

/* -------------------------------------------------------
   PLUGIN ACTION LINKS
------------------------------------------------------- */

if (!function_exists('smcmlc_plugin_action_links')) {
    function smcmlc_plugin_action_links($links) {
        $dashboard_url = admin_url('admin.php?page=' . SMCMLC_MENU_SLUG);
        $upgrade_url   = 'https://smartproductseo.com/product/smart-media-cleanup-pro-for-wordpress/';

        $dashboard_link = '<a href="' . esc_url($dashboard_url) . '">Dashboard</a>';
        $upgrade_link   = '<a href="' . esc_url($upgrade_url) . '" target="_blank" rel="noopener noreferrer">🔑 Upgrade To PRO</a>';

        array_unshift($links, $dashboard_link, $upgrade_link);

        return $links;
    }
}
add_filter('plugin_action_links_' . SMCMLC_PLUGIN_BASENAME, 'smcmlc_plugin_action_links');