<?php
/**
 * Wizard Step 4: Pricing (Enhanced with Icons)
 * 
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

$step4 = $wizard_data['step_4'] ?? [];
$offer_type = $wizard_data['step_1']['offer_type'] ?? 'day';

$base_price = floatval($step4['base_price'] ?? 0);
$price_unit = $step4['price_unit'] ?? ($offer_type === 'slot' ? 'hour' : 'day');
$quick_rules = $step4['quick_rules'] ?? [];
$custom_rules = $step4['custom_rules'] ?? [];

$currency_symbol = html_entity_decode(get_woocommerce_currency_symbol());

// Available icons for pricing rules (20 relevant icons)
$available_icons = [
    '📅' => __('Calendar', 'wahra-rentals-bookings'),
    '📆' => __('Planning', 'wahra-rentals-bookings'),
    '⏰' => __('Clock', 'wahra-rentals-bookings'),
    '🌙' => __('Night/Weekend', 'wahra-rentals-bookings'),
    '☀️' => __('Day', 'wahra-rentals-bookings'),
    '🌅' => __('High season', 'wahra-rentals-bookings'),
    '❄️' => __('Low season', 'wahra-rentals-bookings'),
    '⚡' => __('Last minute', 'wahra-rentals-bookings'),
    '🐦' => __('Early booking', 'wahra-rentals-bookings'),
    '📉' => __('Discount', 'wahra-rentals-bookings'),
    '📈' => __('Surcharge', 'wahra-rentals-bookings'),
    '💰' => __('Savings', 'wahra-rentals-bookings'),
    '🏷️' => __('Promo', 'wahra-rentals-bookings'),
    '⭐' => __('Premium', 'wahra-rentals-bookings'),
    '🔥' => __('Flash offer', 'wahra-rentals-bookings'),
    '🎁' => __('Gift', 'wahra-rentals-bookings'),
    '👥' => __('Group', 'wahra-rentals-bookings'),
    '🔄' => __('Long stay', 'wahra-rentals-bookings'),
    '📊' => __('Variable rate', 'wahra-rentals-bookings'),
    '✅' => __('Included', 'wahra-rentals-bookings'),
];

$days_labels = [
    'mon' => __('Mo', 'wahra-rentals-bookings'),
    'tue' => __('Tu', 'wahra-rentals-bookings'),
    'wed' => __('We', 'wahra-rentals-bookings'),
    'thu' => __('Th', 'wahra-rentals-bookings'),
    'fri' => __('Fr', 'wahra-rentals-bookings'),
    'sat' => __('Sa', 'wahra-rentals-bookings'),
    'sun' => __('Su', 'wahra-rentals-bookings'),
];

// Default quick rules config - each rule specifies which modes it applies to
$default_rules = [
    'weekend' => [
        'icon' => '🌙',
        'title' => __('Weekend', 'wahra-rentals-bookings'),
        'desc' => __('Surcharge on weekend days', 'wahra-rentals-bookings'),
        'default_value' => 15,
        'default_days' => ['fri', 'sat', 'sun'],
        'type' => 'weekend',
        'modes' => ['day', 'slot', 'service'], // All modes
    ],
    'long_stay' => [
        'icon' => '🔄',
        'title' => __('Long Stay', 'wahra-rentals-bookings'),
        'desc' => __('Discount for long rentals', 'wahra-rentals-bookings'),
        'default_value' => -10,
        'default_threshold' => 7,
        'type' => 'duration',
        'modes' => ['day'], // Only day mode - not applicable to slot/service
    ],
    'early_bird' => [
        'icon' => '🐦',
        'title' => __('Early Booking', 'wahra-rentals-bookings'),
        'desc' => __('Discount for booking in advance', 'wahra-rentals-bookings'),
        'default_value' => -5,
        'default_threshold' => 30,
        'type' => 'advance',
        'modes' => ['day', 'slot', 'service'], // All modes
    ],
    'last_minute' => [
        'icon' => '⚡',
        'title' => __('Last Minute', 'wahra-rentals-bookings'),
        'desc' => __('Last minute surcharge or discount', 'wahra-rentals-bookings'),
        'default_value' => 20,
        'default_threshold' => 48,
        'type' => 'last_minute',
        'modes' => ['day', 'slot', 'service'], // All modes
    ],
];

$price_units = [
    'day' => __('Per day', 'wahra-rentals-bookings'),
    'hour' => __('Per hour', 'wahra-rentals-bookings'),
    'slot' => __('Per slot', 'wahra-rentals-bookings'),
    'fixed' => __('Fixed price', 'wahra-rentals-bookings'),
];
?>

<div class="wahrb-step wahrb-step-4" data-step="4">
    <!-- Hero Price Input -->
    <div class="wahrb-pricing-hero">
        <h3>💰 <?php esc_html_e('Your Base Rate', 'wahra-rentals-bookings'); ?></h3>
        <div class="wahrb-price-input-wrapper">
            <div class="wahrb-price-big-input">
                <span class="currency"><?php echo esc_html($currency_symbol); ?></span>
                <input type="number" name="base_price" id="base_price" 
                       value="<?php echo esc_attr($base_price ?: ''); ?>" 
                       min="0" step="0.01" placeholder="0" required>
            </div>
            <?php if ($offer_type === 'slot'): ?>
                <input type="hidden" name="price_unit" id="price_unit" value="hour">
                <span class="wahrb-price-unit-fixed"><?php echo esc_html($price_units['hour']); ?></span>
            <?php elseif ($offer_type === 'service'): ?>
                <input type="hidden" name="price_unit" id="price_unit" value="fixed">
                <span class="wahrb-price-unit-fixed"><?php echo esc_html($price_units['fixed']); ?></span>
            <?php else: ?>
                <select name="price_unit" id="price_unit" class="wahrb-price-unit-select">
                    <?php foreach ($price_units as $key => $label): ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($price_unit, $key); ?>>
                            <?php echo esc_html($label); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            <?php endif; ?>
        </div>
        <div class="wahrb-price-preview">
            <span class="wahrb-price-preview-label"><?php esc_html_e('Your customers will see', 'wahra-rentals-bookings'); ?></span>
            <span class="wahrb-price-preview-value" id="price-preview">
                <?php echo esc_html($currency_symbol . number_format($base_price, 2) . ' / ' . ($price_units[$price_unit] ?? __('day', 'wahra-rentals-bookings'))); ?>
            </span>
        </div>
    </div>

    <!-- Quick Rules -->
    <div class="wahrb-rules-section">
        <h3>⚡ <?php esc_html_e('Quick Rules', 'wahra-rentals-bookings'); ?></h3>
        <p class="desc"><?php esc_html_e('Enable automatic price adjustments', 'wahra-rentals-bookings'); ?></p>

        <?php foreach ($default_rules as $rule_key => $rule): 
            // Skip rules that don't apply to current booking mode
            $allowed_modes = $rule['modes'] ?? ['day'];
            if (!in_array($offer_type, $allowed_modes)) {
                continue;
            }
            
            $saved = $quick_rules[$rule_key] ?? [];
            $is_enabled = !empty($saved['enabled']);
            $current_icon = $saved['icon'] ?? $rule['icon'];
            $current_value = $saved['value'] ?? $rule['default_value'];
            $current_days = $saved['days'] ?? ($rule['default_days'] ?? []);
            $current_threshold = $saved['threshold'] ?? ($rule['default_threshold'] ?? 7);
            $show_client = !empty($saved['show_client']) || !isset($saved['show_client']);
        ?>
        <div class="wahrb-quick-rule <?php echo esc_attr( $is_enabled ? 'active' : '' ); ?>" data-rule="<?php echo esc_attr($rule_key); ?>">
            <div class="wahrb-quick-rule-header">
                <div class="wahrb-rule-toggle <?php echo esc_attr( $is_enabled ? 'on' : '' ); ?>"></div>
                <input type="hidden" name="quick_rules[<?php echo esc_attr($rule_key); ?>][enabled]" 
                       value="<?php echo esc_attr( $is_enabled ? '1' : '0' ); ?>" class="rule-enabled-input">
                
                <span class="wahrb-rule-icon-fixed">
                    <?php echo esc_html($rule['icon']); ?>
                </span>
                <input type="hidden" name="quick_rules[<?php echo esc_attr($rule_key); ?>][icon]" 
                       value="<?php echo esc_attr($rule['icon']); ?>" class="rule-icon-input">
                
                <div class="wahrb-rule-info">
                    <strong><?php echo esc_html($rule['title']); ?></strong>
                    <small><?php echo esc_html($rule['desc']); ?></small>
                </div>
                
                <div class="wahrb-rule-value">
                    <input type="number" name="quick_rules[<?php echo esc_attr($rule_key); ?>][value]" 
                           value="<?php echo esc_attr($current_value); ?>" step="1">
                    <span>%</span>
                </div>
            </div>
            
            <div class="wahrb-rule-config">
                <?php if ($rule_key === 'weekend'): ?>
                    <div class="wahrb-config-row">
                        <span class="wahrb-config-label"><?php esc_html_e('Days:', 'wahra-rentals-bookings'); ?></span>
                        <?php foreach ($days_labels as $day_key => $day_label): ?>
                            <button type="button" class="wahrb-day-chip <?php echo esc_attr( in_array($day_key, $current_days) ? 'selected' : '' ); ?>" 
                                    data-day="<?php echo esc_attr($day_key); ?>">
                                <?php echo esc_html($day_label); ?>
                            </button>
                            <input type="hidden" name="quick_rules[<?php echo esc_attr($rule_key); ?>][days][]" 
                                   value="<?php echo esc_attr($day_key); ?>" 
                                   <?php echo esc_attr( in_array($day_key, $current_days) ? '' : 'disabled' ); ?>
                                   class="day-input-<?php echo esc_attr($day_key); ?>">
                        <?php endforeach; ?>
                    </div>
                
                <?php elseif ($rule_key === 'long_stay'): ?>
                    <div class="wahrb-config-row">
                        <span class="wahrb-config-label"><?php esc_html_e('From', 'wahra-rentals-bookings'); ?></span>
                        <input type="number" name="quick_rules[<?php echo esc_attr($rule_key); ?>][threshold]" 
                               value="<?php echo esc_attr($current_threshold); ?>" 
                               min="2" max="365" class="wahrb-config-input">
                        <span class="wahrb-config-label"><?php esc_html_e('days', 'wahra-rentals-bookings'); ?></span>
                    </div>
                
                <?php elseif ($rule_key === 'early_bird'): ?>
                    <div class="wahrb-config-row">
                        <span class="wahrb-config-label"><?php esc_html_e('Booked at least', 'wahra-rentals-bookings'); ?></span>
                        <input type="number" name="quick_rules[<?php echo esc_attr($rule_key); ?>][threshold]" 
                               value="<?php echo esc_attr($current_threshold); ?>" 
                               min="1" max="365" class="wahrb-config-input">
                        <span class="wahrb-config-label"><?php esc_html_e('days in advance', 'wahra-rentals-bookings'); ?></span>
                    </div>
                
                <?php elseif ($rule_key === 'last_minute'): ?>
                    <div class="wahrb-config-row">
                        <span class="wahrb-config-label"><?php esc_html_e('Booked less than', 'wahra-rentals-bookings'); ?></span>
                        <input type="number" name="quick_rules[<?php echo esc_attr($rule_key); ?>][threshold]" 
                               value="<?php echo esc_attr($current_threshold); ?>" 
                               min="1" max="168" class="wahrb-config-input">
                        <span class="wahrb-config-label"><?php esc_html_e('hours before', 'wahra-rentals-bookings'); ?></span>
                    </div>
                <?php endif; ?>
                
                <div class="wahrb-visible-toggle">
                    <input type="checkbox" name="quick_rules[<?php echo esc_attr($rule_key); ?>][show_client]" 
                           value="1" <?php checked($show_client); ?> id="show_<?php echo esc_attr($rule_key); ?>">
                    <label for="show_<?php echo esc_attr($rule_key); ?>">
                        <?php esc_html_e('Show icon to customers', 'wahra-rentals-bookings'); ?>
                    </label>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Custom Rules -->
    <div class="wahrb-rules-section">
        <div class="wahrb-custom-rules-header">
            <div>
                <h3>🎨 <?php esc_html_e('Custom Rules', 'wahra-rentals-bookings'); ?></h3>
                <p class="desc"><?php esc_html_e('Create your own pricing rules', 'wahra-rentals-bookings'); ?></p>
            </div>
            <button type="button" class="wahrb-add-rule-btn" id="open-custom-rule-modal">
                + <?php esc_html_e('Add', 'wahra-rentals-bookings'); ?>
            </button>
        </div>

        <div id="custom-rules-list">
            <?php if (empty($custom_rules)): ?>
                <div class="wahrb-empty-rules" id="empty-rules-placeholder">
                    <div class="emoji">💡</div>
                    <p><?php esc_html_e('High season, group promo, holiday weekend surcharge...', 'wahra-rentals-bookings'); ?></p>
                </div>
            <?php else: ?>
                <?php foreach ($custom_rules as $idx => $rule): ?>
                    <div class="wahrb-custom-rule-card" data-index="<?php echo esc_attr($idx); ?>">
                        <span class="icon"><?php echo esc_html($rule['icon'] ?? '🏷️'); ?></span>
                        <div class="info">
                            <strong><?php echo esc_html($rule['name']); ?></strong>
                            <small><?php echo esc_html($rule['condition_label'] ?? ''); ?></small>
                        </div>
                        <span class="badge <?php echo esc_attr( ($rule['value'] >= 0) ? 'positive' : 'negative' ); ?>">
                            <?php echo ($rule['value'] >= 0 ? '+' : '') . esc_html($rule['value']); ?>%
                        </span>
                        <button type="button" class="wahrb-remove-btn" data-index="<?php echo esc_attr($idx); ?>">×</button>
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][name]" value="<?php echo esc_attr($rule['name']); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][icon]" value="<?php echo esc_attr($rule['icon'] ?? '🏷️'); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][value]" value="<?php echo esc_attr($rule['value']); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][type]" value="<?php echo esc_attr($rule['type'] ?? 'always'); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][conditions]" value="<?php echo esc_attr($rule['conditions'] ?? ''); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][condition_label]" value="<?php echo esc_attr($rule['condition_label'] ?? ''); ?>">
                        <input type="hidden" name="custom_rules[<?php echo esc_attr($idx); ?>][show_client]" value="<?php echo esc_attr($rule['show_client'] ?? '1'); ?>">
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Icon Picker Overlay -->
<div class="wahrb-icon-picker-overlay" id="icon-picker-overlay">
    <div class="wahrb-icon-picker-modal">
        <h4><?php esc_html_e('Choose an icon', 'wahra-rentals-bookings'); ?></h4>
        <div class="wahrb-icon-grid">
            <?php foreach ($available_icons as $icon => $label): ?>
                <button type="button" class="wahrb-icon-option" data-icon="<?php echo esc_attr($icon); ?>" title="<?php echo esc_attr($label); ?>">
                    <?php echo esc_html($icon); ?>
                </button>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Custom Rule Modal -->
<div class="wahrb-modal-overlay" id="custom-rule-modal">
    <div class="wahrb-modal" style="max-width: 500px;">
        <div class="wahrb-modal-header">
            <h4 id="modal-title"><?php esc_html_e('New Rule', 'wahra-rentals-bookings'); ?></h4>
            <button type="button" class="wahrb-modal-close" id="close-custom-modal">×</button>
        </div>
        <div class="wahrb-modal-body">
            <input type="hidden" id="edit-rule-index" value="-1">
            
            <div class="form-row">
                <div class="form-group">
                    <label><?php esc_html_e('Rule name', 'wahra-rentals-bookings'); ?> <span style="color: #dc2626;">*</span></label>
                    <input type="text" class="form-control" id="new-rule-name" 
                           placeholder="<?php esc_attr_e('Ex: High Season, Summer Promo...', 'wahra-rentals-bookings'); ?>"
                           maxlength="50" required>
                </div>
                <div class="form-group" style="flex: 0 0 80px;">
                    <label><?php esc_html_e('Icon', 'wahra-rentals-bookings'); ?></label>
                    <button type="button" class="wahrb-rule-icon-btn" id="new-rule-icon-btn" 
                            style="width: 100%; height: 48px; font-size: 24px;">🏷️</button>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label><?php esc_html_e('Adjustment (%)', 'wahra-rentals-bookings'); ?> <span style="color: #dc2626;">*</span></label>
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <input type="number" class="form-control wahrb-numeric-input" id="new-rule-value" 
                               placeholder="-10" step="1" min="-100" max="500" 
                               style="flex: 1;" required
                               oninput="this.value = this.value.replace(/[^-0-9]/g, '')">
                        <span style="font-weight: 600; font-size: 18px;">%</span>
                    </div>
                    <small style="color: #64748b; font-size: 11px;"><?php esc_html_e('Negative = discount, Positive = surcharge', 'wahra-rentals-bookings'); ?></small>
                </div>
                <div class="form-group">
                    <label><?php esc_html_e('Condition type', 'wahra-rentals-bookings'); ?></label>
                    <select class="form-control" id="new-rule-type">
                        <option value="always"><?php esc_html_e('Always apply', 'wahra-rentals-bookings'); ?></option>
                        <option value="date_range"><?php esc_html_e('Date range', 'wahra-rentals-bookings'); ?></option>
                        <option value="duration"><?php esc_html_e('Minimum duration', 'wahra-rentals-bookings'); ?></option>
                        <option value="weekday"><?php esc_html_e('Days of the week', 'wahra-rentals-bookings'); ?></option>
                    </select>
                </div>
            </div>
            
            <!-- Type: Date Range -->
            <div class="form-group condition-field" id="condition-date-range" style="display: none;">
                <label><?php esc_html_e('Period', 'wahra-rentals-bookings'); ?> <span style="color: #dc2626;">*</span></label>
                <div style="display: flex; gap: 10px; align-items: center;">
                    <input type="date" class="form-control" id="rule-date-start" style="flex: 1;">
                    <span style="font-weight: 500;"><?php esc_html_e('to', 'wahra-rentals-bookings'); ?></span>
                    <input type="date" class="form-control" id="rule-date-end" style="flex: 1;">
                </div>
            </div>
            
            <!-- Type: Duration -->
            <div class="form-group condition-field" id="condition-duration" style="display: none;">
                <label><?php esc_html_e('Minimum duration (days)', 'wahra-rentals-bookings'); ?> <span style="color: #dc2626;">*</span></label>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <input type="number" class="form-control wahrb-numeric-input" id="rule-duration-value" 
                           min="1" max="365" value="7" step="1"
                           oninput="this.value = Math.max(1, parseInt(this.value) || 1)"
                           style="width: 100px;">
                    <span style="color: #64748b;"><?php esc_html_e('days or more', 'wahra-rentals-bookings'); ?></span>
                </div>
            </div>
            
            <!-- Type: Weekday -->
            <div class="form-group condition-field" id="condition-weekday" style="display: none;">
                <label><?php esc_html_e('Applicable days', 'wahra-rentals-bookings'); ?> <span style="color: #dc2626;">*</span></label>
                <div class="wahrb-weekday-selector" style="display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px;">
                    <?php 
                    $weekdays = [
                        'sun' => __('Sun', 'wahra-rentals-bookings'),
                        'mon' => __('Mon', 'wahra-rentals-bookings'),
                        'tue' => __('Tue', 'wahra-rentals-bookings'),
                        'wed' => __('Wed', 'wahra-rentals-bookings'),
                        'thu' => __('Thu', 'wahra-rentals-bookings'),
                        'fri' => __('Fri', 'wahra-rentals-bookings'),
                        'sat' => __('Sat', 'wahra-rentals-bookings'),
                    ];
                    foreach ($weekdays as $key => $label): ?>
                        <label class="wahrb-weekday-chip" data-day="<?php echo esc_attr($key); ?>">
                            <input type="checkbox" class="rule-weekday-check" value="<?php echo esc_attr($key); ?>">
                            <span><?php echo esc_html($label); ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="form-group" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #e2e8f0;">
                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                    <input type="checkbox" id="new-rule-show-client" checked>
                    <span><?php esc_html_e('Show icon on product page', 'wahra-rentals-bookings'); ?></span>
                </label>
            </div>
        </div>
        <div class="wahrb-modal-footer" style="display: flex; justify-content: space-between; gap: 10px;">
            <button type="button" class="wahrb-btn-secondary" id="cancel-custom-rule"><?php esc_html_e('Cancel', 'wahra-rentals-bookings'); ?></button>
            <button type="button" class="wahrb-btn-primary" id="save-custom-rule"><?php esc_html_e('Save', 'wahra-rentals-bookings'); ?></button>
        </div>
    </div>
</div>

<?php
// Localize step 4 config for wahrb-wizard-steps.js
wp_localize_script('wahrb-wizard-steps', 'wahrbStep4Config', [
    'currencySymbol'   => html_entity_decode(get_woocommerce_currency_symbol()),
    'priceUnits'       => $price_units,
    'customRuleIndex'  => absint(count($custom_rules)),
    'dayNames'         => [
        'sun' => __('Sun', 'wahra-rentals-bookings'),
        'mon' => __('Mon', 'wahra-rentals-bookings'),
        'tue' => __('Tue', 'wahra-rentals-bookings'),
        'wed' => __('Wed', 'wahra-rentals-bookings'),
        'thu' => __('Thu', 'wahra-rentals-bookings'),
        'fri' => __('Fri', 'wahra-rentals-bookings'),
        'sat' => __('Sat', 'wahra-rentals-bookings'),
    ],
    'i18n' => [
        'fallbackUnit'    => __('day', 'wahra-rentals-bookings'),
        'days'            => __('days', 'wahra-rentals-bookings'),
        'newRule'         => __('New Rule', 'wahra-rentals-bookings'),
        'editRule'        => __('Edit Rule', 'wahra-rentals-bookings'),
        'enterRuleName'   => __('Please enter a rule name', 'wahra-rentals-bookings'),
        'enterValidPercent' => __('Please enter a valid percentage', 'wahra-rentals-bookings'),
        'percentRange'    => __('Percentage must be between -100% and +500%', 'wahra-rentals-bookings'),
        'selectDates'     => __('Please select start and end dates', 'wahra-rentals-bookings'),
        'dateOrder'       => __('Start date must be before end date', 'wahra-rentals-bookings'),
        'validDuration'   => __('Please enter a valid minimum duration', 'wahra-rentals-bookings'),
        'selectDay'       => __('Please select at least one day', 'wahra-rentals-bookings'),
        'deleteRule'      => __('Delete this rule?', 'wahra-rentals-bookings'),
        'emptyRules'      => __('High season, group promo, holiday weekend surcharge...', 'wahra-rentals-bookings'),
    ],
]);
// Step 4 JS is handled by wahrb-wizard-steps.js (enqueued in booking-wizard.php)
?>
