<?php

namespace WeDevs\Wpuf\Pro\Fields;

use WeDevs\Wpuf\Ajax\Upload_Ajax;

/**
 * Cover Photo Field Class
 *
 * @since 3.1.0
 **/
class Field_Cover_Photo extends Profile_Field {

    public function __construct() {
        $this->name       = __( 'Cover Photo', 'wpuf-pro' );
        $this->input_type = 'cover_photo';
        $this->icon       = 'cover';
    }

    /**
     * Render the Cover Photo 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();
        }

        // Get cover photo attachment ID
        $attachment_data = $this->get_user_meta_attachment( $post_id, 'wpuf_cover_photo' );
        $has_photo       = $attachment_data && $attachment_data['has_value'];
        $attachment_id   = $attachment_data ? $attachment_data['attachment_id'] : 0;

        $unique_id = sprintf( '%s-%d', $field_settings['name'], $form_id );
        ?>
        <li <?php $this->print_list_attributes( $field_settings ); ?>>
            <?php $this->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']; ?>">
                        <a id="wpuf-<?php echo $unique_id; ?>-pickfiles" data-form_id="<?php echo $form_id; ?>"
                           class="button file-selector <?php echo ' wpuf_' . $field_settings['name'] . '_' . $form_id; ?>"
                           href="#"><?php echo $field_settings['button_label']; ?></a>

                        <ul class="wpuf-attachment-list thumbnail">
                            <?php
                            if ( $has_photo && $attachment_id ) {
                                // Use the same pattern as other file upload fields
                                echo Upload_Ajax::attach_html( $attachment_id, $field_settings['name'] );
                            }
                            ?>
                        </ul>
                    </div>
                </div><!-- .container -->

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

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

            <script type="text/javascript">
                ;( function ( $ ) {
                    $( document ).ready( function () {
                        var uploader = new WPUF_Uploader( 'wpuf-<?php echo $unique_id; ?>-pickfiles', 'wpuf-<?php echo $unique_id; ?>-upload-container', 1, '<?php echo $field_settings['name']; ?>', 'jpg,jpeg,gif,png,bmp', <?php echo $field_settings['max_size'] ?>);
                        wpuf_plupload_items.push( uploader );
                    } );
                } )( jQuery );
            </script>
        </li>

        <?php
    }

    /**
     * Get field options setting
     *
     * @return array
     **/
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings( false, [ 'dynamic', 'count', 'width' ] );
        $settings = [
            $this->get_meta_key_setting( 'wpuf_cover_photo' ),
            [
                'name'      => 'button_label',
                'title'     => __( 'Button Label', 'wpuf-pro' ),
                'type'      => 'text',
                'default'   => __( 'Select Cover Photo', 'wpuf-pro' ),
                'section'   => 'basic',
                'priority'  => 20,
                'help_text' => __( 'Enter a label for the Cover Photo button', 'wpuf-pro' ),
            ],
            [
                'name'      => 'max_size',
                'title'     => __( 'Max. file size', 'wpuf-pro' ),
                'type'      => 'text',
                'section'   => 'advanced',
                'priority'  => 20,
                'help_text' => __( 'Enter maximum upload size limit in KB', 'wpuf-pro' ),
            ],
        ];

        if ( function_exists( 'wpuf_field_profile_photo_allowed_extensions' ) ) {
            $settings[] = [
                'name'        => 'extension',
                'title'       => __( 'Allowed file types', 'wpuf-pro' ),
                'title_class' => 'label-hr',
                'type'        => 'checkbox',
                'options'     => wpuf_field_profile_photo_allowed_extensions(),
                'section'     => 'advanced',
                'priority'    => 21,
                'help_text'   => __( 'Enter The allowed file types', 'wpuf-pro' ),
            ];
        }

        return array_merge( $default_options, $settings );
    }

    /**
     * Get the field props
     *
     * @return array
     **/
    public function get_field_props() {
        $defaults = $this->default_attributes();
        $props = [
            'input_type'    => 'cover_photo',
            'required'      => 'yes',
            'is_meta'       => 'no', // we will handle this manually
            'button_label'  => __( 'Select Cover Photo', 'wpuf-pro' ),
            'name'          => 'wpuf_cover_photo',
            'max_size'      => '2048', // default 2MB
            'extension'     => [ 'jpg', 'jpeg', 'png' ],
        ];

        return array_merge( $defaults, $props );
    }

    /**
     * Prepare entry
     *
     * @param $field
     *
     * @return void
     **/
    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;
    }

    /**
     * Process and save cover photo upload
     *
     * @since 4.2.3
     *
     * @param array $postdata Form post data
     * @param int   $user_id  User ID to save meta for
     *
     * @return void
     */
    public static function process_upload( $postdata, $user_id ) {
        if ( ! isset( $postdata['wpuf_files']['wpuf_cover_photo'] ) ) {
            return;
        }

        $attachment_id = absint( $postdata['wpuf_files']['wpuf_cover_photo'][0] );

        // Verify the attachment exists and is valid
        $attachment = get_post( $attachment_id );
        if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
            return;
        }

        $file_path = get_attached_file( $attachment_id );

        // Security: Remove any potential directory traversal
        $file_path = wp_normalize_path( realpath( $file_path ) );
        $upload_base = wp_normalize_path( realpath( wp_upload_dir()['basedir'] ) );

        // Verify the file is within uploads directory
        if ( ! $file_path || 0 !== strpos( $file_path, $upload_base ) ) {
            return;
        }

        // Use the validation function
        $validation_result = wpuf_validate_profile_photo_file( $file_path, basename( $file_path ) );

        if ( ! $validation_result || $validation_result['detected_mime'] !== $attachment->post_mime_type ) {
            return;
        }

        // Additional security checks for malicious content
        $file_content = file_get_contents( $file_path );
        if ( preg_match( '/<\?(php|=|\s)/i', $file_content ) ||
             preg_match( '/^(\x7FELF|\x4D\x5A)/', $file_content ) ||
             preg_match( '/^PK\x03\x04/', $file_content ) ) {
            return;
        }

        // Check file size (2MB limit)
        $max_size = apply_filters( 'wpuf_profile_photo_max_size', 2 * 1024 * 1024 );
        if ( $validation_result['file_size'] <= $max_size ) {
            update_user_meta( $user_id, 'wpuf_cover_photo', $attachment_id );
        }
    }

}
