<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://30liones.com/team
 * @since      1.0.0
 *
 * @package    Apartment_Fee_Display_Manager
 * @subpackage Apartment_Fee_Display_Manager/public
 */

/**
 * @package    Apartment_Fee_Display_Manager
 * @subpackage Apartment_Fee_Display_Manager/public
 * @author     Mark Szymanski <mark@30lines.com>
 */
class Apartment_Fee_Display_Manager_Public {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

	}

	public function enqueue_styles() {
		wp_enqueue_style( 
			$this->plugin_name, 
			plugin_dir_url( dirname( __FILE__ ) ) . 'dist/css/public-style.min.css', 
			array(), 
			$this->version, 
			'all' 
		);
	}

	public function enqueue_scripts() {
		wp_enqueue_script( 
			$this->plugin_name, 
			plugin_dir_url( dirname( __FILE__ ) ) . 'dist/js/public-script.min.js', 
			array(), 
			$this->version, 
			true 
		);
	}

	public function register_shortcodes() {
	    // Shortcode: [fees-calculator] or [fees-calculator id="123"]
	    add_shortcode( 'fees-calculator', array( $this, 'render_calculator' ) );
	    add_shortcode( 'fees-calculator-modal', array( $this, 'render_modal_calculator' ) );
	}

	private function get_calculated_accent_color() {

	    $acf_override = get_field('fees_accent_color_override', 'option');
	    if ( ! empty( $acf_override ) ) return $acf_override;

	    $rp_options = get_option( 'rentpress_options' );
	    if ( ! empty( $rp_options['rentpress_accent_color_section_input'] ) ) {
	        return $rp_options['rentpress_accent_color_section_input']; 
	    }

	    return '#0693e3';
	}

	private function darken_color( $hex, $factor ) {
	    $hex = str_replace( '#', '', $hex );
	    
	    if ( strlen( $hex ) == 3 ) {
	        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
	    }

	    // Convert to RGB
	    $r = hexdec( substr( $hex, 0, 2 ) );
	    $g = hexdec( substr( $hex, 2, 2 ) );
	    $b = hexdec( substr( $hex, 4, 2 ) );

	    // Darken (Divide by factor) and ensure valid range (0-255)
	    $r = max( 0, min( 255, $r / $factor ) );
	    $g = max( 0, min( 255, $g / $factor ) );
	    $b = max( 0, min( 255, $b / $factor ) );

	    // Convert back to Hex
	    return sprintf( "#%02x%02x%02x", $r, $g, $b );
	}

	/* -----------------------------------------------------------
	   Shared Logic
	----------------------------------------------------------- */
	private function get_calculator_data( $atts ) {
    // Context ID Logic
    $a = shortcode_atts( array( 
        'id'    => get_the_ID(),
        'container-title' => '',
    ), $atts );

    $context_id = intval( $a['id'] );
    $fee_source_id = $context_id;
    $default_title_text = '';
    $post_type = get_post_type( $context_id );

    // Check RentPress Floorplan logic
    if ( 'rentpress_floorplan' === get_post_type( $context_id ) ) {
        if ( function_exists( 'rentpress_getAllFloorplanDataWithCodeOrPostID' ) ) {
            
            $floorplan_data = rentpress_getAllFloorplanDataWithCodeOrPostID( $context_id );
            
            if ( ! empty( $floorplan_data->floorplan_parent_property_post_id ) ) {
                $fee_source_id = intval( $floorplan_data->floorplan_parent_property_post_id );
            }

            if ( ! empty( $floorplan_data->floorplan_name ) ) {
                $default_title_text = $floorplan_data->floorplan_name;
            }
        }
    }

    // 4. Title Logic
    $final_title = '';
    $community_override = get_field('fees_container_title', 'option');
    $fp_override        = get_field('fp_fees_container_title', 'option');
    $should_prepend     = get_field('prepend_community_name', 'option');
    
    // Grab the actual Community Name using the Parent Property ID
    $community_name = get_the_title( $fee_source_id ); 

    if ( 'rentpress_floorplan' === $post_type ) {
        // FLOOR PLAN CONTEXT
        // Use the Floor Plan override, fallback to the floor plan name ($default_title_text)
        $final_title = !empty( $fp_override ) ? $fp_override : $default_title_text;
    } else {
        // PROPERTY CONTEXT
        // Use the Community override, fallback to the property name
        $default_prop_name = !empty( $default_title_text ) ? $default_title_text : $community_name;
        $final_title = !empty( $community_override ) ? $community_override : $default_prop_name;
    }

    if ( $should_prepend && !empty( $community_name ) ) {
        if ( trim( $community_name ) !== trim( $final_title ) ) {
            $final_title = $community_name . ' - ' . $final_title;
        }
    }

    // SHORTCODE ATTRIBUTE OVERRIDE
    if ( ! empty( $a['container-title'] ) ) {
        $final_title = $a['container-title'];
    }

    // Fetch ACF Data
    $fees_repeater = get_field('apartment_fees', $fee_source_id);
    $sort_mode = get_field('fees_amenity_sort', 'option');
    $message_box   = get_field('message_box', $fee_source_id);
    
    if( ! $message_box ) { 
        $message_box = get_field('message_box', 'option'); 
    }

    if ( empty( $fees_repeater ) ) {
        $fees_repeater = get_field('apartment_fees', 'option');
    }

    // Sort Data
    $sorted_fees = [ 'oneTime' => [], 'monthly' => [], 'annual'  => [] ];
    if ( ! empty( $fees_repeater ) ) {
        foreach ( $fees_repeater as $fee ) {
            $raw_freq = isset($fee['frequency']) ? $fee['frequency'] : 'monthly';
            
            if ( $raw_freq === 'onetime' ) {
                $target_bucket = 'oneTime';
            } elseif ( $raw_freq === 'annual' ) {
                $target_bucket = 'annual';
            } else {
                $target_bucket = 'monthly';
            }

            if( isset($sorted_fees[$target_bucket]) ) {
                $sorted_fees[$target_bucket][] = $fee;
            }
        }
    }

    foreach ($sorted_fees as $key => &$bucket) {
        if ( empty($bucket) ) continue;

        if ( $sort_mode === 'alpha' ) {
            // Sort A-Z by fee_name
            usort($bucket, function($a, $b) {
                return strcasecmp($a['fee_name'], $b['fee_name']);
            });
        } elseif ( $sort_mode === 'price' ) {
            // Sort Low to High by Amount
            usort($bucket, function($a, $b) {
                return (float)$a['amount'] - (float)$b['amount'];
            });
        }
    }
    unset($bucket); // Break reference

    // Color Logic
    $base_color  = $this->get_calculated_accent_color();
    $hover_color = $this->darken_color( $base_color, 1.1 ); 

	    return array(
	        'post_id'     => $context_id,
	        'sorted_fees' => $sorted_fees,
	        'message_box' => $message_box,
	        'base_color'  => $base_color,
	        'hover_color' => $hover_color,
	        'display_title' => $final_title,
	    );
	}

	/* -----------------------------------------------------------
	   Inline Calculator
	----------------------------------------------------------- */
	public function render_calculator( $atts ) {
	    $data = $this->get_calculator_data( $atts );
	    
	    $post_id     = $data['post_id'];
	    $sorted_fees = $data['sorted_fees'];
	    $message_box = $data['message_box'];
	    $base_color  = $data['base_color'];
	    $hover_color = $data['hover_color'];
	    $display_title = $data['display_title'];

	    wp_enqueue_style( $this->plugin_name );
	    wp_enqueue_script( $this->plugin_name );

	    ob_start();
	    
	    // Pass variables explicitly to template via include
	    include plugin_dir_path( dirname( __FILE__ ) ) . 'public/partials/apartment-fee-display-manager-public-display.php';
	    
	    return ob_get_clean();
	}

	/* -----------------------------------------------------------
	   Modal Calculator
	----------------------------------------------------------- */
	public function render_modal_calculator( $atts ) {
		$data = $this->get_calculator_data( $atts );

		$post_id     = $data['post_id'];
		$sorted_fees = $data['sorted_fees'];
		$message_box = $data['message_box'];
		$base_color  = $data['base_color'];
		$hover_color = $data['hover_color'];
		$display_title = $data['display_title'];

		$a = shortcode_atts( array(
		  'button-title' => '',
		), $atts );

		$button_text = $a['button-title'];

		// Global Option
		if ( empty( $button_text ) ) {
		    $button_text = get_field('fees_modal_button_title', 'option');
		}

		// Default String
		if ( empty( $button_text ) ) {
		    $button_text = 'View Fees';
		}

		wp_enqueue_style( $this->plugin_name );
		wp_enqueue_script( $this->plugin_name );

		wp_enqueue_style( 'apartment-fee-modal-css', plugin_dir_url( dirname( __FILE__ ) ) . 'dist/css/modal-style.min.css', array(), '1.0', 'all' );
		wp_enqueue_script( 'apartment-fee-modal-js', plugin_dir_url( dirname( __FILE__ ) ) . 'dist/js/modal-script.min.js', array(), '1.0', true );

		ob_start();
		?>

		<button id="openFeeModalBtn" class="rentpress-fees-modal" style="background-color: <?php echo esc_attr($base_color); ?>; color: #fff; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer;">
		    <?php echo esc_html($button_text); ?>
		</button>

		<div id="feeCalculatorModal" class="custom-modal-overlay" style="display:none;">
		    <div class="custom-modal-content">
		        <span class="custom-modal-close">
		            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 24px; height: 24px;">
		              <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
		            </svg>
		        </span>
		        
		        <?php include plugin_dir_path( dirname( __FILE__ ) ) . 'public/partials/apartment-fee-display-manager-public-display.php'; ?>
		    </div>
		</div>

		<?php
		return ob_get_clean();
	}

	public function render_calculator_in_footer() {

	    // 1. Check if we are on a supported RentPress post type
	    if ( ! is_singular( 'rentpress_floorplan' ) && ! is_singular( 'rentpress_property' ) ) {
	        return;
	    }

	    $post_type = get_post_type();
	    $placement = ''; // shortcode, inline, modal

	    if ( $post_type === 'rentpress_floorplan' ) {
	        $placement = get_field('fees_calculator_placement', 'option');
	    } elseif ( $post_type === 'rentpress_property' ) {
	        $placement = get_field('fees_property_calculator_placement', 'option');
	    }

	    if ( empty($placement) || $placement === 'shortcode' ) {
	        return;
	    }

	    $html = '';
	    if ( $placement === 'inline' ) {
	        $html = $this->render_calculator( array() );
	    } elseif ( $placement === 'modal' ) {
	        $html = $this->render_modal_calculator( array() );
	    }

	    $target_selector = '';
	    $position = 'after';
	    $grid_wrapper_class = ''; // NEW: Empty by default

	    if ( $post_type === 'rentpress_floorplan' ) {
	        if ( $placement === 'inline' ) {
	            $target_selector = get_field('fees_single_floor_plan_location', 'option');
	        } elseif ( $placement === 'modal' ) {
	            $target_selector = get_field('fees_single_floor_plan_modal_button_location', 'option');
	        }
	    } elseif ( $post_type === 'rentpress_property' ) {
	        if ( $placement === 'inline' ) {
	            $target_selector = get_field('fees_single_property_location', 'option');
	        } elseif ( $placement === 'modal' ) {
	            $target_selector = get_field('fees_single_property_modal_button_location', 'option');
	        }
	    }

	    if ( $target_selector === '#property-pet-policy' ) {
	        $position = 'append';
	    }

	    if ( $target_selector === '.rentpress-single-floorplan-main-info-block-cta-wrapper' ) {
	        $position = 'after';
	        $grid_wrapper_class = 'col-sm-4 col-md-4 col-lg-4 col-xl-4 col-12 cta-rentpress-fees-modal-wrapper';
	    }

	   if ( ! empty($html) && ! empty($target_selector) ) {
        ?>
        <div id="fee-calculator-payload" style="display:none;" 
             data-target="<?php echo esc_attr($target_selector); ?>" 
             data-position="<?php echo esc_attr($position); ?>"
             data-wrapper-class="<?php echo esc_attr($grid_wrapper_class); ?>">
             <?php echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
        </div>
        <?php
    }
	}
} // Class Apartment_Fee_Display_Manager_Public