<?php
    if ( ! defined( 'ABSPATH' ) ) exit;

    class cloudS3StorageClass extends cloudS3StoragePlugin {

        public $started = false;
        public $s3 = false;

        public function __construct()
        {
            parent::__construct();

            add_filter('plugin_action_links', array($this, 'cloud_s3_storage_deactivation_link'), 10, 4);
            add_filter('plugin_action_links', array($this, 'cloud_s3_add_action_links'), 10, 4);

            $this->cloud_s3_storage_prepareAction();

            $this->credentialPrepared();

            $this->setMedia();

            $this->startTemplate($this->options);

            if ( defined( 'WP_CLI' ) && WP_CLI ) {
                $this->register_wp_cli_commands();
            }

            add_action('rest_api_init', array($this, 'register_cron_job_routes'));
        }


        public function cloud_s3_add_action_links($links, $plugin_file) {
            $main_plugin_file = 'cloud-s3-storage/cloud-s3-storage.php';

            if ($main_plugin_file === $plugin_file) {
                $settings_link = '<a href="' . esc_url(menu_page_url('cloud-s3-configure', false)) . '">' . __('Settings', 'cloud-s3-storage') . '</a>';
                array_unshift($links, $settings_link);
            }
            return $links;
        }

        public function cloud_s3_storage_deactivation_link($actions, $plugin_file, $plugin_data, $context) {
            $options = get_option('cloud_s3_settings');
            if($this->option_checker()) {
                $confirmation_message = sprintf(
                    /* translators: Number of externally hosted files */
                    __('You have %s files hosted externally. Are you sure you want to deactivate the plugin?', 'cloud-s3-storage'),
                    $this->smart_monitor['ajx-s3-count']
                );

                $main_plugin_file = 'cloud-s3-storage/cloud-s3-storage.php';

                if ($main_plugin_file === $plugin_file) {
                    $deactivate_url = wp_nonce_url(admin_url('plugins.php?action=deactivate&plugin=' . urlencode($plugin_file)), 'deactivate-plugin_' . $plugin_file);
                    $actions['deactivate'] = '<a href="' . esc_url($deactivate_url) . '" onclick="return confirm(\'' . $confirmation_message . '\')">'.__('Deactivate', 'cloud-s3-storage').'</a>';
                }
            }
            return $actions;

        }
    
        public function register_wp_cli_commands() {
            \WP_CLI::add_command( 'cloud-s3-storage reindex-image', array( $this, 'wp_cli_reindex_image' ) );
    
            \WP_CLI::add_command( 'cloud-s3-storage clear-image', array( $this, 'wp_cli_clear_image' ) );
    
            \WP_CLI::add_command( 'cloud-s3-storage rollback-image', array( $this, 'wp_cli_rollback_image' ) );
        }
    
        public function wp_cli_reindex_image( $args, $assoc_args ) {
            $this->cloud_s3_storage_reindex_image_endpoint_handler();
        }
    
        public function wp_cli_clear_image( $args, $assoc_args ) {
            $this->cloud_s3_storage_clear_image_endpoint_handler();
        }
    
        public function wp_cli_rollback_image( $args, $assoc_args ) {
            $this->cloud_s3_storage_rollback_image_endpoint_handler();
        }

        public function cloud_s3_storage_status_ajax_handler() {
            $data = $this->smart_monitor;
            wp_send_json($data);
            wp_die();
        }       

        public function setMedia() {
            $mode = $this->options['active_mode']== 'on' ? true : false;
            $media = new cloudS3StorageMedia((bool)$mode);
        }

        public function getFieldList() {
            $fields = array();
            foreach ($this->setup_field['fields'] as $field) {
                $fields[] = $field['id'];
            }
            return $fields;
        }

        public function register_cron_job_routes() {
            if ($this->enable_link_test()) {
                register_rest_route('cloud-s3-storage/v1', '/reindex-image/', array(
                    'methods' => 'GET',
                    'callback' => array($this, 'cloud_s3_storage_reindex_image_endpoint_handler'),
                    'permission_callback' => function() {
                        return current_user_can('manage_options');
                    }
                ));
                register_rest_route('cloud-s3-storage/v1', '/clear-image/', array(
                    'methods' => 'GET',
                    'callback' => array($this, 'cloud_s3_storage_clear_image_endpoint_handler'),
                    'permission_callback' => function() {
                        return current_user_can('upload_files');
                    }
                ));
                register_rest_route('cloud-s3-storage/v1', '/rollback-image/', array(
                    'methods' => 'GET',
                    'callback' => array($this, 'cloud_s3_storage_rollback_image_endpoint_handler'),
                    'permission_callback' => function() {
                        return current_user_can('edit_posts');
                    }
                ));
            }
        }

        public function cloud_s3_storage_reindex_image_endpoint_handler() {
            cloudS3StorageCache::deleteCache('cloud_s3_storage_cached_file_attach_list');
            $this->runDB_mapping();
            $data = $this->getImageToConvert($this->getLimitImageToConvert());

            foreach ($data as $img) {
                $this->uploadImage($img['url']); 
            }
            delete_transient('cloud_s3_storage_cached_id_list');

            wp_send_json($data);
            wp_die();
        }

        public function cloud_s3_storage_rollback_image_endpoint_handler() {
            cloudS3StorageCache::deleteCache('cloud_s3_storage_cached_file_attach_list');
            $this->runDB_mapping();
            $data = $this->getImageToDownload($this->getLimitImageToConvert());
            foreach ($data as $img) {    
                $external_url = cloudS3StorageObserver::replace_url($img['Key']);
                $this->downloadImage($img['Key']);
            }
            delete_transient('cloud_s3_storage_cached_id_list');

            wp_send_json($data);
            wp_die();
        }

        public function ibrid_mode() {
            return isset($this->options['active_bihost']) ? (bool) $this->options['active_bihost'] : false;
        }

        public function enable_link_test() {
            return isset($this->options['active_direct_url']) ? (bool) $this->options['active_direct_url'] : false;
        }
        
        public function runDB_mapping () {
            if(CloudS3StorageDB::getMissingImagesPercentage() > 0) {
                wp_send_json( ["description" => __("Image mapping still in progress, you can start in a few minutes",'cloud-s3-storage')]);
                wp_die();
            }
        }

        public function cloud_s3_storage_clear_image_endpoint_handler() {
            cloudS3StorageCache::deleteCache('cloud_s3_storage_cached_file_attach_list');
            $this->runDB_mapping();
            $delete_status = [];
            if($this->ibrid_mode()) {
                wp_send_json( ["description" => __("Hybrid mode activated",'cloud-s3-storage')]);
                wp_die();
            } 
            foreach($this->getfileToDelete($this->getLimitImageToConvert()) as $image) {
                $delete_status[$image['url']] = false;

                if(cloudS3StorageMedia::deleteFile($image['complete_path'])) {
                    $delete_status[$image['url']] = true;
                }
            }
            delete_transient('cloud_s3_storage_cached_id_list');

            wp_send_json( $delete_status);
            wp_die();
        }

        public function getfileToDelete($limit = 0) {
            $data = $this->layer['image-to-del'];

            if($limit>0) {
                return array_slice($data, 0, $limit);
            }
            
            return $data;
        }

        public function getImageToConvert($limit = 0) {
            $data = $this->monitor['image-not-converted'];

            if($limit>0) {
                return array_slice($data, 0, $limit);
            }
            
            return $data;
        }

        public function getImageToDownload($limit = 0) {
            $data = $this->layer['ajx-s3'];
            
            if($limit>0) {
                return array_slice($data, 0, $limit);
            }
            
            return $data;
        }

        public function uploadImage ($image_url) {
            return cloudS3Class::putS3File($image_url,$image_url);
        }

        public function downloadImage ($image_url) {
            
            $ibrid = false;
            if($this->ibrid_mode()) {
                $ibrid = true;
            } 
            return cloudS3Class::downloadS3File($image_url,$image_url, $ibrid);
        }

        public function getLimitImageToConvert() {
            return isset($this->options['image_max_cron']) ? (int)$this->options['image_max_cron'] : 0;
        }
        
        public function credentialPrepared() {
            
            $fields = $this->getFieldList();
            
            $options = get_option('cloud_s3_settings');
            if($options) {            
                $this->started = true;
                foreach ($fields as $field) {
                    $this->options[$field] = $options[$field] ?? '';
                }
            } else {
                foreach ($fields as $field) {
                    $this->options[$field] = '';
                }
            }
        }
        
        public function cloud_s3_main_page() {
            $data = array(
                'enable_link_test' => $this->enable_link_test()
            );
            $this->page->getTemplate('cloud-s3-main-page', $data);
        }
        
        public function cloud_s3_settings_page() {
            $this->page->getTemplate('cloud-s3-conf');
        }
                
        public function cloud_s3_section_callback() {
            echo 'Insert your Amazon S3 credentials below:';
        }
        
        public function s3_storage_init() {
            $this->s3 = new cloudS3Class();
        }

        public function cloud_s3_storage_menu() {
            add_menu_page(
                'Cloud S3 Storage Settings',
                'Cloud S3 Storage',
                'manage_options',
                'cloud-s3-settings',
                array($this,'cloud_s3_main_page')
            );
        
            add_submenu_page(
                'cloud-s3-settings',
                'Settings Page',
                'Settings',
                'manage_options',
                'cloud-s3-configure',
                array($this, 'cloud_s3_settings_page')
            );
            
            do_action('cloud_s3_storage_menu_hook');
        }
        
        public function cloud_s3_storage_prepareAction() {
        
            $this->addAction(array(
                'admin_menu' => 'cloud_s3_storage_menu',
                'admin_init' => 'cloud_s3_settings_init',
                'init' => 's3_storage_init',
                'wp_ajax_cloud_s3_storage_status_ajax_handler' => 'cloud_s3_storage_status_ajax_handler',
                'admin_enqueue_scripts' => 'cloud_s3_storage_enqueue_scripts',
                'rest_api_init' => 'register_cron_job_routes',
                'add_attachment' => 'invalidate_attachment_cache',
                'edit_attachment' => 'invalidate_attachment_cache'
            ));
        
        }
        
        public function invalidate_attachment_cache() {
            cloudS3StorageCache::deleteCache('cloud_s3_storage_cached_file_attach_list');
        }
        
        public function cloud_s3_storage_enqueue_scripts() {
            $this->includeScript($this->setup_js);
            $this->includeStyle($this->setup_css);
        }
    }
