<?php
namespace Softech_Addons_for_Elementor\Includes\Dynamic_Tags\Tags\Image_Tags;

use Elementor\Controls_Manager;
use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module;
use Softech_Addons_for_Elementor\Includes\Dynamic_Tags\Groups\Softech_Image_Group;

if ( ! defined( 'ABSPATH' ) ) exit;

class Softech_Custom_Image_Field extends Data_Tag {

    public function get_name() {
        return 'softech-custom-image-field';
    }

    public function get_title() {
        return esc_html__( 'Custom Image Field', 'softech-addons-for-elementor' );
    }

    public function get_group() {
        return Softech_Image_Group::get_name();
    }

    public function get_categories() {
        return [ Module::IMAGE_CATEGORY ];
    }

    /**
     * Register controls shown in the Elementor dynamic tag panel.
     */
    protected function register_controls() {

        $this->add_control(
            'custom_field_key',
            [
                'label'       => esc_html__( 'Custom Field Key', 'softech-addons-for-elementor' ),
                'type'        => Controls_Manager::TEXT,
                'placeholder' => esc_html__( 'e.g. my_image_field', 'softech-addons-for-elementor' ),
                
                'dynamic'     => [ 'active' => false ],
            ]
        );

        $this->add_control(
            'show_placeholder',
            [
                'label'       => esc_html__( 'Show Placeholder', 'softech-addons-for-elementor' ),
                'type'        => Controls_Manager::SWITCHER,
                'label_on'    => esc_html__( 'Yes', 'softech-addons-for-elementor' ),
                'label_off'   => esc_html__( 'No', 'softech-addons-for-elementor' ),
                'default'     => 'yes',
                
            ]
        );
        $this->add_control(
            'fallback_image',
            [
                'label'     => esc_html__( 'Fallback Image', 'softech-addons-for-elementor' ),
                'type'      => Controls_Manager::MEDIA,
                'condition' => [
                    'show_placeholder' => '', // only visible when Show Placeholder is OFF
                ],
            ]
        );
        
    }

    /**
     * Resolve the meta value to an image array.
     *
     * Supported meta value formats:
     *  1. Attachment ID (integer)          → wp_get_attachment_image_url()
     *  2. Array with 'id' key              → treated as attachment ID
     *  3. Array with 'url' key             → used as direct URL (id = 0)
     *  4. Serialized version of the above  → unserialized first
     *  5. Plain URL string                 → used directly (id = 0)
     *
     * @param array $options
     * @return array|null  Returns null when no image found and placeholder is disabled.
     */
    // public function get_value( array $options = [] ) {
    //     $post_id = get_the_ID();

    //     if ( ! $post_id ) {
    //         return $this->fallback();
    //     }

    //     $meta_key = trim( $this->get_settings( 'custom_field_key' ) );

    //     if ( empty( $meta_key ) ) {
    //         return $this->fallback();
    //     }

    //     // Prefer ACF's get_field() when available for proper field resolution
    //     if ( function_exists( 'get_field' ) ) {
    //         $meta_value = get_field( $meta_key, $post_id );
    //     } else {
    //         $meta_value = get_post_meta( $post_id, $meta_key, true );
    //     }

    //     if ( empty( $meta_value ) ) {
    //         return $this->fallback();
    //     }

    //     // ── Case 1: Attachment ID (plain integer) ──────────────────────────
    //     if ( is_numeric( $meta_value ) ) {
    //         return $this->image_from_id( (int) $meta_value, $options );
    //     }

    //     // ── Case 2: Array (e.g. ACF image field in "array" return format) ──
    //     if ( is_array( $meta_value ) ) {
    //         if ( ! empty( $meta_value['id'] ) && is_numeric( $meta_value['id'] ) ) {
    //             return $this->image_from_id( (int) $meta_value['id'], $options );
    //         }
    //         if ( ! empty( $meta_value['url'] ) ) {
    //             return [
    //                 'id'  => isset( $meta_value['id'] ) ? (int) $meta_value['id'] : 0,
    //                 'url' => esc_url( $meta_value['url'] ),
    //             ];
    //         }
    //     }

    //     // ── Case 3: Serialized string ──────────────────────────────────────
    //     $unserialized = @maybe_unserialize( $meta_value );
    //     if ( is_array( $unserialized ) ) {
    //         if ( ! empty( $unserialized['id'] ) && is_numeric( $unserialized['id'] ) ) {
    //             return $this->image_from_id( (int) $unserialized['id'], $options );
    //         }
    //         if ( ! empty( $unserialized['url'] ) ) {
    //             return [
    //                 'id'  => 0,
    //                 'url' => esc_url( $unserialized['url'] ),
    //             ];
    //         }
    //     }

    //     // ── Case 4: Plain URL string ───────────────────────────────────────
    //     if ( filter_var( $meta_value, FILTER_VALIDATE_URL ) ) {
    //         return [
    //             'id'  => 0,
    //             'url' => esc_url( $meta_value ),
    //         ];
    //     }

    //     return $this->fallback();
    // }
    
        public function get_value( array $options = [] ) {
        $meta_key = trim( (string) $this->get_settings( 'custom_field_key' ) );
    
        if ( empty( $meta_key ) ) {
            return $this->fallback();
        }
    
        $meta_value = $this->get_current_acf_value( $meta_key );
    
        if ( empty( $meta_value ) ) {
            return $this->fallback();
        }
    
        // Attachment ID
        if ( is_numeric( $meta_value ) ) {
            return $this->image_from_id( (int) $meta_value, $options );
        }
    
        // Array value
        if ( is_array( $meta_value ) ) {
            if ( ! empty( $meta_value['id'] ) && is_numeric( $meta_value['id'] ) ) {
                return $this->image_from_id( (int) $meta_value['id'], $options );
            }
    
            if ( ! empty( $meta_value['url'] ) ) {
                return [
                    'id'  => ! empty( $meta_value['id'] ) ? (int) $meta_value['id'] : 0,
                    'url' => esc_url( $meta_value['url'] ),
                ];
            }
        }
    
        // Serialized value
        $unserialized = maybe_unserialize( $meta_value );
        if ( is_array( $unserialized ) ) {
            if ( ! empty( $unserialized['id'] ) && is_numeric( $unserialized['id'] ) ) {
                return $this->image_from_id( (int) $unserialized['id'], $options );
            }
    
            if ( ! empty( $unserialized['url'] ) ) {
                return [
                    'id'  => ! empty( $unserialized['id'] ) ? (int) $unserialized['id'] : 0,
                    'url' => esc_url( $unserialized['url'] ),
                ];
            }
        }
    
        // Plain URL
        if ( filter_var( $meta_value, FILTER_VALIDATE_URL ) ) {
            return [
                'id'  => 0,
                'url' => esc_url( $meta_value ),
            ];
        }
    
        return $this->fallback();
    }
    
    /**
     * Get ACF value from the current post OR current taxonomy term.
     */
    private function get_current_acf_value( string $meta_key ) {
        $queried_object = get_queried_object();
    
        // Taxonomy term context
        if ( $queried_object instanceof \WP_Term ) {
            if ( function_exists( 'get_field' ) ) {
                $term_context = $queried_object->taxonomy . '_' . $queried_object->term_id;
                $value        = get_field( $meta_key, $term_context );
    
                if ( ! empty( $value ) ) {
                    return $value;
                }
            }
    
            return get_term_meta( $queried_object->term_id, $meta_key, true );
        }
    
        // Post context
        $post_id = get_the_ID();
        if ( ! $post_id ) {
            return '';
        }
    
        if ( function_exists( 'get_field' ) ) {
            return get_field( $meta_key, $post_id );
        }
    
        return get_post_meta( $post_id, $meta_key, true );
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Helpers
    // ─────────────────────────────────────────────────────────────────────────

    /**
     * Decide what to return when no image is found.
     *
     * Returns the Elementor placeholder array when the toggle is ON.
     * Returns an empty array (renders nothing) when the toggle is OFF.
     *
     * @return array
     */
    private function fallback() {
        $show_placeholder = $this->get_settings( 'show_placeholder' );
    
        if ( 'yes' === $show_placeholder ) {
            return $this->get_placeholder_image();
        }
    
        // Check for a manually chosen fallback image
        $fallback = $this->get_settings( 'fallback_image' );
    
        if ( ! empty( $fallback['url'] ) ) {
            return [
                'id'  => ! empty( $fallback['id'] ) ? (int) $fallback['id'] : 0,
                'url' => esc_url( $fallback['url'] ),
            ];
        }
    
        // Nothing configured — render nothing
        return [];
    }

    /**
     * Build an image array from an attachment ID, respecting image size options.
     * Falls back via fallback() so the placeholder toggle is always respected.
     *
     * @param int   $image_id
     * @param array $options
     * @return array
     */
    private function image_from_id( int $image_id, array $options ) {
        if ( ! wp_attachment_is_image( $image_id ) ) {
            return $this->fallback();
        }

        $size = ! empty( $options['image_size'] ) ? $options['image_size'] : 'large';

        // Handle custom dimensions
        if ( 'custom' === $size ) {
            $custom_dimension = ! empty( $options['image_custom_dimension'] )
                ? $options['image_custom_dimension']
                : [ 'width' => 800, 'height' => 600 ];

            $size = [
                absint( $custom_dimension['width'] ),
                absint( $custom_dimension['height'] ),
            ];
        }

        $image_url = wp_get_attachment_image_url( $image_id, $size );

        if ( ! $image_url ) {
            return $this->fallback();
        }

        return [
            'id'  => $image_id,
            'url' => $image_url,
        ];
    }

    /**
     * Returns the Elementor default placeholder image array.
     *
     * @return array
     */
    private function get_placeholder_image() {
        return [
            'id'  => 0,
            'url' => \Elementor\Utils::get_placeholder_image_src(),
        ];
    }
}