<?php
/**
 * Media-library image picker field for auction term meta.
 * @var $key string
 * @var $data array
 */
$fieldId = 'term_meta_auction_' . $key;
?>
<tr class="form-field term-auction__<?= $key ?>">
    <th scope="row"><label for="<?= $fieldId ?>"><?php _e( $data['label'], 'auctionforge' ); ?></label></th>
    <td>
        <input type="hidden" name="term_meta[auction_<?= $key ?>]" id="<?= $fieldId ?>" value="<?= esc_attr($data['value']) ?>">
        <div id="<?= $fieldId ?>_preview" style="margin-bottom:8px;<?= empty($data['preview']) ? 'display:none;' : '' ?>">
            <img src="<?= esc_url($data['preview']) ?>" style="max-width:200px;height:auto;border:1px solid #ddd;" alt="">
        </div>
        <button type="button" class="button" id="<?= $fieldId ?>_upload"><?php _e('Select image', 'auctionforge'); ?></button>
        <button type="button" class="button" id="<?= $fieldId ?>_remove" style="<?= empty($data['value']) ? 'display:none;' : '' ?>"><?php _e('Remove', 'auctionforge'); ?></button>
        <p class="description"><?php _e($data['description'], 'auctionforge'); ?></p>
        <script>
        jQuery(function ($) {
            var frame,
                $input = $('#<?= $fieldId ?>'),
                $preview = $('#<?= $fieldId ?>_preview'),
                $remove = $('#<?= $fieldId ?>_remove');
            $('#<?= $fieldId ?>_upload').on('click', function (e) {
                e.preventDefault();
                if (!window.wp || !wp.media) {
                    return;
                }
                if (!frame) {
                    frame = wp.media({
                        title: '<?= esc_js(__('Select cover image', 'auctionforge')) ?>',
                        library: {type: 'image'},
                        multiple: false
                    });
                    frame.on('select', function () {
                        var att = frame.state().get('selection').first().toJSON();
                        var thumb = (att.sizes && (att.sizes.medium || att.sizes.full)) ? (att.sizes.medium || att.sizes.full).url : att.url;
                        $input.val(att.id);
                        $preview.show().find('img').attr('src', thumb);
                        $remove.show();
                    });
                }
                frame.open();
            });
            $remove.on('click', function (e) {
                e.preventDefault();
                $input.val('');
                $preview.hide().find('img').attr('src', '');
                $remove.hide();
            });
        });
        </script>
    </td>
</tr>
