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

use Elementor\Controls_Manager;
use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
use Softech_Addons_for_Elementor\Includes\Dynamic_Tags\Groups\Softech_Post_Group;

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

class Softech_Custom_Field_URL extends Tag {

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

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

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

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

    /**
     * Register the "Custom Field Key" control in the Elementor 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_url_field', 'softech-addons-for-elementor' ),
                'dynamic'     => [ 'active' => false ],
            ]
        );
    }

    /**
     * Render the URL output.
     *
     * Supported meta value formats:
     *  1. Plain URL string                          → used directly
     *  2. ACF link array  ['url' => '…', …]         → 'url' key extracted
     *  3. Serialized version of the above array     → unserialized first
     */
    public function render() {
        $post_id = get_the_ID();

        if ( ! $post_id ) {
            return;
        }

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

        if ( empty( $meta_key ) ) {
            return;
        }

        // 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;
        }

        $url = $this->resolve_url( $meta_value );

        if ( $url ) {
            echo esc_url( $url );
        }
    }

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

    /**
     * Resolve any supported meta value format to a plain URL string.
     *
     * @param  mixed       $meta_value
     * @return string|null  Valid URL or null if unresolvable.
     */
    private function resolve_url( $meta_value ) {

        // ── Case 1: Plain URL string ───────────────────────────────────────
        if ( is_string( $meta_value ) ) {

            // Try to unserialize — could be a stored array
            $unserialized = @maybe_unserialize( $meta_value );

            if ( is_array( $unserialized ) ) {
                return $this->extract_url_from_array( $unserialized );
            }

            // Validate and return as-is
            if ( filter_var( $meta_value, FILTER_VALIDATE_URL ) ) {
                return $meta_value;
            }
        }

        // ── Case 2: ACF Link array or any associative array with 'url' ────
        if ( is_array( $meta_value ) ) {
            return $this->extract_url_from_array( $meta_value );
        }

        return null;
    }

    /**
     * Pull the URL out of an array-format field value.
     *
     * ACF "Link" field returns:
     *   [ 'title' => '…', 'url' => 'https://…', 'target' => '_blank' ]
     *
     * @param  array       $array
     * @return string|null
     */
    private function extract_url_from_array( array $array ) {
        if ( ! empty( $array['url'] ) && filter_var( $array['url'], FILTER_VALIDATE_URL ) ) {
            return $array['url'];
        }

        // Fallback: first element that looks like a URL
        foreach ( $array as $value ) {
            if ( is_string( $value ) && filter_var( $value, FILTER_VALIDATE_URL ) ) {
                return $value;
            }
        }

        return null;
    }
}