<?php
/**
 * Plugin Name:       Imagi Boost
 * Plugin URI:        https://eslamdev.com/plugins/image-boost
 * Description:       A powerful, zero-API local image compression & optimization plugin. Supports WebP, AVIF, WooCommerce, bulk optimization, and background processing.
 * Version:           1.1.0
 * Requires at least: 6.0
 * Requires PHP:      7.4
 * Author:            EsLaM Hamed
 * Author URI:        https://eslamdev.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       image-boost
 * Domain Path:       /languages
 */

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

// ─── Plugin Constants ─────────────────────────────────────────
define('IMGBOOST_VERSION', '1.1.0');
define('IMGBOOST_FILE', __FILE__);
define('IMGBOOST_PATH', plugin_dir_path(__FILE__));
define('IMGBOOST_URL', plugin_dir_url(__FILE__));
define('IMGBOOST_BASENAME', plugin_basename(__FILE__));
$imgboost_upload_dir = wp_get_upload_dir();
define('IMGBOOST_BACKUP_DIR', wp_normalize_path(trailingslashit($imgboost_upload_dir['basedir']) . 'imgboost-backups/'));
// ─── Autoloader ───────────────────────────────────────────────
spl_autoload_register(function ($class) {
    if (strpos($class, 'ImgBoost_') !== 0) {
        return;
    }

    $class_name = str_replace('ImgBoost_', '', $class);
    $file_name = 'class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';

    $paths = [
        IMGBOOST_PATH . 'includes/' . $file_name,
        IMGBOOST_PATH . 'admin/' . $file_name,
    ];

    foreach ($paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            break;
        }
    }
});

// Load non-class helpers
require_once IMGBOOST_PATH . 'includes/helpers.php';

// ─── Activation / Deactivation ────────────────────────────────
register_activation_hook(__FILE__, ['ImgBoost_DB', 'activate']);
register_deactivation_hook(__FILE__, ['ImgBoost_DB', 'deactivate']);

// ─── Initialize Plugin ───────────────────────────────────────
add_action('plugins_loaded', function () {
    // Init Database & Core
    ImgBoost_DB::init();

    // Setup Queue Cron action handler
    add_action('imgboost_process_queue', ['ImgBoost_Auto_Optimizer', 'process_queue']);

    // Admin UI
    if (is_admin()) {
        ImgBoost_Admin::init();
        ImgBoost_Media_Library::init();
    }

    // AJAX Handlers
    ImgBoost_Ajax::init();

    // Auto-optimize on upload
    if (get_option('imgboost_auto_optimize', 1)) {
        ImgBoost_Auto_Optimizer::init();
    }

    // Converter (Frontend output buffering)
    ImgBoost_Converter::init();
});

// Schedule the queue cron on 'init' (after translations are loaded),
// since wp_schedule_event() triggers the 'cron_schedules' filter below,
// which uses __() and must not run before the 'init' action.
add_action('init', ['ImgBoost_Auto_Optimizer', 'setup_cron']);

// ─── Custom Cron Schedules ──────────────────────────────────
add_filter('cron_schedules', function ($schedules) {
    if (!isset($schedules['imgboost_five_minutes'])) {
        $schedules['imgboost_five_minutes'] = [
            'interval' => 300,
            'display' => __('Every 5 Minutes (Image Boost)', 'image-boost')
        ];
    }
    return $schedules;
});

// ─── Admin Bar Node ──────────────────────────────────────────
add_action('admin_bar_menu', function ($wp_admin_bar) {
    if (!current_user_can('manage_options')) {
        return;
    }

    $wp_admin_bar->add_node([
        'id' => 'image-boost',
        'title' => '<span class="ab-icon dashicons-images-alt2"></span><span class="ab-label">Image Boost</span>',
        'href' => admin_url('admin.php?page=image-boost'),
    ]);

    $wp_admin_bar->add_node([
        'id' => 'image-boost-dashboard',
        'parent' => 'image-boost',
        'title' => __('Dashboard', 'image-boost'),
        'href' => admin_url('admin.php?page=image-boost'),
    ]);

    $wp_admin_bar->add_node([
        'id' => 'image-boost-bulk',
        'parent' => 'image-boost',
        'title' => __('Bulk Optimize', 'image-boost'),
        'href' => admin_url('admin.php?page=image-boost-bulk'),
    ]);

    $wp_admin_bar->add_node([
        'id' => 'image-boost-settings',
        'parent' => 'image-boost',
        'title' => __('Settings', 'image-boost'),
        'href' => admin_url('admin.php?page=image-boost-settings'),
    ]);
}, 100);

// ─── Custom Admin Footer ─────────────────────────────────────
add_filter('admin_footer_text', function ($text) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
    if (strpos($page, 'image-boost') === 0) {
        // translators: 1: Heart icon, 2: Developer name
        return sprintf(__('Designed & Developed with %1$s by %2$s', 'image-boost'), '<span style="color:#e25555;">❤️</span>', '<a href="https://eslamdev.com" target="_blank" style="text-decoration:none;font-style:italic;">EsLaM Hamed</a>');
    }
    return $text;
});

// ─── Cron Schedule for Backup Deletion ────────────────────────
add_action('imgboost_daily_cleanup', ['ImgBoost_Backup', 'auto_delete_old_backups']);
