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

/**
 * Post Term URL – Dynamic Tag
 *
 * In a loop over partner CPT posts, outputs the permalink of the taxonomy
 * term assigned to each post — NOT the post permalink itself.
 *
 * Example:
 *   Post permalink  → /alaya/the-lotus-leaf-2/        (wrong, what was happening)
 *   Term permalink  → /alaya/partner/the-lotus-leaf/  (correct, what this outputs)
 *
 * Usage: Container link → Dynamic tag → "Post Term URL"
 *        Taxonomy: partner (or whatever your taxonomy slug is)
 *
 * Drop into: includes/dynamic-tags/tags/post-tags/
 */
class Softech_Post_Term_Url extends Tag {

    public function get_name() {
        return 'softech-post-term-url';
    }

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

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

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

    protected function register_controls() {

        // Taxonomy dropdown — lists all registered taxonomies
        $this->add_control(
            'taxonomy',
            [
                'label'       => esc_html__( 'Taxonomy', 'softech-addons-for-elementor' ),
                'type'        => Controls_Manager::SELECT,
                'options'     => $this->get_taxonomy_options(),
                'default'     => '',
                'description' => esc_html__( 'Select the taxonomy. The first term assigned to the current post will be used for the URL.', 'softech-addons-for-elementor' ),
            ]
        );

        // Which term to use when the post has multiple terms in the taxonomy
        $this->add_control(
            'term_index',
            [
                'label'       => esc_html__( 'Term', 'softech-addons-for-elementor' ),
                'type'        => Controls_Manager::SELECT,
                'options'     => [
                    '0' => esc_html__( 'First term', 'softech-addons-for-elementor' ),
                    '1' => esc_html__( 'Second term', 'softech-addons-for-elementor' ),
                    '2' => esc_html__( 'Third term', 'softech-addons-for-elementor' ),
                ],
                'default'     => '0',
            ]
        );

        $this->add_control(
            'fallback',
            [
                'label'       => esc_html__( 'Fallback URL', 'softech-addons-for-elementor' ),
                'type'        => Controls_Manager::TEXT,
                'placeholder' => 'https://',
            ]
        );
    }

    public function render() {
        $taxonomy = $this->get_settings( 'taxonomy' );

        if ( empty( $taxonomy ) ) {
            $this->render_fallback();
            return;
        }

        // get_the_ID() works correctly inside Elementor's loop —
        // Elementor calls setup_postdata() for each item before rendering.
        $post_id = get_the_ID();

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

        $terms = get_the_terms( $post_id, $taxonomy );

        if ( empty( $terms ) || is_wp_error( $terms ) ) {
            $this->render_fallback();
            return;
        }

        // Pick the term at the configured index (default: first)
        $index = (int) $this->get_settings( 'term_index' );
        $term  = isset( $terms[ $index ] ) ? $terms[ $index ] : $terms[0];

        $url = get_term_link( $term );

        if ( is_wp_error( $url ) ) {
            $this->render_fallback();
            return;
        }

        echo esc_url( $url );
    }

    private function render_fallback() {
        $fallback = trim( (string) $this->get_settings( 'fallback' ) );
        if ( ! empty( $fallback ) ) {
            echo esc_url( $fallback );
        }
    }

    private function get_taxonomy_options(): array {
        $options = [ '' => esc_html__( '— Select Taxonomy —', 'softech-addons-for-elementor' ) ];

        $taxonomies = get_taxonomies( [ 'public' => true ], 'objects' );

        foreach ( $taxonomies as $taxonomy ) {
            $options[ $taxonomy->name ] = $taxonomy->label . ' (' . $taxonomy->name . ')';
        }

        return $options;
    }
}