<?php

namespace WeDevs\Wpuf\Pro\Fields;

use WeDevs\Wpuf\Ajax\Upload_Ajax;

/**
 * File Field Class
 *
 * @since 3.1.0
 **/
class Field_File extends Pro_Field_Contract {

    public function __construct() {
        $this->name       = __( 'File Upload', 'wpuf-pro' );
        $this->input_type = 'file_upload';
        $this->icon       = 'arrow-up-tray';
    }

    /**
     * Render the File field
     *
     * @param  array  $field_settings
     *
     * @param  integer  $form_id
     *
     * @param  string  $type
     *
     * @param  integer  $post_id
     *
     * @return void
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        if ( method_exists( 'WeDevs\Wpuf\Fields\Field_Contract', 'enqueue_file_upload_scripts' ) ) {
            $this->enqueue_file_upload_scripts();
        }

        // Upload-zone structure (shared with the registration templates).
        wp_enqueue_style( 'wpuf-file-upload-zone' );

        $allowed_ext = '';
        $extensions  = wpuf_allowed_extensions();
        $unique_id   = sprintf( '%s-%d', $field_settings['name'], $form_id );

        if ( is_array( $field_settings['extension'] ) ) {
            foreach ($field_settings['extension'] as $ext) {
                $allowed_ext .= $extensions[$ext]['ext'] . ',';
            }
        } else {
            $allowed_ext = '*';
        }

        if( isset( $post_id ) &&  $post_id != '0' ) {
            $uploaded_items = $post_id ? $this->get_meta( $post_id, $field_settings['name'], $type, false ) : array();

            if ( $uploaded_items ) {
                if( is_serialized( $uploaded_items[0] ) ) {
                    $uploaded_items = maybe_unserialize( $uploaded_items[0] );
                }

                if ( is_array( $uploaded_items[0] ) ) {
                    $uploaded_items = $uploaded_items[0];
                }
            }
        } else {
            $uploaded_items = array();
        }

        $this->field_print_label( $field_settings, $form_id );
        ?>

        <div class="wpuf-fields">
            <div id="wpuf-<?php echo $unique_id; ?>-upload-container">
                <div class="wpuf-attachment-upload-filelist" data-type="file"
                     data-required="<?php echo $field_settings['required']; ?>">
                    <!-- Modern File Upload Design -->
                    <div class="wpuf-file-upload-zone">
                        <div class="wpuf-upload-content">
                            <div class="wpuf-upload-icon">
                                <svg width="20" height="19" viewBox="0 0 20 19" fill="none"
                                     xmlns="http://www.w3.org/2000/svg">
                                    <path
                                        d="M5.75 14.75C2.98858 14.75 0.75 12.5114 0.75 9.75C0.75 7.30154 2.50992 5.26413 4.83376 4.83376C5.26412 2.50992 7.30154 0.75 9.75 0.75C12.1985 0.75 14.2359 2.50992 14.6662 4.83376C16.9901 5.26413 18.75 7.30154 18.75 9.75C18.75 12.5114 16.5114 14.75 13.75 14.75M6.75 9.75L9.75 6.75M9.75 6.75L12.75 9.75M9.75 6.75V18.75"
                                        stroke="#94A3B8" stroke-width="1.5" stroke-linejoin="round"/>
                                </svg>
                            </div>
                            <div class="wpuf-upload-title">
                                <?php $this->print_label( $field_settings, $form_id ); ?>
                            </div>
                            <div class="wpuf-upload-instructions">
                                <?php
                                // Get file type restrictions
                                $file_types = [];
                                if ( is_array( $field_settings['extension'] ) ) {
                                    foreach ( $field_settings['extension'] as $ext ) {
                                        if ( isset( $extensions[ $ext ] ) ) {
                                            $file_types[] = strtoupper( $extensions[ $ext ]['ext'] );
                                        }
                                    }
                                }
                                $file_types_text = ! empty( $file_types ) ? implode(
                                    ', ', array_unique( $file_types )
                                ) : __( 'All file types', 'wpuf-pro' );
                                // Get max file size
                                $max_size_mb = round( $field_settings['max_size'] / 1024, 1 );
                                $max_size_text = $max_size_mb >= 1 ? $max_size_mb . 'MB' : $field_settings['max_size'] . 'KB';
                                /* translators: %1$s: allowed file types, %2$s: maximum file size */
                                printf(
                                    esc_html__( 'Only %1$s files and max size of %2$s each', 'wpuf-pro' ),
                                    esc_html( $file_types_text ),
                                    esc_html( $max_size_text )
                                );
                                ?>
                            </div>
                        </div>
                        <!-- Hidden clickable area that preserves all functionality -->
                        <a id="wpuf-<?php echo $unique_id; ?>-pickfiles" data-form_id="<?php echo $form_id; ?>"
                           class="wpuf-upload-trigger <?php echo ' wpuf_' . $field_settings['name'] . '_' . $form_id; ?>"
                           href="#"></a>
                    </div>

                    <ul class="wpuf-attachment-list thumbnails">

                        <?php
                        if ( $uploaded_items ) {
                            foreach ( $uploaded_items as $attach_id ) {
                                echo Upload_Ajax::attach_html( $attach_id, $field_settings['name'] );
                                if ( is_admin() ) {
                                    printf(
                                        '<a href="%s">%s</a>', wp_get_attachment_url( $attach_id ),
                                        __( 'Download File', 'wpuf-pro' )
                                    );
                                }
                            }
                        }
                        ?>

                    </ul>
                </div>
            </div><!-- .container -->

            <?php $this->help_text( $field_settings ); ?>

        </div> <!-- .wpuf-fields -->

        <script type="text/javascript">
            jQuery(function($) {
                var uploader = new WPUF_Uploader('wpuf-<?php echo $unique_id; ?>-pickfiles', 'wpuf-<?php echo $unique_id; ?>-upload-container', <?php echo $field_settings['count']; ?>, '<?php echo $field_settings['name']; ?>', '<?php echo $allowed_ext; ?>', <?php echo $field_settings['max_size'] ?>);
                wpuf_plupload_items.push(uploader);
            });
        </script>

        <?php $this->after_field_print_label();
    }

    /**
     * Get field options setting
     *
     * @return array
     */
    public function get_options_settings() {
        $default_options      = $this->get_default_option_settings( true, array('dynamic') );

        $settings = array(
            array(
                'name'          => 'max_size',
                'title'         => __( 'Max. file size', 'wpuf-pro' ),
                'type'          => 'text',
                'variation'     => 'number',
                'section'       => 'advanced',
                'priority'      => 20,
                'help_text'     => __( 'Enter maximum upload size limit in KB', 'wpuf-pro' ),
            ),

            array(
                'name'          => 'count',
                'title'         => __( 'Max. files', 'wpuf-pro' ),
                'type'          => 'text',
                'variation'     => 'number',
                'section'       => 'advanced',
                'priority'      => 21,
                'help_text'     => __( 'Number of files can be uploaded', 'wpuf-pro' ),
            ),

            array(
                'name'          => 'extension',
                'title'         => __( 'Allowed Files', 'wpuf-pro' ),
                'title_class'   => 'label-hr',
                'type'          => 'checkbox',
                'options'       => apply_filters(
                    'wpuf_field_file_allowed_extensions',
                    [
                        'images'    => __( 'Images (jpg, jpeg, gif, png, bmp, webp)', 'wpuf-pro' ),
                        'audio'     => __( 'Audio (mp3, wav, ogg, wma, mka, m4a, ra, mid, midi)', 'wpuf-pro' ),
                        'video'     => __( 'Videos (avi, divx, flv, mov, ogv, mkv, mp4, m4v, divx, mpg, mpeg, mpe)', 'wpuf-pro' ),
                        'pdf'       => __( 'PDF (pdf)', 'wpuf-pro' ),
                        'office'    => __( 'Office Documents (doc, ppt, pps, xls, mdb, docx, xlsx, pptx, odt, odp, ods, odg, odc, odb, odf, rtf, txt)', 'wpuf-pro' ),
                        'zip'       => __( 'Zip Archives (zip, gz, gzip, rar, 7z)', 'wpuf-pro' ),
                        'csv'       => __( 'CSV (csv)', 'wpuf-pro' ),
                    ]
                ),
                'section'       => 'advanced',
                'priority'      => 22,
                'help_text'     => '',
            ),

            array(
                'name'      => 'playable_audio_video',
                'title'     => __( 'Make Audio/Video files playable', 'wpuf-pro' ),
                'type'      => 'radio',
                'options'   => array(
                    'yes'   => __( 'Yes', 'wpuf-pro' ),
                    'no'    => __( 'No', 'wpuf-pro' ),
                ),
                'section'   => 'advanced',
                'priority'  => 22,
                'default'   => 'no',
                'inline'    => true,
                'help_text' => __( 'Make uploaded Audio/Video files playable in post', 'wpuf-pro' ),
            ),

            array(
                'name'          => 'preview_width',
                'title'         => __( 'Preview Width', 'wpuf-pro' ),
                'type'          => 'text',
                'section'       => 'advanced',
                'priority'      => 22,
                'help_text'     => __( 'Width in px (e.g: 123) for video player, only applicable if you make audio/video files playable.', 'wpuf-pro' ),
            ),

            array(
                'name'          => 'preview_height',
                'title'         => __( 'Preview Height', 'wpuf-pro' ),
                'type'          => 'text',
                'section'       => 'advanced',
                'priority'      => 22,
                'help_text'     => __( 'Height in px (e.g: 456) for video player, only applicable if you make audio/video files playable.', 'wpuf-pro' ),
            ),
        );


        return array_merge( $default_options, $settings );
    }

    /**
     * Get the field props
     *
     * @return array
     */
    public function get_field_props() {
        $defaults = $this->default_attributes();

        $props    = array(
            'input_type'                => 'file_upload',
            'is_meta'                   => 'yes',
            'max_size'                  => '1024',
            'count'                     => '1',
            'extension'                 => array( 'images', 'audio', 'video', 'pdf', 'office', 'zip', 'csv' ),
            'playable_audio_video'      => 'no',
            'preview_width'             => '123',
            'preview_height'            => '456',
            'id'                        => 0,
            'is_new'                    => true,
            'show_in_post'              => 'yes',
            'hide_field_label'          => 'no',
        );

        return array_merge( $defaults, $props );
    }


    /**
     * Prepare entry
     *
     * @param $field
     *
     * @return mixed
     */
    public function prepare_entry( $field ) {
        $files = isset( $_POST['wpuf_files'][$field['name']] ) ? $_POST['wpuf_files'][$field['name']] : [];
        $sanitized = array_map( 'absint', wp_unslash( $files ) );
        
        return $sanitized;
    }
}
