<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://anssilaitila.fi
 * @since      1.0.0
 *
 * @package    Shared_Files
 * @subpackage Shared_Files/public
 */
/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Shared_Files
 * @subpackage Shared_Files/public
 * @author     Anssi Laitila <anssi.laitila@gmail.com>
 */
class Shared_Files_Public {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    string    $plugin_name       The name of the plugin.
     * @param    string    $version           The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles( $hook ) {
        $s = get_option( 'shared_files_settings' );
        wp_enqueue_style(
            $this->plugin_name,
            SHARED_FILES_URI . 'dist/css/p.css',
            array(),
            $this->version,
            'all'
        );
        wp_enqueue_style(
            $this->plugin_name . '-basiclightbox',
            SHARED_FILES_URI . 'dist/basiclightbox/basicLightbox.min.css',
            array(),
            $this->version,
            'all'
        );
        wp_enqueue_script( 'plupload-all' );
        if ( isset( $s['card_font'] ) && $s['card_font'] ) {
            if ( $s['card_font'] == 'roboto' ) {
                wp_enqueue_style( $this->plugin_name . '-google-fonts', 'https://fonts.googleapis.com/css?family=Roboto&display=swap', false );
            } elseif ( $s['card_font'] == 'ubuntu' ) {
                wp_enqueue_style( $this->plugin_name . '-google-fonts', 'https://fonts.googleapis.com/css?family=Ubuntu&display=swap', false );
            }
        }
    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts( $hook ) {
        $s = get_option( 'shared_files_settings' );
        wp_enqueue_script(
            $this->plugin_name,
            SHARED_FILES_URI . 'dist/js/p.js',
            array('jquery'),
            $this->version,
            false
        );
        wp_enqueue_script(
            $this->plugin_name . '-basiclightbox',
            SHARED_FILES_URI . 'dist/basiclightbox/basicLightbox.min.js',
            array('jquery'),
            $this->version,
            false
        );
        $inline_js = $this->get_inline_scripts();
        wp_add_inline_script( $this->plugin_name, $inline_js );
    }

    public function get_inline_scripts() {
        $s = get_option( 'shared_files_settings' );
        $js = '';
        $js .= "jQuery(document).ready(function(\$) {";
        $js .= "\n      if (typeof ajaxurl === 'undefined') {\n        ajaxurl = '" . esc_url_raw( admin_url( 'admin-ajax.php' ) ) . "'; // get ajaxurl\n      }\n      ";
        if ( !isset( $s['file_upload_file_not_required'] ) ) {
            $js .= "\n        \$('.shared-files-frontend-file-upload').submit(function (e) {\n\n          let elem_class = \$(this).closest('.shared-files-main-container').data('elem-class');\n\n          if (\$('.' + elem_class + ' .shared-files-file-metadata-entry').length == 0) {\n            alert('Please choose the file first.');\n            return false;\n          }\n\n        });\n        ";
        }
        // NEW FILE UPLOAD
        if ( 1 ) {
            $plupload_nonce = wp_create_nonce( "plupload_nonce" );
            $multi_selection = 'false';
            $js .= "\n\n        var uploader = new plupload.Uploader({\n\n          browse_button: 'browse-button',\n          container: 'shared-files-file-uploader-container',\n\n          url: '" . esc_url_raw( admin_url( 'admin-ajax.php' ) ) . "',\n\n          multipart_params: {\n            'action': 'shared_files_file_upload',\n            '_wpnonce': '" . $plupload_nonce . "',\n          },\n\n          multi_selection: ' . {$multi_selection} . ',\n\n          urlstream_upload: true,\n\n          init: {\n\n            FilesAdded: function(up, files) {\n\n              plupload.each(files, function(file) {\n\n                up.start();\n\n                \$('.shared-files-file-upload-status').removeClass('shared-files-file-upload-status-error');\n                \$('.shared-files-file-upload-status').removeClass('file-upload-status-ok');\n\n                \$('.shared-files-progress-bar-fill').addClass('shared-files-progress-bar-fill-active');\n\n                \$('.shared-files-progress-bar-fill').html('');\n\n                \$('.shared-files-progress-bar-fill').css('width', '');\n\n                \$('.shared-files-file-upload-status').addClass('shared-files-file-upload-status-default');\n\n              });\n\n            },\n\n            UploadProgress: function(up, file) {\n\n              \$('#' + file.id + ' b').html(file.percent + '%');\n\n              \$('.shared-files-progress-bar-fill').css('width', file.percent + '%');\n\n              \$('.shared-files-progress-bar-fill').html(file.percent + '%');\n\n\n            },\n\n            Error: function(up, err) {\n\n              \$('.shared-files-file-upload-status').html('<div>" . sanitize_text_field( __( 'Error', 'shared-files' ) ) . ": ' + err.message + ' Status: ' + err.status + '</div>');\n\n              console.log( err );\n\n            },\n\n            FileUploaded: function(up, file, response) {\n\n\n              let res;\n\n              try {\n                res = JSON.parse(response.response);\n              } catch (e) {\n                console.error('Invalid server response', response.response);\n\n                \$('.shared-files-file-upload-status').html('" . sanitize_text_field( __( 'Upload failed: Invalid response from server.', 'shared-files' ) ) . "');\n\n                return;\n              }\n\n              if (!res.success) {\n                console.error('Server reported error:', res.data?.error || 'Unknown error');\n\n                \$('.shared-files-file-upload-status').addClass('shared-files-file-upload-status-error');\n\n                \$('.shared-files-file-upload-status').html( '" . sanitize_text_field( __( 'Upload failed', 'shared-files' ) ) . ": ' + (res.data?.error || 'Unknown error') );\n\n                return;\n              }\n\n              \$('.shared-files-file-upload-status').addClass('file-upload-status-ok');\n\n              var filename_parts = res.data.file.split('/');\n              var filename = filename_parts.pop();\n\n              \$('.shared-files-file-upload-status').append( '<div>" . sanitize_text_field( __( 'File uploaded', 'shared-files' ) ) . ": ' + filename + '</div>');\n\n              var html = '<div class=\"shared-files-file-metadata-entry\">' +\n                  '<input type=\"hidden\" name=\"_sf_file_uploaded_file[' + file.id + '][file]\" value=\"' + res.data.file + '\">' +\n                  '<input type=\"hidden\" name=\"_sf_file_uploaded_file[' + file.id + '][type]\" value=\"' + res.data.type + '\">' +\n                  '<input type=\"hidden\" name=\"_sf_file_uploaded_file[' + file.id + '][url]\" value=\"' + res.data.url + '\">' +\n                  '<span>Uploaded (metadata): ' + file.name + '</span>' +\n                  '</div>';\n\n              \$('#shared-files-file-metadata-entries').append(html);\n\n              \$('.shared-files-file-upload-status-next-steps').show();\n\n            }\n\n          }\n\n        });\n\n        uploader.init();\n\n      ";
        }
        $js .= "});";
        return $js;
    }

    public function enqueue_block_assets() {
        if ( !function_exists( 'register_block_type' ) ) {
            // Gutenberg not active
            return;
        }
        if ( is_admin() ) {
            wp_enqueue_style(
                'shared-files-block-editor',
                SHARED_FILES_URI . 'dist/css/p.css',
                array('wp-edit-blocks'),
                filemtime( SHARED_FILES_PATH . 'dist/css/p.css' )
            );
        }
    }

    public function register_block() {
        if ( !function_exists( 'register_block_type' ) ) {
            // Gutenberg not active
            return;
        }
        register_block_type( SHARED_FILES_PATH . 'blocks/shared-files/build/block.json', array(
            'render_callback' => array($this, 'render_block'),
        ) );
    }

    public function render_block( $attributes, $content ) {
        $file_id = ( isset( $attributes['fileId'] ) ? intval( $attributes['fileId'] ) : 0 );
        $file_upload = ( isset( $attributes['fileUpload'] ) && $attributes['fileUpload'] ? ' file_upload="1"' : '' );
        $shortcode = '[shared_files';
        if ( $file_id ) {
            $shortcode .= ' file_id="' . $file_id . '"';
        }
        $shortcode .= $file_upload . ']';
        return do_shortcode( $shortcode );
    }

    public function filter_rest_api_query( $args, $request ) {
        $meta_query = array(
            'relation' => 'OR',
        );
        $meta_query[] = array(
            'key'     => '_sf_not_public',
            'compare' => '=',
            'value'   => '',
        );
        $meta_query[] = array(
            'key'     => '_sf_not_public',
            'compare' => 'NOT EXISTS',
        );
        // Add the meta query to the existing meta queries
        if ( isset( $args['meta_query'] ) ) {
            $args['meta_query'][] = $meta_query;
        } else {
            $args['meta_query'] = $meta_query;
        }
        return $args;
    }

    /**
     * Register the shortcodes.
     *
     * @since    1.0.0
     */
    public function register_shortcodes() {
        add_shortcode( 'shared_files', array('ShortcodeSharedFiles', 'shared_files') );
        add_shortcode( 'shared_files_search', array('ShortcodeSharedFilesSearch', 'shared_files_search') );
        add_shortcode( 'shared_files_categories', array('ShortcodeSharedFilesCategories', 'shared_files_categories') );
        add_shortcode( 'shared_files_simple', array('Shared_Files_Public', 'shared_files_simple') );
        add_shortcode( 'shared_files_info', array('ShortcodeSharedFilesInfo', 'shared_files_info') );
        add_shortcode( 'shared_files_accordion', array('ShortcodeSharedFilesAccordion', 'shared_files_accordion') );
        add_shortcode( 'shared_files_favorites', array('ShortcodeSharedFilesFavorites', 'shared_files_favorites') );
        add_shortcode( 'shared_files_restricted', array('ShortcodeSharedFilesRestricted', 'shared_files_restricted') );
        add_shortcode( 'shared_files_exact_search', array('ShortcodeSharedFilesExactSearch', 'shared_files_exact_search') );
    }

    public static function shared_files_simple( $atts = [], $content = null, $tag = '' ) {
        $html = '';
        $html .= ShortcodeSharedFilesSimple::view( $atts );
        return $html;
    }

}
