<?php if (!defined('ABSPATH')) exit; ?>
<?php
/**
 * Palace Properties — Admin Meta Box (Tabbed Interface)
 *
 * Registers and renders a modern, tabbed meta box for the palace-properties
 * custom post type. Provides full field editing with Lock Updates and
 * Hide Property toggles, organized across nine tabs.
 *
 * @package Integrate_Palace_Properties
 */

class IntegratePalaceP_Local_Fields {

    /**
     * Boot the class: hook into WordPress.
     */
    public static function init() {
        add_action('add_meta_boxes', [__CLASS__, 'register_meta_box']);
        add_action('save_post_palace-properties', [__CLASS__, 'save_meta'], 10, 2);
    }

    /**
     * Register the meta box on the palace-properties edit screen.
     */
    public static function register_meta_box() {
        add_meta_box(
            'ipp_property_fields',
            'Property Data',
            [__CLASS__, 'render_meta_box'],
            'palace-properties',
            'normal',
            'high'
        );
    }

    /* ------------------------------------------------------------------ */
    /*  RENDER                                                             */
    /* ------------------------------------------------------------------ */

    public static function render_meta_box($post) {
        wp_nonce_field('ipp_save_property_meta', 'ipp_property_meta_nonce');

        // Helper to get meta value
        $m = function ($key, $default = '') use ($post) {
            $val = get_post_meta($post->ID, $key, true);
            return $val !== '' && $val !== false ? $val : $default;
        };

        $lock = $m('ipp_lock_updates');
        $hide = $m('ipp_hide_property');

        // Tab definitions
        $tabs = [
            'information' => 'Information',
            'address'     => 'Address',
            'financial'   => 'Financial',
            'features'    => 'Features',
            'content'     => 'Content',
            'agent'       => 'Agent',
            'links'       => 'Links',
            'gallery'     => 'Gallery',
            'advanced'    => 'Advanced',
        ];
        ?>

        <!-- ==================== INLINE STYLES ==================== -->
        <style>
            /* Reset inside meta box */
            #ipp_property_fields .inside { padding: 0 !important; }

            .ipp-admin {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                color: #1e293b;
                line-height: 1.5;
            }

            /* ---------- Top Toggles ---------- */
            .ipp-admin__toggles {
                display: flex;
                flex-wrap: wrap;
                gap: 16px;
                padding: 20px 24px;
                background: #f8fafc;
                border-bottom: 1px solid #e2e8f0;
            }
            .ipp-admin__toggle-card {
                flex: 1 1 320px;
                display: flex;
                align-items: center;
                gap: 14px;
                padding: 16px 20px;
                border-radius: 10px;
                border: 1px solid #e2e8f0;
                background: #fff;
                transition: box-shadow .15s ease;
            }
            .ipp-admin__toggle-card:hover {
                box-shadow: 0 2px 8px rgba(0,0,0,.06);
            }
            .ipp-admin__toggle-card--lock {
                border-left: 4px solid #f59e0b;
            }
            .ipp-admin__toggle-card--hide {
                border-left: 4px solid #ef4444;
            }
            .ipp-admin__toggle-icon {
                width: 40px;
                height: 40px;
                border-radius: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
            }
            .ipp-admin__toggle-card--lock .ipp-admin__toggle-icon {
                background: #fffbeb;
                color: #d97706;
            }
            .ipp-admin__toggle-card--hide .ipp-admin__toggle-icon {
                background: #fef2f2;
                color: #dc2626;
            }
            .ipp-admin__toggle-icon svg { width: 20px; height: 20px; }
            .ipp-admin__toggle-text {
                flex: 1;
            }
            .ipp-admin__toggle-label {
                font-weight: 600;
                font-size: 14px;
                color: #1e293b;
                display: block;
                margin-bottom: 2px;
            }
            .ipp-admin__toggle-desc {
                font-size: 12px;
                color: #64748b;
            }

            /* CSS Toggle Switch */
            .ipp-switch {
                position: relative;
                width: 48px;
                height: 26px;
                flex-shrink: 0;
            }
            .ipp-switch input {
                opacity: 0;
                width: 0;
                height: 0;
                position: absolute;
            }
            .ipp-switch__slider {
                position: absolute;
                cursor: pointer;
                inset: 0;
                background: #cbd5e1;
                border-radius: 26px;
                transition: background .2s ease;
            }
            .ipp-switch__slider::before {
                content: '';
                position: absolute;
                height: 20px;
                width: 20px;
                left: 3px;
                bottom: 3px;
                background: #fff;
                border-radius: 50%;
                transition: transform .2s ease;
                box-shadow: 0 1px 3px rgba(0,0,0,.15);
            }
            .ipp-switch input:checked + .ipp-switch__slider {
                background: #f59e0b;
            }
            .ipp-switch--danger input:checked + .ipp-switch__slider {
                background: #ef4444;
            }
            .ipp-switch--green input:checked + .ipp-switch__slider {
                background: #22c55e;
            }
            .ipp-switch input:checked + .ipp-switch__slider::before {
                transform: translateX(22px);
            }
            .ipp-switch input:focus-visible + .ipp-switch__slider {
                box-shadow: 0 0 0 3px rgba(59,130,246,.4);
            }

            /* ---------- Tab Bar ---------- */
            .ipp-admin__tabs {
                display: flex;
                flex-wrap: wrap;
                gap: 0;
                padding: 0 24px;
                background: #fff;
                border-bottom: 2px solid #e2e8f0;
            }
            .ipp-admin__tab {
                padding: 12px 18px;
                font-size: 13px;
                font-weight: 600;
                color: #64748b;
                background: none;
                border: none;
                border-bottom: 2px solid transparent;
                margin-bottom: -2px;
                cursor: pointer;
                transition: all .15s ease;
                white-space: nowrap;
            }
            .ipp-admin__tab:hover {
                color: #1e293b;
                background: #f8fafc;
            }
            .ipp-admin__tab.is-active {
                color: #2563eb;
                border-bottom-color: #2563eb;
            }

            /* ---------- Tab Panels ---------- */
            .ipp-admin__panel {
                display: none;
                padding: 24px;
            }
            .ipp-admin__panel.is-active {
                display: block;
            }

            /* ---------- Field Grid ---------- */
            .ipp-admin__fields {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 18px 24px;
            }
            .ipp-admin__field {
                display: flex;
                flex-direction: column;
                gap: 6px;
            }
            .ipp-admin__field--full {
                grid-column: 1 / -1;
            }
            .ipp-admin__field label {
                font-size: 12px;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: .04em;
                color: #64748b;
            }
            .ipp-admin__field input[type="text"],
            .ipp-admin__field input[type="number"],
            .ipp-admin__field input[type="url"],
            .ipp-admin__field input[type="email"],
            .ipp-admin__field input[type="date"],
            .ipp-admin__field select,
            .ipp-admin__field textarea {
                width: 100%;
                padding: 9px 12px;
                border: 1px solid #d1d5db;
                border-radius: 8px;
                font-size: 14px;
                font-family: inherit;
                color: #1e293b;
                background: #fff;
                transition: border-color .15s ease, box-shadow .15s ease;
                box-sizing: border-box;
            }
            .ipp-admin__field input:focus,
            .ipp-admin__field select:focus,
            .ipp-admin__field textarea:focus {
                outline: none;
                border-color: #2563eb;
                box-shadow: 0 0 0 3px rgba(37,99,235,.12);
            }
            .ipp-admin__field input[readonly],
            .ipp-admin__field textarea[readonly] {
                background: #f1f5f9;
                color: #64748b;
                cursor: not-allowed;
            }
            .ipp-admin__field textarea {
                min-height: 120px;
                resize: vertical;
            }
            .ipp-admin__field textarea.ipp-admin__textarea--large {
                min-height: 220px;
            }
            .ipp-admin__field textarea.ipp-admin__textarea--raw {
                min-height: 300px;
                font-family: "SF Mono", "Fira Code", "Fira Mono", "Roboto Mono", monospace;
                font-size: 12px;
                line-height: 1.6;
                white-space: pre;
                overflow-x: auto;
            }

            /* Dropdown arrow */
            .ipp-admin__field select {
                appearance: none;
                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath d='M3 5l3 3 3-3' stroke='%2364748b' stroke-width='1.5' fill='none'/%3E%3C/svg%3E");
                background-repeat: no-repeat;
                background-position: right 12px center;
                padding-right: 36px;
            }

            /* Toggle inside feature fields */
            .ipp-admin__field .ipp-switch {
                margin-top: 4px;
            }

            /* ---------- Gallery ---------- */
            .ipp-admin__gallery-info {
                padding: 16px 20px;
                background: #f0f9ff;
                border: 1px solid #bae6fd;
                border-radius: 8px;
                color: #0369a1;
                font-size: 13px;
                line-height: 1.6;
                margin-bottom: 16px;
            }
            .ipp-admin__gallery-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
                gap: 12px;
            }
            .ipp-admin__gallery-item {
                border-radius: 8px;
                overflow: hidden;
                border: 1px solid #e2e8f0;
                background: #f8fafc;
            }
            .ipp-admin__gallery-item img {
                width: 100%;
                height: 100px;
                object-fit: cover;
                display: block;
            }

            /* ---------- Section Heading inside panel ---------- */
            .ipp-admin__section-title {
                font-size: 11px;
                font-weight: 700;
                text-transform: uppercase;
                letter-spacing: .08em;
                color: #94a3b8;
                margin: 24px 0 12px;
                padding-bottom: 8px;
                border-bottom: 1px solid #e2e8f0;
                grid-column: 1 / -1;
            }
            .ipp-admin__section-title:first-child {
                margin-top: 0;
            }

            /* Responsive */
            @media (max-width: 782px) {
                .ipp-admin__fields {
                    grid-template-columns: 1fr;
                }
                .ipp-admin__tabs {
                    padding: 0 12px;
                }
                .ipp-admin__tab {
                    padding: 10px 12px;
                    font-size: 12px;
                }
                .ipp-admin__panel {
                    padding: 16px;
                }
                .ipp-admin__toggles {
                    padding: 16px;
                }
            }
        </style>

        <div class="ipp-admin">

            <!-- ==================== TOP TOGGLES ==================== -->
            <div class="ipp-admin__toggles">
                <!-- Lock Updates -->
                <div class="ipp-admin__toggle-card ipp-admin__toggle-card--lock">
                    <div class="ipp-admin__toggle-icon">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                    </div>
                    <div class="ipp-admin__toggle-text">
                        <span class="ipp-admin__toggle-label">Lock Updates</span>
                        <span class="ipp-admin__toggle-desc">Prevent webhook from overwriting this property's data</span>
                    </div>
                    <label class="ipp-switch">
                        <input type="checkbox" name="ipp_lock_updates" value="1" <?php checked($lock, '1'); ?>>
                        <span class="ipp-switch__slider"></span>
                    </label>
                </div>

                <!-- Hide Property -->
                <div class="ipp-admin__toggle-card ipp-admin__toggle-card--hide">
                    <div class="ipp-admin__toggle-icon">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>
                    </div>
                    <div class="ipp-admin__toggle-text">
                        <span class="ipp-admin__toggle-label">Hide Property</span>
                        <span class="ipp-admin__toggle-desc">Exclude from frontend listings</span>
                    </div>
                    <label class="ipp-switch ipp-switch--danger">
                        <input type="checkbox" name="ipp_hide_property" value="1" <?php checked($hide, '1'); ?>>
                        <span class="ipp-switch__slider"></span>
                    </label>
                </div>
            </div>

            <!-- ==================== TAB BAR ==================== -->
            <div class="ipp-admin__tabs" role="tablist">
                <?php $first = true; foreach ($tabs as $key => $label) : ?>
                    <button type="button"
                            class="ipp-admin__tab<?php echo $first ? ' is-active' : ''; ?>"
                            role="tab"
                            aria-controls="ipp-panel-<?php echo esc_attr($key); ?>"
                            data-tab="<?php echo esc_attr($key); ?>"
                    ><?php echo esc_html($label); ?></button>
                <?php $first = false; endforeach; ?>
            </div>

            <!-- ==================== TAB PANELS ==================== -->

            <!-- TAB: Information -->
            <div id="ipp-panel-information" class="ipp-admin__panel is-active" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_property_code">Property Code</label>
                        <input type="text" id="ipp_property_code" name="ipp_property_code" value="<?php echo esc_attr($m('ipp_property_code')); ?>" readonly>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_property_code_global">Global Code</label>
                        <input type="text" id="ipp_property_code_global" name="ipp_property_code_global" value="<?php echo esc_attr($m('ipp_property_code_global')); ?>" readonly>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_our_code">Our Code</label>
                        <input type="text" id="ipp_our_code" name="ipp_our_code" value="<?php echo esc_attr($m('ipp_our_code')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_sort_code">Sort Code</label>
                        <input type="text" id="ipp_sort_code" name="ipp_sort_code" value="<?php echo esc_attr($m('ipp_sort_code')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_status">Status</label>
                        <select id="ipp_status" name="ipp_status">
                            <?php
                            $statuses = ['Active', 'Inactive', 'Archived', 'Draft', 'Pending'];
                            $current_status = $m('ipp_status');
                            if ($current_status && !in_array($current_status, $statuses)) {
                                array_unshift($statuses, $current_status);
                            }
                            foreach ($statuses as $s) : ?>
                                <option value="<?php echo esc_attr($s); ?>" <?php selected($current_status, $s); ?>><?php echo esc_html($s); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_management_type">Management Type</label>
                        <input type="text" id="ipp_management_type" name="ipp_management_type" value="<?php echo esc_attr($m('ipp_management_type')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_class">Property Class</label>
                        <input type="text" id="ipp_class" name="ipp_class" value="<?php echo esc_attr($m('ipp_class')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_grid">Grid</label>
                        <input type="text" id="ipp_grid" name="ipp_grid" value="<?php echo esc_attr($m('ipp_grid')); ?>">
                    </div>
                </div>
            </div>

            <!-- TAB: Address -->
            <div id="ipp-panel-address" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_address1">Address 1 (Unit/Number)</label>
                        <input type="text" id="ipp_address1" name="ipp_address1" value="<?php echo esc_attr($m('ipp_address1')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_address2">Address 2 (Street)</label>
                        <input type="text" id="ipp_address2" name="ipp_address2" value="<?php echo esc_attr($m('ipp_address2')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_address3">Address 3 (City/Suburb)</label>
                        <input type="text" id="ipp_address3" name="ipp_address3" value="<?php echo esc_attr($m('ipp_address3')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_address4">Address 4 (Region)</label>
                        <input type="text" id="ipp_address4" name="ipp_address4" value="<?php echo esc_attr($m('ipp_address4')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_unit">Unit</label>
                        <input type="text" id="ipp_unit" name="ipp_unit" value="<?php echo esc_attr($m('ipp_unit')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_postcode">Postcode</label>
                        <input type="text" id="ipp_postcode" name="ipp_postcode" value="<?php echo esc_attr($m('ipp_postcode')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_suburb">Suburb</label>
                        <input type="text" id="ipp_suburb" name="ipp_suburb" value="<?php echo esc_attr($m('ipp_suburb')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_region">Region</label>
                        <input type="text" id="ipp_region" name="ipp_region" value="<?php echo esc_attr($m('ipp_region')); ?>">
                    </div>
                </div>
            </div>

            <!-- TAB: Financial -->
            <div id="ipp-panel-financial" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_rent_amount">Rent Amount</label>
                        <input type="number" id="ipp_rent_amount" name="ipp_rent_amount" value="<?php echo esc_attr($m('ipp_rent_amount')); ?>" step="0.01" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_rental_period">Rental Period</label>
                        <select id="ipp_rental_period" name="ipp_rental_period">
                            <?php
                            $periods = ['Week', 'Fortnight', 'Month', 'Year'];
                            $current_period = $m('ipp_rental_period');
                            if ($current_period && !in_array($current_period, $periods)) {
                                array_unshift($periods, $current_period);
                            }
                            foreach ($periods as $p) : ?>
                                <option value="<?php echo esc_attr($p); ?>" <?php selected($current_period, $p); ?>><?php echo esc_html($p); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_date_available">Date Available</label>
                        <input type="date" id="ipp_date_available" name="ipp_date_available" value="<?php echo esc_attr($m('ipp_date_available')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_market_value">Market Value</label>
                        <input type="number" id="ipp_market_value" name="ipp_market_value" value="<?php echo esc_attr($m('ipp_market_value')); ?>" step="0.01" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_commission_percent">Commission %</label>
                        <input type="number" id="ipp_commission_percent" name="ipp_commission_percent" value="<?php echo esc_attr($m('ipp_commission_percent')); ?>" step="0.01" min="0" max="100">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_maintenance_fee_percent">Maintenance Fee %</label>
                        <input type="number" id="ipp_maintenance_fee_percent" name="ipp_maintenance_fee_percent" value="<?php echo esc_attr($m('ipp_maintenance_fee_percent')); ?>" step="0.01" min="0" max="100">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_keepback_amount">Keepback Amount</label>
                        <input type="number" id="ipp_keepback_amount" name="ipp_keepback_amount" value="<?php echo esc_attr($m('ipp_keepback_amount')); ?>" step="0.01" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_keepback_reason">Keepback Reason</label>
                        <input type="text" id="ipp_keepback_reason" name="ipp_keepback_reason" value="<?php echo esc_attr($m('ipp_keepback_reason')); ?>">
                    </div>
                </div>
            </div>

            <!-- TAB: Features -->
            <div id="ipp-panel-features" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_bedrooms">Bedrooms</label>
                        <input type="number" id="ipp_bedrooms" name="ipp_bedrooms" value="<?php echo esc_attr($m('ipp_bedrooms')); ?>" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_bathrooms">Bathrooms</label>
                        <input type="number" id="ipp_bathrooms" name="ipp_bathrooms" value="<?php echo esc_attr($m('ipp_bathrooms')); ?>" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_ensuites">Ensuites</label>
                        <input type="number" id="ipp_ensuites" name="ipp_ensuites" value="<?php echo esc_attr($m('ipp_ensuites')); ?>" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_cars">Cars</label>
                        <input type="number" id="ipp_cars" name="ipp_cars" value="<?php echo esc_attr($m('ipp_cars')); ?>" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_parking">Parking</label>
                        <input type="text" id="ipp_parking" name="ipp_parking" value="<?php echo esc_attr($m('ipp_parking')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_year_built">Year Built</label>
                        <input type="number" id="ipp_year_built" name="ipp_year_built" value="<?php echo esc_attr($m('ipp_year_built')); ?>" min="1800" max="2100">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_stories">Stories</label>
                        <input type="number" id="ipp_stories" name="ipp_stories" value="<?php echo esc_attr($m('ipp_stories')); ?>" min="0">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_floor_area">Floor Area</label>
                        <input type="text" id="ipp_floor_area" name="ipp_floor_area" value="<?php echo esc_attr($m('ipp_floor_area')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_land_area_sqm">Land Area (m&sup2;)</label>
                        <input type="text" id="ipp_land_area_sqm" name="ipp_land_area_sqm" value="<?php echo esc_attr($m('ipp_land_area_sqm')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_land_area_hectares">Land Area (hectares)</label>
                        <input type="text" id="ipp_land_area_hectares" name="ipp_land_area_hectares" value="<?php echo esc_attr($m('ipp_land_area_hectares')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_furnishings">Furnishings</label>
                        <input type="text" id="ipp_furnishings" name="ipp_furnishings" value="<?php echo esc_attr($m('ipp_furnishings')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_new_construction">New Construction</label>
                        <select id="ipp_new_construction" name="ipp_new_construction">
                            <option value="">--</option>
                            <option value="Yes" <?php selected($m('ipp_new_construction'), 'Yes'); ?>>Yes</option>
                            <option value="No" <?php selected($m('ipp_new_construction'), 'No'); ?>>No</option>
                        </select>
                    </div>
                    <div class="ipp-admin__field">
                        <label>Pets Allowed</label>
                        <label class="ipp-switch ipp-switch--green">
                            <input type="checkbox" name="ipp_pets_allowed" value="1" <?php checked($m('ipp_pets_allowed'), '1'); ?>>
                            <span class="ipp-switch__slider"></span>
                        </label>
                    </div>
                    <div class="ipp-admin__field">
                        <label>Smokers Allowed</label>
                        <label class="ipp-switch ipp-switch--green">
                            <input type="checkbox" name="ipp_smokers_allowed" value="1" <?php checked($m('ipp_smokers_allowed'), '1'); ?>>
                            <span class="ipp-switch__slider"></span>
                        </label>
                    </div>
                </div>
            </div>

            <!-- TAB: Content -->
            <div id="ipp-panel-content" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_advert_text">Advert Text</label>
                        <textarea id="ipp_advert_text" name="ipp_advert_text" class="ipp-admin__textarea--large"><?php echo esc_textarea($m('ipp_advert_text')); ?></textarea>
                    </div>
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_header">Header</label>
                        <input type="text" id="ipp_header" name="ipp_header" value="<?php echo esc_attr($m('ipp_header')); ?>">
                    </div>
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_feature_details">Feature Details</label>
                        <textarea id="ipp_feature_details" name="ipp_feature_details"><?php echo esc_textarea($m('ipp_feature_details')); ?></textarea>
                    </div>
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_amenities">Amenities</label>
                        <textarea id="ipp_amenities" name="ipp_amenities"><?php echo esc_textarea($m('ipp_amenities')); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- TAB: Agent -->
            <div id="ipp-panel-agent" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_code">Agent Code</label>
                        <input type="text" id="ipp_agent_code" name="ipp_agent_code" value="<?php echo esc_attr($m('ipp_agent_code')); ?>" readonly>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_full_name">Full Name</label>
                        <input type="text" id="ipp_agent_full_name" name="ipp_agent_full_name" value="<?php echo esc_attr($m('ipp_agent_full_name')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_title">Title</label>
                        <input type="text" id="ipp_agent_title" name="ipp_agent_title" value="<?php echo esc_attr($m('ipp_agent_title')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_email1">Email 1</label>
                        <input type="email" id="ipp_agent_email1" name="ipp_agent_email1" value="<?php echo esc_attr($m('ipp_agent_email1')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_email2">Email 2</label>
                        <input type="email" id="ipp_agent_email2" name="ipp_agent_email2" value="<?php echo esc_attr($m('ipp_agent_email2')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_phone_mobile">Phone Mobile</label>
                        <input type="text" id="ipp_agent_phone_mobile" name="ipp_agent_phone_mobile" value="<?php echo esc_attr($m('ipp_agent_phone_mobile')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_phone_work">Phone Work</label>
                        <input type="text" id="ipp_agent_phone_work" name="ipp_agent_phone_work" value="<?php echo esc_attr($m('ipp_agent_phone_work')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_agent_fax">Fax</label>
                        <input type="text" id="ipp_agent_fax" name="ipp_agent_fax" value="<?php echo esc_attr($m('ipp_agent_fax')); ?>">
                    </div>
                </div>
            </div>

            <!-- TAB: Links -->
            <div id="ipp-panel-links" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_virtual_tour_url">Virtual Tour URL</label>
                        <input type="url" id="ipp_virtual_tour_url" name="ipp_virtual_tour_url" value="<?php echo esc_attr($m('ipp_virtual_tour_url')); ?>">
                    </div>
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_web_link_url">Web Link URL</label>
                        <input type="url" id="ipp_web_link_url" name="ipp_web_link_url" value="<?php echo esc_attr($m('ipp_web_link_url')); ?>">
                    </div>
                    <div class="ipp-admin__field ipp-admin__field--full">
                        <label for="ipp_geographic_location">Geographic Location (lat:lng)</label>
                        <input type="text" id="ipp_geographic_location" name="ipp_geographic_location" value="<?php echo esc_attr($m('ipp_geographic_location')); ?>" placeholder="-35.2813540:174.0579896">
                    </div>
                    <?php
                    $geo = $m('ipp_geographic_location');
                    if ($geo && strpos($geo, ':') !== false) :
                        $parts = explode(':', $geo);
                        $lat = floatval($parts[0]);
                        $lng = floatval($parts[1]);
                        if ($lat && $lng) : ?>
                            <div class="ipp-admin__field ipp-admin__field--full">
                                <label>Map Preview</label>
                                <iframe
                                    src="https://maps.google.com/maps?q=<?php echo esc_attr($lat); ?>,<?php echo esc_attr($lng); ?>&z=15&output=embed"
                                    width="100%" height="250" style="border:none; border-radius:8px;" loading="lazy"
                                ></iframe>
                            </div>
                        <?php endif;
                    endif; ?>
                </div>
            </div>

            <!-- TAB: Gallery -->
            <div id="ipp-panel-gallery" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__gallery-info">
                    Gallery images are managed through the WordPress Media Library. Use the buttons below to add, remove, or reorder property images. Changes are saved when you update the post.
                </div>
                <?php
                // Render gallery field — hook into existing gallery functionality
                if (function_exists('integrate_palace_gallery')) {
                    integrate_palace_gallery($post);
                } else {
                    // Fallback: show current gallery images
                    $gallery_ids = get_post_meta($post->ID, 'ipp_gallery', true);
                    if (!is_array($gallery_ids)) {
                        // Try legacy key
                        $gallery_ids = get_post_meta($post->ID, 'integrate_palace_gallery', true);
                    }
                    if (!is_array($gallery_ids)) {
                        $gallery_ids = $gallery_ids ? explode(',', $gallery_ids) : [];
                    }
                    if (!empty($gallery_ids)) : ?>
                        <div class="ipp-admin__gallery-grid">
                            <?php foreach ($gallery_ids as $img_id) :
                                $thumb = wp_get_attachment_image_url(intval($img_id), 'thumbnail');
                                if ($thumb) : ?>
                                    <div class="ipp-admin__gallery-item">
                                        <img src="<?php echo esc_url($thumb); ?>" alt="">
                                    </div>
                                <?php endif;
                            endforeach; ?>
                        </div>
                    <?php else : ?>
                        <p style="color:#94a3b8;font-size:14px;">No gallery images found for this property.</p>
                    <?php endif;
                }
                ?>
            </div>

            <!-- TAB: Advanced -->
            <div id="ipp-panel-advanced" class="ipp-admin__panel" role="tabpanel">
                <div class="ipp-admin__fields">
                    <div class="ipp-admin__field">
                        <label for="ipp_owner_code">Owner Code</label>
                        <input type="text" id="ipp_owner_code" name="ipp_owner_code" value="<?php echo esc_attr($m('ipp_owner_code')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_la_account_no">LA Account No</label>
                        <input type="text" id="ipp_la_account_no" name="ipp_la_account_no" value="<?php echo esc_attr($m('ipp_la_account_no')); ?>">
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_change_code">Change Code</label>
                        <input type="text" id="ipp_change_code" name="ipp_change_code" value="<?php echo esc_attr($m('ipp_change_code')); ?>" readonly>
                    </div>
                    <div class="ipp-admin__field">
                        <label for="ipp_archived">Archived</label>
                        <select id="ipp_archived" name="ipp_archived">
                            <option value="">No</option>
                            <option value="1" <?php selected($m('ipp_archived'), '1'); ?>>Yes</option>
                        </select>
                    </div>

                    <!-- Custom Fields -->
                    <?php
                    $custom_raw = $m('ipp_custom_fields');
                    $custom_fields = [];
                    if ($custom_raw) {
                        if (is_string($custom_raw)) {
                            $custom_fields = json_decode($custom_raw, true);
                            if (!is_array($custom_fields)) {
                                $custom_fields = maybe_unserialize($custom_raw);
                            }
                            if (!is_array($custom_fields)) {
                                $custom_fields = [];
                            }
                        } elseif (is_array($custom_raw)) {
                            $custom_fields = $custom_raw;
                        }
                    }
                    if (!empty($custom_fields)) : ?>
                        <div class="ipp-admin__section-title">Custom Fields</div>
                        <?php foreach ($custom_fields as $cf_key => $cf_val) : ?>
                            <div class="ipp-admin__field">
                                <label><?php echo esc_html($cf_key); ?></label>
                                <input type="hidden" name="ipp_custom_field_keys[]" value="<?php echo esc_attr($cf_key); ?>">
                                <input type="text" name="ipp_custom_field_vals[]" value="<?php echo esc_attr(is_array($cf_val) ? wp_json_encode($cf_val) : $cf_val); ?>">
                            </div>
                        <?php endforeach;
                    endif; ?>

                    <!-- Raw Data -->
                    <div class="ipp-admin__field ipp-admin__field--full" style="margin-top:16px;">
                        <label for="ipp_raw_data">Raw JSON Data</label>
                        <?php
                        $raw = $m('ipp_raw_data');
                        if (is_array($raw)) {
                            $raw = wp_json_encode($raw, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                        } elseif (is_string($raw) && $raw) {
                            $decoded = json_decode($raw);
                            if ($decoded !== null) {
                                $raw = wp_json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
                            }
                        }
                        ?>
                        <textarea id="ipp_raw_data" class="ipp-admin__textarea--raw" readonly><?php echo esc_textarea($raw); ?></textarea>
                    </div>
                </div>
            </div>

        </div><!-- /.ipp-admin -->

        <!-- ==================== INLINE JS: Tab Switching ==================== -->
        <script>
        (function() {
            var tabs   = document.querySelectorAll('.ipp-admin__tab');
            var panels = document.querySelectorAll('.ipp-admin__panel');

            tabs.forEach(function(tab) {
                tab.addEventListener('click', function(e) {
                    e.preventDefault();
                    var target = this.getAttribute('data-tab');

                    tabs.forEach(function(t) { t.classList.remove('is-active'); });
                    panels.forEach(function(p) { p.classList.remove('is-active'); });

                    this.classList.add('is-active');
                    var panel = document.getElementById('ipp-panel-' + target);
                    if (panel) panel.classList.add('is-active');
                });
            });
        })();
        </script>

        <?php
    }

    /* ------------------------------------------------------------------ */
    /*  SAVE                                                               */
    /* ------------------------------------------------------------------ */

    public static function save_meta($post_id, $post) {
        // Verify nonce
        if (!isset($_POST['ipp_property_meta_nonce']) ||
            !wp_verify_nonce($_POST['ipp_property_meta_nonce'], 'ipp_save_property_meta')) {
            return;
        }

        // Skip autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // ---- Text fields ----
        $text_fields = [
            'ipp_property_code',
            'ipp_property_code_global',
            'ipp_our_code',
            'ipp_sort_code',
            'ipp_status',
            'ipp_management_type',
            'ipp_class',
            'ipp_grid',
            'ipp_address1',
            'ipp_address2',
            'ipp_address3',
            'ipp_address4',
            'ipp_unit',
            'ipp_postcode',
            'ipp_suburb',
            'ipp_region',
            'ipp_rental_period',
            'ipp_date_available',
            'ipp_parking',
            'ipp_furnishings',
            'ipp_new_construction',
            'ipp_header',
            'ipp_agent_code',
            'ipp_agent_full_name',
            'ipp_agent_title',
            'ipp_agent_phone_mobile',
            'ipp_agent_phone_work',
            'ipp_agent_fax',
            'ipp_geographic_location',
            'ipp_owner_code',
            'ipp_la_account_no',
            'ipp_change_code',
            'ipp_keepback_reason',
        ];

        foreach ($text_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, sanitize_text_field(wp_unslash($_POST[$key])));
            }
        }

        // ---- Email fields ----
        $email_fields = ['ipp_agent_email1', 'ipp_agent_email2'];
        foreach ($email_fields as $key) {
            if (isset($_POST[$key])) {
                $email = sanitize_email(wp_unslash($_POST[$key]));
                update_post_meta($post_id, $key, $email);
            }
        }

        // ---- URL fields ----
        $url_fields = ['ipp_virtual_tour_url', 'ipp_web_link_url'];
        foreach ($url_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, esc_url_raw(wp_unslash($_POST[$key])));
            }
        }

        // ---- Numeric (float) fields ----
        $float_fields = [
            'ipp_rent_amount',
            'ipp_market_value',
            'ipp_commission_percent',
            'ipp_maintenance_fee_percent',
            'ipp_keepback_amount',
        ];
        foreach ($float_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, floatval($_POST[$key]));
            }
        }

        // ---- Integer fields ----
        $int_fields = [
            'ipp_bedrooms',
            'ipp_bathrooms',
            'ipp_ensuites',
            'ipp_cars',
            'ipp_year_built',
            'ipp_stories',
        ];
        foreach ($int_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, absint($_POST[$key]));
            }
        }

        // ---- Text/numeric flex fields ----
        $flex_fields = ['ipp_floor_area', 'ipp_land_area_sqm', 'ipp_land_area_hectares'];
        foreach ($flex_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, sanitize_text_field(wp_unslash($_POST[$key])));
            }
        }

        // ---- Textarea fields ----
        $textarea_fields = [
            'ipp_advert_text',
            'ipp_feature_details',
            'ipp_amenities',
        ];
        foreach ($textarea_fields as $key) {
            if (isset($_POST[$key])) {
                update_post_meta($post_id, $key, sanitize_textarea_field(wp_unslash($_POST[$key])));
            }
        }

        // ---- Toggle/checkbox fields ----
        $toggle_fields = ['ipp_lock_updates', 'ipp_hide_property', 'ipp_pets_allowed', 'ipp_smokers_allowed'];
        foreach ($toggle_fields as $key) {
            $val = isset($_POST[$key]) ? '1' : '0';
            update_post_meta($post_id, $key, $val);
        }

        // ---- Archived ----
        if (isset($_POST['ipp_archived'])) {
            update_post_meta($post_id, 'ipp_archived', sanitize_text_field($_POST['ipp_archived']));
        }

        // ---- Custom Fields ----
        if (!empty($_POST['ipp_custom_field_keys']) && !empty($_POST['ipp_custom_field_vals'])) {
            $keys = array_map('sanitize_text_field', wp_unslash($_POST['ipp_custom_field_keys']));
            $vals = array_map('sanitize_text_field', wp_unslash($_POST['ipp_custom_field_vals']));
            $custom = [];
            foreach ($keys as $i => $k) {
                if ($k !== '' && isset($vals[$i])) {
                    $custom[$k] = $vals[$i];
                }
            }
            update_post_meta($post_id, 'ipp_custom_fields', wp_json_encode($custom));
        }
    }
}

// Initialize
IntegratePalaceP_Local_Fields::init();
