<?php
namespace Storzen\Fields;
use Storzen\Contracts\Field;
defined('ABSPATH') || exit;

class Image extends Field {
    public function sanitize( $raw ) { return absint( $raw ); }

    public function render( $value ) {
        $id      = $this->field_id();
        $preview = $id . '_preview';
        $val     = absint( $value );
        $url     = $val ? wp_get_attachment_image_url( $val, 'thumbnail' ) : '';
        wp_enqueue_media();
        echo '<div class="sz-image-field">';
        echo '<input type="hidden" id="' . esc_attr($id) . '" name="' . esc_attr($this->field_name()) . '" value="' . esc_attr($val) . '">';
        echo '<div class="sz-image-preview" id="' . esc_attr($preview) . '"' . ( $url ? '' : ' style="display:none"' ) . '>';
        if ( $url ) echo '<img src="' . esc_url($url) . '" alt="">';
        echo '</div>';
        echo '<div class="sz-image-actions">';
    $select_label = $val ? esc_html__('Change Image','storzen') : esc_html__('Select Image','storzen');
    $is_pro_active = defined('STORZEN_IS_PRO') && STORZEN_IS_PRO === 'yes';
    $show_pro = $this->pro && ! $is_pro_active;
    echo '<button type="button" class="sz-btn sz-btn--outline sz-btn--sm js-sz-media-select"';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- disabled attribute and $select_label are escaped
    echo ' data-target="' . esc_attr($id) . '" data-preview="' . esc_attr($preview) . '"' . ( $show_pro ? ' disabled' : '' ) . '>' . $select_label . '</button>';
    if ( $val ) {
        echo ' <button type="button" class="sz-btn sz-btn--ghost sz-btn--sm js-sz-media-remove"';
        echo ' data-target="' . esc_attr($id) . '" data-preview="' . esc_attr($preview) . '">' . esc_html__('Remove','storzen') . '</button>';
    }
    echo '</div></div>';
    if ( $show_pro ) echo '<span class="sz-pro-badge">PRO</span>';
    }
}
