<?php

/**
 * Provide a public-facing view for the plugin
 *
 * This file is used to markup the public-facing aspects of the plugin.
 *
 * @link       https://30liones.com/team
 * @since      1.0.0
 *
 * @package    Apartment_Fee_Display_Manager
 * @subpackage Apartment_Fee_Display_Manager/public/partials
 */

if ( defined( 'RENTPRESS_PLUGIN_DATA_ACCESS' ) ) {
    require_once RENTPRESS_PLUGIN_DATA_ACCESS . 'data_layer.php';
}

$floorplan = null;
$property_data = null;
$floorplan_rent_default = '';
$calculated_title = get_the_title( $post_id ); 
$current_post_type = get_post_type( $post_id );
// Fetch custom labels, fallback to defaults if empty
$label_onetime = get_field('fees_label_onetime', 'option') ?: 'One-Time Fees';
$label_monthly = get_field('fees_label_monthly', 'option') ?: 'Monthly Fees';
$label_annual  = get_field('fees_label_annual', 'option') ?: 'Annual Fees';

if ( 'rentpress_floorplan' === $current_post_type ) {
    if ( function_exists( 'rentpress_getAllFloorplanDataWithCodeOrPostID' ) ) {
        $floorplan = rentpress_getAllFloorplanDataWithCodeOrPostID( $post_id );
        
        if ( $floorplan && isset( $floorplan->floorplan_rent_base ) ) {
            $floorplan_rent_default = $floorplan->floorplan_rent_base;
        }
        
        if ( $floorplan && ! empty( $floorplan->floorplan_name ) ) {
            $calculated_title = '' . $floorplan->floorplan_name;
        }
    }
} elseif ( 'rentpress_property' === $current_post_type ) {
    if ( function_exists( 'rentpress_getAllPropertyDataWithCodeOrPostID' ) ) {
        $property_data = rentpress_getAllPropertyDataWithCodeOrPostID( $post_id );
        
        $floorplan_rent_default = 0; 
        
        $rent_keys_to_check = array('property_rent_min', 'property_rent_base', 'property_rent_best');

        if ( is_array( $property_data ) ) {
            foreach ( $rent_keys_to_check as $key ) {
                if ( !empty( $property_data[$key] ) ) {
                    $floorplan_rent_default = $property_data[$key];
                    break;
                }
            }
        } elseif ( is_object( $property_data ) ) {
            foreach ( $rent_keys_to_check as $key ) {
                if ( !empty( $property_data->$key ) ) {
                    $floorplan_rent_default = $property_data->$key;
                    break;
                }
            }
        }
        
        $calculated_title = get_the_title( $post_id );
    }
}

if ( empty( $floorplan_rent_default ) ) {
    $min_rent = get_post_meta( $post_id, 'rentpress_min_rent', true );
    
    if ( ! empty( $min_rent ) ) {
        $floorplan_rent_default = $min_rent;
    }
}

$global_title_override = get_field('fees_container_title', 'option');
if ( ! empty( $global_title_override ) ) {
    $calculated_title = $global_title_override;
}

$modal_cta_placement = get_field('modal_cta_placement', 'option');
if ( empty($modal_cta_placement) ) {
    $modal_cta_placement = 'above_table'; // Safe fallback
}

if ( ! empty( $display_title ) && $display_title !== get_the_title( $post_id ) ) {
    $calculated_title = $display_title;
}

if ( ! function_exists( 'render_fee_section_safe' ) ) {
    function render_fee_section_safe($key, $title, $fees) {
        if (empty($fees)) return;
        
        $section_total = 0;
        foreach($fees as $f) { $section_total += (float) $f['amount']; }
        
        // $per_month_display = ($key === 'annual') 
        //     ? ' <span class="per-month">( $'. number_format($section_total/12, 2) .'/month)</span>' 
        //     : '';
        ?>
        
        <div id="<?php echo esc_attr($key); ?>Fees" class="fees-list-container">
            <h3><?php echo esc_html($title); ?></h3>
            <ul class="fees-list">
                <li class="fees-list-header">
                    <span class="is-fee">Fee</span>
                    <span class="is-amount">Amount</span>
                    <span class="is-qty">Quantity</span>
                </li>
                
                <?php foreach($fees as $fee): 
                    $name  = isset($fee['fee_name']) ? $fee['fee_name'] : 'Unnamed Fee';
                    $desc  = isset($fee['description']) ? $fee['description'] : '';
                    $price = isset($fee['amount']) ? (float) $fee['amount'] : 0;
                    
                    $is_trans = !empty($fee['transactional']);
                    $min_one  = !empty($fee['min_one']);
                    $max_qty  = !empty($fee['max_number']) ? (int) $fee['max_number'] : 99;
                    $start_qty = ($min_one) ? 1 : 0;
                ?>
                    <li class="fees-list-item" 
                        data-freq="<?php echo esc_attr($key); ?>" 
                        data-price="<?php echo esc_attr($price); ?>"
                        <?php if($is_trans) echo 'data-transactional="true"'; ?>
                    >
                        <span class="is-fee">
                            <?php echo esc_html($name); ?>
                            <?php if($desc): ?>
                                <span class="info-icon-container" tabindex="0">
                                    <span class="is-desc"><?php echo esc_html($desc); ?></span>
                                    <svg class="fee-info-icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                      <path stroke-linecap="round" stroke-linejoin="round" d="m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z" />
                                    </svg>
                                </span>
                            <?php endif; ?>
                        </span>
                        
                        <span class="is-amount">$<?php echo number_format($price, 2); ?></span>
                        
                        <span class="is-counter">
                            <?php if($is_trans): ?>
                                <?php if($max_qty === 1): ?>
                                    <input type="checkbox" class="fee-checkbox" 
                                        <?php checked($start_qty, 1); ?> 
                                        <?php disabled($min_one, true); // Lock it checked if it's mandatory ?>
                                    />
                                    <span>(Add)</span>
                                <?php else: ?>
                                    <div class="counter-control" data-max="<?php echo esc_attr($max_qty); ?>" data-min="<?php echo esc_attr($start_qty); ?>">
                                        <button aria-label="Decrease quantity" class="counter-sub" <?php disabled($start_qty, 0); ?>>-</button>
                                        <span class="counter-amount"><?php echo esc_html($start_qty); ?></span>
                                        <button aria-label="Increase quantity" class="counter-add" <?php disabled($start_qty, $max_qty); ?>>+</button>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span>1</span>
                            <?php endif; ?>
                        </span>
                    </li>
                <?php endforeach; ?>

                <li class="fees-list-total">
                    <span><strong>Total</strong></span>
                    <span class="is-total">
                        <strong>$<?php echo number_format($section_total, 2); ?></strong>
                    </span>
                    <span></span>
                </li>
            </ul>
        </div>
    <?php } 
}
?>

<div id="rentalFees" class="rental-fees-container" style="--dark-accent-bg: <?php echo esc_attr($base_color); ?>; --dark-accent-hover: <?php echo esc_attr($hover_color); ?>;">

    <div class="rental-fees-container-header">
    <?php if ( ! empty( $calculated_title ) ): ?>
        <h2 class="fee-container-title"><?php echo esc_html( $calculated_title ); ?></h2>
    <?php endif; ?>
    <?php if ( $modal_cta_placement === 'above_table' ) : ?>
        <div class="rentpress-dynamic-cta-target rental-fees-container-cta"></div>
    <?php endif; ?>
    </div>

    <div class="fees-column">
        <?php 
        render_fee_section_safe('oneTime', esc_html( $label_onetime ), $sorted_fees['oneTime']);
        render_fee_section_safe('monthly', esc_html( $label_monthly ), $sorted_fees['monthly']);
        render_fee_section_safe('annual', esc_html( $label_annual ), $sorted_fees['annual']);
        ?>
    </div>

    <div id="totalsContainer" class="totals-container">
        <div class="is-base-rent">
            <label><strong>Enter Your Base Rent:</strong></label>
            <div class="base-rent-wrapper"><input type="text" class="fee-calc-input" inputmode="numeric" id="baseRent" value="$<?php echo esc_attr( number_format( (float) $floorplan_rent_default, 0 ) ); ?>"></div>
        </div>
        <div class="is-output">
             <div id="oneTimeTotalRow" style="display: none;">
                <span><small>*Total <?php echo esc_html( $label_onetime ); ?>: $<span id="oneTimeFeesOutput">0.00</span></small></span>
            </div>

            <div id="annualTotalRow" style="display: none;">
                <span><small>*Total <?php echo esc_html( $label_annual ); ?>: $<span id="annualFeesOutput">0.00</span></small></span>
            </div>

            <div class="is-output-total">
                <span><?php echo esc_html( $label_monthly ); ?>: </span>
                <span id="monthlyFeesOutput">0.00</span>
            </div>

            <div class="is-output-total">
                <span>Total Monthly Cost: </span>
                <span id="totalMonthly">0.00</span>
            </div>
        </div>

        <?php if ( $modal_cta_placement === 'under_totals' ) : ?>
            <div class="rentpress-dynamic-cta-target totals-cta-option"></div>
        <?php endif; ?>
        
        <?php if( !empty($message_box) ): ?>
            <div id="feesAdditionalInfo" class="fees-additional-info">
                <?php echo wp_kses_post( $message_box ); ?>
            </div>
        <?php endif;

        $url_ext = get_field('parent_floorplan_url_extension', 'option');
        if ( empty($url_ext) ) {
            $url_ext = ''; 
        }
        $units = isset($floorplan->floorplan_units_available) ? (int) $floorplan->floorplan_units_available : 0;
        if ( $units === 0 && !empty($floorplan->floorplan_parent_property_post_link) ) : 
        $clean_ext = ltrim($url_ext, '/');
        $url = trailingslashit( $floorplan->floorplan_parent_property_post_link ) . $clean_ext;
        $url = str_replace('/#', '#', $url);
        ?>
            <a href="<?php echo esc_url( $url ); ?>" class="button v-btn available-floorplans-btn button">Available Floor Plans</a>
        <?php endif; ?>
    </div>
</div>
<?php
include plugin_dir_path( __FILE__ ) . 'apartment-fee-display-manager-schema-floorplan.php';
?>