<?php
/**
 * File Field Handler
 * 
 * @package HvnlyNab\Database\FieldTypes
 * @since 2.0.0
 */

namespace HvnlyNab\Database\FieldTypes;

class FileField extends BaseFieldType {
    public function __construct() {
        parent::__construct('file');
        $this->requires_assets = true;
    }
    
    public function render($field, $value, $post_id) {
        $file_type = $field['file_type'] ?? 'file';
        $field_id = esc_attr($field['fieldid']);
        $field_name = esc_attr($field['name']);
        $placeholder = esc_attr($field['placeholder'] ?? '');
        
        // Set data-type based on file_type
        $data_type = $file_type; // 'image', 'pdf', or 'file'
        
        ob_start();
        ?>
<div data-field-id="<?php echo esc_attr( $field_id ); ?>" data-field-type="file">
    <div>
        <label><?php echo esc_html( $field['label'] ); ?></label>
        <div class="hvnly-meta-field" style="display: block;margin:0px">
            <div class="hvnly-meta-input hvnly-popup-meta-input">
                <input type="text" id="<?php echo esc_attr( $field_id ); ?>"
                    name="<?php echo esc_attr( $field_name ); ?>" class="widefat"
                    value="<?php echo esc_attr( $value ); ?>" placeholder="<?php echo esc_attr( $placeholder ); ?>" />
                <div class="hvnly-preview-container">
                    <?php if ( ! empty( $value ) ) : ?>
                    <?php 
                                // The preview HTML is already escaped in the get_preview_html method
                                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                echo $this->get_preview_html( $value, $file_type, $field_id ); 
                                ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="button hvnly-upload-button"
                    data-target="#<?php echo esc_attr( $field_id ); ?>"
                    data-type="<?php echo esc_attr( $data_type ); ?>">
                    <?php 
                            // The button text is escaped in the get_upload_button_text method
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            echo $this->get_upload_button_text( $file_type ); 
                            ?>
                </button>
            </div>
        </div>
    </div>
</div>
<?php
        
        $html = ob_get_clean();
        $html .= $this->render_description( $field );
        
        return $html;
    }
    
    /**
     * Get upload button text based on file type
     *
     * @param string $file_type File type.
     * @return string Translated button text.
     */
    private function get_upload_button_text( $file_type ) {
        switch ( $file_type ) {
            case 'image':
                return esc_html__( 'Upload Image', 'havenlytics' );
            case 'pdf':
                return esc_html__( 'Upload PDF', 'havenlytics' );
            default:
                return esc_html__( 'Upload File', 'havenlytics' );
        }
    }
    
    /**
     * Get preview HTML based on file type
     *
     * @param string $value     File URL.
     * @param string $file_type File type.
     * @param string $field_id  Field ID.
     * @return string HTML preview.
     */
    private function get_preview_html( $value, $file_type, $field_id ) {
        $escaped_value     = esc_url( $value );
        $escaped_field_id  = esc_attr( $field_id );
        $escaped_basename  = esc_html( basename( $value ) );
        
        if ( 'pdf' === $file_type ) {
            return sprintf(
                '<div class="hvnly-preview-wrapper">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="color: #ff6b6b;">
                            <span class="dashicons dashicons-media-document" style="font-size: 32px;"></span>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #333;">%s</div>
                            <div style="font-size: 12px; color: #666;">PDF Document</div>
                        </div>
                    </div>
                    <button type="button" class="hvnly-remove-preview" data-target="%s" style="margin-top: 8px;">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>',
                $escaped_basename,
                $escaped_field_id
            );
        } elseif ( 'image' === $file_type ) {
            return sprintf(
                '<div class="hvnly-preview-wrapper">
                    <img src="%s" style="max-width:150px; height:auto;" alt="" />
                    <button type="button" class="hvnly-remove-preview" data-target="%s">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>',
                $escaped_value,
                $escaped_field_id
            );
        } else {
            return sprintf(
                '<div class="hvnly-preview-wrapper">
                    <a href="%s" target="_blank">%s</a>
                    <button type="button" class="hvnly-remove-preview" data-target="%s">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>',
                $escaped_value,
                esc_html__( 'View File', 'havenlytics' ),
                $escaped_field_id
            );
        }
    }
    
    /**
     * Save file field data.
     *
     * @param int    $post_id    Post ID.
     * @param string $field_name Field name.
     * @param mixed  $value      Field value.
     */
    public function save( $post_id, $field_name, $value ) {
        update_post_meta( $post_id, $field_name, esc_url_raw( $value ) );
    }
    
    /**
     * Sanitize file field value.
     *
     * @param mixed $value Field value.
     * @return string Sanitized URL.
     */
    public function sanitize( $value ) {
        return esc_url_raw( $value );
    }
    
    /**
     * Validate file field value.
     *
     * @param mixed $value Field value.
     * @param array $field Field configuration.
     * @return bool|\WP_Error True if valid, WP_Error otherwise.
     */
    public function validate( $value, $field ) {
        if ( isset( $field['is_required'] ) && $field['is_required'] && empty( $value ) ) {
            $message = sprintf(
                /* translators: %s: field label */
                __( 'The file field "%s" is required.', 'havenlytics' ),
                esc_html( $field['label'] )
            );
            return new \WP_Error( 'required_field', $message );
        }
        
        if ( ! empty( $value ) && ! filter_var( $value, FILTER_VALIDATE_URL ) ) {
            return new \WP_Error( 'invalid_url', __( 'Please enter a valid URL.', 'havenlytics' ) );
        }
        
        return true;
    }
    
    /**
     * Enqueue required assets.
     */
    public function enqueue_assets() {
        wp_enqueue_media();
    }
}