<?php
/**
 * Plugin Name: Smart Media Cleanup
 * Plugin URI:  https://marketupmedia.gr/smart-media-cleanup
 * Description: Automatically delete unused media when posts are removed, and clean up orphan attachments in your media library.
 * Version:     1.1.0
 * Tested up to:   7.0
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Author:      MarketUp Media
 * Author URI:  https://marketupmedia.gr
 * Text Domain: smart-media-cleanup
 * Domain Path: /languages
 * License:     GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

define( 'SMC_VERSION', '1.1.0' );
define( 'SMC_FILE', __FILE__ );
define( 'SMC_PATH', plugin_dir_path( __FILE__ ) );
define( 'SMC_URL', plugin_dir_url( __FILE__ ) );

if ( file_exists( SMC_PATH . 'vendor/autoload.php' ) ) {
	require_once SMC_PATH . 'vendor/autoload.php';
} else {
	require_once SMC_PATH . 'includes/class-plugin.php';
	require_once SMC_PATH . 'includes/class-settings.php';
	require_once SMC_PATH . 'includes/class-admin-notices.php';
	require_once SMC_PATH . 'includes/class-logger.php';
	require_once SMC_PATH . 'includes/class-attachment-usage.php';
	require_once SMC_PATH . 'includes/class-cleanup-on-delete.php';
	require_once SMC_PATH . 'includes/class-orphan-scanner.php';
	require_once SMC_PATH . 'includes/class-orphan-admin.php';
	require_once SMC_PATH . 'includes/class-virtual-folders.php';
}

register_activation_hook( __FILE__, 'smart_media_cleanup_activate' );
register_deactivation_hook( __FILE__, 'smart_media_cleanup_deactivate' );

function smart_media_cleanup_activate() {
	$defaults = array(
		'enabled'               => true,
		'post_types'            => array( 'post' ),
		'delete_featured'       => true,
		'delete_attached'       => true,
		'delete_meta_galleries' => true,
		'meta_keys'             => array(),
		'trigger'               => 'permanent',
		'check_usage'           => true,
		'enable_log'             => true,
		'log_retention_days'     => 30,
		'enable_virtual_folders' => false,
		'folder_names'           => array(),
	);

	$existing = get_option( 'smc_settings' );

	if ( false === $existing || ! is_array( $existing ) ) {
		// Fresh install — write defaults.
		add_option( 'smc_settings', $defaults );
	} else {
		// Update — merge so new keys get their defaults without touching existing values.
		update_option( 'smc_settings', array_merge( $defaults, $existing ) );
	}

	Smart_Media_Cleanup\Logger::install_table();
}

function smart_media_cleanup_deactivate() {
	// Intentionally empty — data is preserved on deactivate.
}

add_action( 'plugins_loaded', array( 'Smart_Media_Cleanup\Plugin', 'instance' ) );
