<?php

namespace auctionforge\inc\controllers;

use auctionforge\inc\helpers\View;

/**
 * Per-auction cover image override.
 *
 * BidSpirit stores auction cover images at 400x400 max, which looks pixelated
 * in wide/retina card layouts. This adds a "Cover Image" field to the auction
 * edit screen (Bidspirit -> Auctions -> edit) where the auction house can
 * upload a high resolution replacement from the media library. When set, the
 * attachment is used instead of the BidSpirit day image wherever auction
 * cards/covers render (see the applyToDays() call sites). The stored
 * auction_days term meta is never modified, so removing the override reverts
 * to the BidSpirit image and sync/auto-end code paths are unaffected.
 *
 * Saving needs no extra handler: the field posts term_meta[auction_cover_image],
 * which BidspiritLots::bidspirit_save_taxonomy_custom_meta_field() persists.
 */
class CoverImageOverride
{
    const META_KEY = 'auction_cover_image';

    public function init()
    {
        add_action('auction_number_edit_form_fields', array($this, 'render_field'), 20);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_media'));
    }

    /**
     * Load the WP media library scripts on the auction term edit screen.
     * @param string $hook
     */
    public function enqueue_media($hook)
    {
        if ($hook !== 'term.php' && $hook !== 'edit-tags.php') {
            return;
        }
        $screen = get_current_screen();
        if ($screen && $screen->taxonomy === BidspiritLots::TAX_AUCTION_TYPE) {
            wp_enqueue_media();
        }
    }

    /**
     * Render the image picker on the auction term edit screen.
     * @param \WP_Term $term
     */
    public function render_field($term)
    {
        $attachmentId = (int) get_term_meta($term->term_id, self::META_KEY, true);
        echo View::render('admin.view.fields.term_image', array(
            'key' => 'cover_image',
            'data' => array(
                'label' => __('Cover Image', 'auctionforge'),
                'description' => __('Optional high resolution replacement for the BidSpirit auction cover (BidSpirit covers are limited to 400x400 and can look pixelated on large or retina displays). Used on auction cards and cover areas. Remove it to fall back to the BidSpirit image.', 'auctionforge'),
                'value' => $attachmentId ? $attachmentId : '',
                'preview' => $attachmentId ? wp_get_attachment_image_url($attachmentId, 'medium') : '',
                'class' => '',
            ),
        ));
    }

    /**
     * Resolve the override image URL for an auction term, or '' when unset.
     * @param int $termId
     * @return string
     */
    public static function getUrl($termId)
    {
        $attachmentId = (int) get_term_meta($termId, self::META_KEY, true);
        if (!$attachmentId) {
            return '';
        }
        $url = wp_get_attachment_image_url($attachmentId, 'large');
        if (!$url) {
            $url = wp_get_attachment_image_url($attachmentId, 'full');
        }
        return $url ? $url : '';
    }

    /**
     * Apply the override to a term's auction_days array at render time.
     * Day objects are cloned so cached/stored term meta is never mutated
     * (the sync auto-end path reads auction_days and writes it back).
     *
     * @param mixed $days auction_days value from term meta
     * @param int $termId
     * @return mixed
     */
    public static function applyToDays($days, $termId)
    {
        if (!is_array($days) || empty($days)) {
            return $days;
        }
        $url = self::getUrl($termId);
        if (!$url) {
            return $days;
        }
        $result = array();
        foreach ($days as $index => $day) {
            if (is_object($day)) {
                $day = clone $day;
                $day->image = $url;
            }
            $result[$index] = $day;
        }
        return $result;
    }
}
