<?php


namespace SmartSyncS3;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use Exception;
use SmartSyncS3\Ajax\SMARL_AjaxHandler;
use SmartSyncS3\Ajax\SMARL_AwsConfigAjax;
use SmartSyncS3\Helpers\SMARL_Helper;
use SmartSyncS3\Models\SMARL_CloudConfig;
use SmartSyncS3\Views\SMARL_AWSWizard;
use SmartSyncS3\Views\SMARL_CustomUrl;
use SmartSyncS3\Views\SMARL_SettingsPage;


/**
 * Class SmartSync
 *
 * The SmartSync class serves as the core of the AWS S3 SmartSync plugin. It manages the initialization
 * of the plugin, handles hooks, filters, and AJAX interactions, and facilitates integration with AWS S3
 * and CloudFront. The class is designed to provide a seamless experience for synchronizing and managing
 * assets with AWS services.
 *
 * Features:
 * - Initializes filters for asset and media URL modifications.
 * - Sets up actions for plugin lifecycle events (activation, deactivation, update).
 * - Registers hooks for WordPress plugin lifecycle events.
 * - Manages AJAX requests related to AWS configuration and general plugin interactions.
 * - Enqueues admin scripts and styles for the plugin's interface.
 *
 * @package SmartSyncS3
 * @author Infinitie Technologies
 * @developer Jay Parmar
 *
 * Properties:
 * @property SMARL_CloudConfig|null $config Holds the configuration for AWS S3 and CloudFront settings.
 * @property SMARL_AwsConfigAjax|null $awsConfigAjax Manages AJAX interactions for AWS configuration.
 * @property SMARL_AjaxHandler|null $ajaxHandlers Handles general AJAX requests for plugin operations.
 * @property string $pluginRoot The root directory of the plugin.
 *
 * Usage:
 * Instantiate the class and call `initialize_actions`, `initialize_filters`, and `initialize_hooks` to set up the plugin.
 *
 * Example:
 * ```php
 * $smartSync = new SmartSync(plugin_root: plugin_dir_path(__FILE__));
 * $smartSync->initialize_actions();
 * $smartSync->initialize_filters();
 * $smartSync->initialize_hooks();
 * ```
 */
class SMARL_SmartSync
{

    /**
     * @var SMARL_CloudConfig|null $config Holds the configuration for AWS S3 and CloudFront settings.
     * @access private
     */
    private ?SMARL_CloudConfig $config;

    /**
     * @var SMARL_AwsConfigAjax|null $awsConfigAjax Handles AJAX requests related to AWS configuration.
     * @access private
     */
    private ?SMARL_AwsConfigAjax $awsConfigAjax;

    /**
     * @var SMARL_AjaxHandler|null $ajaxHandlers Handles general AJAX requests for the plugin.
     * @access private
     */
    private ?SMARL_AjaxHandler $ajaxHandlers;

    /**
     * @var string $pluginRoot The root directory of the plugin.
     * @access private
     */
    private string $pluginRoot;

    /**
     * Constructor for the SmartSync class.
     *
     * @param string $plugin_root The root directory of the plugin.
     * @developer Jay Parmar
     */
    public function __construct(string $plugin_root)
    {
        $this->config = SMARL_CloudConfig::load();
        $this->pluginRoot = $plugin_root;
        $this->awsConfigAjax = new SMARL_AwsConfigAjax(configuration: $this->config);
        $this->ajaxHandlers = new SMARL_AjaxHandler(configuration: $this->config);
    }


    /**
     * Initializes filters for modifying asset and attachment URLs.
     * @developer Jay Parmar
     */
    public function initializeFilters(): void
    {
        if ($this->config->useCdnForAssets) {
            add_filter('script_loader_src', [$this, 'replaceBaseUrl'], 10, 2);
            add_filter('style_loader_src', [$this, 'replaceBaseUrl'], 10, 2);
        }
        add_filter('wp_get_attachment_url', [$this, 'getAttachmentUrl'], 10, 2);
        add_filter('wp_delete_file', [$this, 'deleteFromS3'], 10, 2);
    }
    /**
     * Initializes actions for plugin lifecycle events and admin scripts.
     * @developer Jay Parmar
     */
    public function initializeActions(): void{
        add_action('activated_plugin', [$this, 'onPluginActivation']);
        add_action('add_attachment', [$this, 's3UploadNewMedia']);
        $this->awsConfigAjax->initializeActions();
        $this->ajaxHandlers->initializeActions();
        add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);


    }

    public function initializeViews(): void
    {

        add_action('plugins_loaded', function () {
            $cloudConfig = SMARL_CloudConfig::load();
            $settingsPage = new SMARL_SettingsPage($cloudConfig);
            $settingsPage->loadView();
            $awsWizardPage = new SMARL_AWSWizard($cloudConfig);
            $awsWizardPage->loadView();
            $customUrlPage = new SMARL_CustomUrl($cloudConfig);
            $customUrlPage->loadView();
        });
    }

    public function registerAutoload(): void
    {
        if (file_exists(plugin_dir_path($this->pluginRoot) . 'vendor/autoload.php')) {
            require_once plugin_dir_path($this->pluginRoot) . 'vendor/autoload.php';
        }
    }

    /**
     * Registers hooks for activation, deactivation, and uninstallation of the plugin.
     * @developer Jay Parmar
     */
    public function initializeHooks(): void
    {
        register_activation_hook($this->pluginRoot, [self::class, 'activateRegisterHook']);
        register_deactivation_hook($this->pluginRoot, [self::class, 'deActivateHook']);
        register_uninstall_hook($this->pluginRoot, [self::class, 'onPluginUninstall']);

    }

    /**
     * Handles plugin uninstallation.
     * @developer Jay Parmar
     */
    public static function onPluginUninstall(): void {
        // Get the directory of the uninstalled plugin
        $plugin_directory = dirname(plugin_dir_path(__FILE__));
    }

    /**
     * Handles plugin updates.
     *
     * @param mixed $upgrader_object The upgrader object.
     * @param array $options Details about the update process.
     * @developer Jay Parmar
     */
    public function onPluginUpdate(mixed $upgrader_object, array $options): mixed {
        if ($options['type'] === 'plugin' && isset($options['plugins'])) {
            foreach ($options['plugins'] as $plugin) {
                // Get the directory of the updated plugin
                $plugin_directory = WP_PLUGIN_DIR . '/' . trim(dirname($plugin), ".");

            }
        }
        return $upgrader_object;
    }

    /**
     * Handles plugin deactivation.
     *
     * @param string $plugin The plugin being deactivated.
     * @developer Jay Parmar
     */
    public function onPluginDeactivation(string $plugin): void {

        $plugin_directory = WP_PLUGIN_DIR . '/' . trim(dirname($plugin), ".");

    }

    /**
     * Handles plugin activation.
     *
     * @param string $plugin The plugin being activated.
     * @developer Jay Parmar
     */
    public function onPluginActivation(string $plugin): void {

        $plugin_directory = WP_PLUGIN_DIR . '/' . trim(dirname($plugin), ".");

    }


    /**
     * Replaces the attachment URL with the CloudFront URL if enabled.
     *
     * @param string $url The original attachment URL.
     * @return string The modified attachment URL or the original URL on failure.
     * @developer Jay Parmar
     */
    public function getAttachmentUrl(string $url): string
    {
        $originalUrl = $url;
        try {
            $config = $this->config;
            $use_cloudfront = $config->useCdnForMedia;
            // Replace URL only if CloudFront is enabled and configured
            if ($use_cloudfront && !empty($config->url) ) {
                $extension = SMARL_Helper::getFileExtensionFromUrl(url:$url);
                $mediaExtensions = SMARL_Helper::getExtension(type: "media");
                if(in_array(needle: $extension, haystack: $mediaExtensions)){
                    $url = SMARL_Helper::replaceBaseUrl(originalUrl:$url, newBaseUrl: $this->generateUrlFromBase($config->url));
                }
            }
        } catch (Exception) {
            return $originalUrl;
        }
        return $url;
    }

    public function generateUrlFromBase($baseUrl): string{
        return "https://" . $baseUrl;
    }

    /**
     * Replaces the base URL of scripts and styles with the CloudFront URL.
     *
     * @param string $src The original source URL.
     * @return string The modified source URL or the original on failure.
     * @developer Jay Parmar
     */
    public function replaceBaseUrl(string $src): string
    {
        try {
            return SMARL_Helper::replaceBaseUrl(originalUrl:$src, newBaseUrl:"https://" . $this->config->url);
        }catch (Exception){
            return $src;
        }

    }


    /**
     * Handles plugin deactivation hook.
     * @developer Jay Parmar
     */
    public function deActivateHook(): void
    {
        SMARL_CloudConfig::delete();
        $this->config = SMARL_CloudConfig::load();
    }

    /**
     * Handles plugin activation hook.
     * @developer Jay Parmar
     */
    public static function activateRegisterHook(): void
    {
        SMARL_CloudConfig::init();

    }

    /**
     * Enqueues admin scripts and styles for the plugin.
     * @developer Jay Parmar
     */
    public function enqueueScripts(): void
    {
        wp_enqueue_style(
            'aws-admin-css',
            plugin_dir_url($this->pluginRoot) . 'assets/css/wizard.css',
            [],
            SMARL_ASSET_VERSION_CODE
        );
        wp_enqueue_script(
            'aws-admin-js',
            plugin_dir_url($this->pluginRoot) . 'assets/js/wizard.js',
            ['jquery'],
            SMARL_ASSET_VERSION_CODE,
            true
        );
        wp_localize_script('aws-admin-js', 'ajax_object', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('smarl_nonce'),
            "isLite" => false,
            'strings' => [
                'aws_region_us_east_1' => esc_attr__('US East (N. Virginia)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_us_east_2' => esc_attr__('US East (Ohio)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_us_west_1' => esc_attr__('US West (N. California)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_us_west_2' => esc_attr__('US West (Oregon)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ca_central_1' => esc_attr__('Canada (Central)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_west_1' => esc_attr__('Europe (Ireland)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_west_2' => esc_attr__('Europe (London)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_west_3' => esc_attr__('Europe (Paris)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_central_1' => esc_attr__('Europe (Frankfurt)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_south_1' => esc_attr__('Europe (Milan)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_eu_south_2' => esc_attr__('Europe (Spain)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_me_south_1' => esc_attr__('Middle East (Bahrain)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_me_central_1' => esc_attr__('Middle East (UAE)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_af_south_1' => esc_attr__('Africa (Cape Town)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_northeast_1' => esc_attr__('Asia Pacific (Tokyo)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_northeast_2' => esc_attr__('Asia Pacific (Seoul)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_northeast_3' => esc_attr__('Asia Pacific (Osaka)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_southeast_1' => esc_attr__('Asia Pacific (Singapore)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_southeast_2' => esc_attr__('Asia Pacific (Sydney)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_southeast_3' => esc_attr__('Asia Pacific (Jakarta)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_south_1' => esc_attr__('Asia Pacific (Mumbai)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_ap_south_2' => esc_attr__('Asia Pacific (Hyderabad)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_sa_east_1' => esc_attr__('South America (São Paulo)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_cn_north_1' => esc_attr__('China (Beijing)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_cn_northwest_1' => esc_attr__('China (Ningxia)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_us_gov_east_1' => esc_attr__('AWS GovCloud (US-East)', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'aws_region_us_gov_west_1' => esc_attr__('AWS GovCloud (US-West)', 'smartsync-lite-media-offloader-and-assets-cdn'),

                'digitalocean_region_nyc1' => esc_attr__('New York City 1', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_nyc2' => esc_attr__('New York City 2', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_nyc3' => esc_attr__('New York City 3', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_ams3' => esc_attr__('Amsterdam 3', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_sfo2' => esc_attr__('San Francisco 2', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_sfo3' => esc_attr__('San Francisco 3', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_sgp1' => esc_attr__('Singapore 1', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_lon1' => esc_attr__('London 1', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_fra1' => esc_attr__('Frankfurt 1', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'digitalocean_region_tor1' => esc_attr__('Toronto 1', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // General User-Facing Messages
                'enter_domain' => esc_attr__('Please enter a domain.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'certificate_generated' => esc_attr__('Certificate generated successfully!', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'no_dns_records' => esc_attr__('No DNS records available. Please wait and try again later.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'certificate_generation_failed' => esc_attr__('Certificate generation failed', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'certificate_generation_error' => esc_attr__('An error occurred while generating the certificate. Please try again.', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // DNS Validation
                'dns_validation_records' => esc_attr__('DNS Validation Records', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'checking' => esc_attr__('Checking...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'domain' => esc_attr__('Domain', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'type' => esc_attr__('Type', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'name' => esc_attr__('Name', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'value' => esc_attr__('Value', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'verified' => esc_attr__('Verified', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'pending_validation' => esc_attr__('Pending Validation', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'all_dns_verified' => esc_attr__('All DNS records have been verified!', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // Error Handling
                'error' => esc_attr__('Error', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'dns_check_error' => esc_attr__('An error occurred while checking DNS records.', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // Certificate Attachment
                'certificate_attached' => esc_attr__('Certificate attached successfully!', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'attachment_failed' => esc_attr__('Attachment failed', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'attachment_error' => esc_attr__('An error occurred while attaching the certificate. Please try again.', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // IAM and Bucket Configuration
                'iam_required' => esc_attr__('IAM Key and Secret are required.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'bucket_required' => esc_attr__('Bucket name is required.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'configuration_saved' => esc_attr__('Configuration saved successfully!', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'configuration_failed' => esc_attr__('Configuration failed', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // Bucket Loading
                'loading_buckets' => esc_attr__('Loading buckets...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'load_buckets_failed' => esc_attr__('Failed to load buckets. Check your IAM credentials or permissions.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'load_buckets_error' => esc_attr__('An error occurred while loading buckets. Please try again.', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // Navigation Steps
                'step_1_next' => esc_attr__('Next: Validate IAM Credentials', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'step_2_next' => esc_attr__('Next: Configure Bucket', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'step_2_back' => esc_attr__('Back to Step 1', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'step_3_back' => esc_attr__('Back to Step 2', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'step_3_finalize' => esc_attr__('Finalize Configuration', 'smartsync-lite-media-offloader-and-assets-cdn'),

                // Tabs Navigation
                'tab_general' => esc_attr__('General Settings', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'tab_advanced' => esc_attr__('Advanced Settings', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'tab_help' => esc_attr__('Help', 'smartsync-lite-media-offloader-and-assets-cdn'),
            ]
        ]);

        wp_enqueue_script(
            'aws-settings-js',
            plugin_dir_url($this->pluginRoot) . 'assets/js/settings.js',
            ['jquery'],
            SMARL_ASSET_VERSION_CODE,
            true
        );

        wp_localize_script('aws-settings-js', 'ajaxObject', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('smarl_nonce'),
            'wizard_url' => admin_url('admin.php?page=aws-configuration-wizard'),
            "isLite" => false,
            'settings_strings' => [
                'syncing' => esc_attr__('Syncing...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'sync' => esc_attr__('Sync', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'progress' => esc_attr__('Progress', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'sync_completed' => esc_attr__('Sync completed successfully.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'sync_failed' => esc_attr__('Sync failed. Check errors below.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'starting_sync' => esc_attr__('Starting sync process...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'starting_sync_of' => esc_attr__('Starting sync of', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'files' => esc_attr__('files', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'uploaded' => esc_attr__('Uploaded', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'downloaded' => esc_attr__('Downloaded', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'confirm_sync_local_to_aws' => esc_attr__('Are you sure you want to sync local files to AWS?', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'confirm_sync_aws_to_local' => esc_attr__('Are you sure you want to sync AWS files to local?', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'failed_to_start_sync' => esc_attr__('Failed to start sync. Please try again.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'confirm_stop_processes' => esc_attr__('Are you sure you want to stop all the running processes?', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'stopping' => esc_attr__('Stopping...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'stopping_processes' => esc_attr__('Stopping all processes...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'failed_to_stop_processes' => esc_attr__('Failed to stop processes.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'clearing_cache' => esc_attr__('Clearing CloudFront cache...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'cache_cleared' => esc_attr__('CloudFront cache cleared successfully.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'failed_to_clear_cache' => esc_attr__('Failed to clear CloudFront cache.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'setting_up_cdn' => esc_attr__('Setting up CDN...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'removing_cdn' => esc_attr__('Removing CDN...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'cdn_setup_success' => esc_attr__('CDN setup successfully.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'cdn_setup_failed' => esc_attr__('Failed to set up CDN.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'enabling_auto_delete' => esc_attr__('Enabling auto-delete...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'disabling_auto_delete' => esc_attr__('Disabling auto-delete...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'auto_delete_enabled' => esc_attr__('Auto-delete enabled successfully.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'auto_delete_disabled' => esc_attr__('Auto-delete disabled successfully.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'auto_delete_failed' => esc_attr__('Failed to toggle auto-delete.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'loading' => esc_attr__('Loading...', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'error' => esc_attr__('Error', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'failed_to_fetch_analytics' => esc_attr__('Failed to fetch analytics. Please try again.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'running' => esc_attr__('Sync is running.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'not_running' => esc_attr__('No sync is running.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'sync_in_process' => esc_attr__('sync in process. Please try again after some time.', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'to_aws' => esc_attr__('to AWS', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'from_aws' => esc_attr__('from AWS', 'smartsync-lite-media-offloader-and-assets-cdn'),
                'confirm_clear_cache' => esc_attr__('Are you sure you want to clear all the cache from AWS CloudFront?', 'smartsync-lite-media-offloader-and-assets-cdn'),
            ]
        ]);
    }

    public function s3UploadNewMedia($post_id): void
    {

        if ($this->config->bucket === ""){
            return;
        }
        $attachment = get_post($post_id);
        if ($attachment && $attachment->post_type === 'attachment') {
            add_filter('wp_generate_attachment_metadata', function ($metadata, $post_id) {

                $resized_files = [get_attached_file($post_id)];
                if (!empty($metadata['sizes'])) {
                    foreach ($metadata['sizes'] as $file_data) {
                        $resized_files[] = wp_upload_dir()['path']  . '/' . $file_data['file'];
                    }
                }

                foreach ($resized_files as $resized_file) {
                    $uploads_path = wp_upload_dir();
                    $file_name = str_replace($uploads_path['basedir'], '', $resized_file);

                    $this->config->putS3Object(file_name: $file_name, file_path: $resized_file);

                    if ($this->config->mediaAutoDelete){
                        wp_delete_file($resized_file);
                    }
                }
                return $metadata;
            }, 10, 2);
        }
    }

    public function deleteFromS3($file) {
        try {
            $uploads_path = wp_upload_dir();
            $aws_key = str_replace($uploads_path['basedir'], '', $file);


            $this->config->getS3Client()->deleteObject([
                'Bucket' => $this->config->bucket,
                'Key'    => $aws_key,
            ]);

        }catch (Exception $e){

        }
        return $file;
    }
}


