<?php
/**
 * FRESH Manager — שירותים (Services) Admin Page
 */
defined( 'ABSPATH' ) || exit;

/* ---------- SAVE HANDLER ---------- */
function freshm_save_services_handler() {
    if ( ! isset( $_POST['freshm_save_services'] ) || ! current_user_can( 'manage_options' ) ) return;
    check_admin_referer( 'freshm_services_action', 'freshm_services_nonce' );

    // Save categories
    $raw_cats = isset( $_POST['freshm_svc_cats'] ) ? $_POST['freshm_svc_cats'] : array();
    $cats = array();
    foreach ( $raw_cats as $c ) {
        if ( empty( $c['name'] ) ) continue;
        $cats[] = array(
            'name'  => sanitize_text_field( $c['name'] ),
            'slug'  => sanitize_title( $c['slug'] ?: $c['name'] ),
            'order' => intval( $c['order'] ?? 0 ),
        );
    }
    usort( $cats, function( $a, $b ) { return $a['order'] - $b['order']; } );
    update_option( 'freshm_service_categories', $cats );

    // Save services
    $raw = isset( $_POST['freshm_svcs'] ) ? $_POST['freshm_svcs'] : array();
    $services = array();
    foreach ( $raw as $item ) {
        if ( empty( $item['name'] ) ) continue;
        $sv = array(
            'name'      => sanitize_text_field( $item['name'] ),
            'slug'      => sanitize_title( $item['slug'] ?: $item['name'] ),
            'category'  => sanitize_text_field( $item['category'] ?? '' ),
            'icon'      => sanitize_text_field( $item['icon'] ?? '' ),
            'custom_icon' => esc_url_raw( $item['custom_icon'] ?? '' ),
            'excerpt'   => sanitize_textarea_field( $item['excerpt'] ?? '' ),
            'color'     => sanitize_hex_color( $item['color'] ?? '#c9a84c' ) ?: '#c9a84c',
            'order'     => intval( $item['order'] ?? 0 ),
            'status'    => ( $item['status'] ?? 'publish' ) === 'draft' ? 'draft' : 'publish',
            'hero_image' => esc_url_raw( $item['hero_image'] ?? '' ),
            'content'    => wp_kses_post( $item['content'] ?? '' ),
            'video_url'  => esc_url_raw( $item['video_url'] ?? '' ),
            'cta_title'  => sanitize_text_field( $item['cta_title'] ?? '' ),
            'cta_text'   => sanitize_text_field( $item['cta_text'] ?? '' ),
            'cta_btn'    => sanitize_text_field( $item['cta_btn'] ?? '' ),
            'closing_text' => sanitize_textarea_field( $item['closing_text'] ?? '' ),
            'benefits'   => array(),
            'process'    => array(),
            'metrics'    => array(),
            'gallery'    => array(),
        );

        // Benefits
        if ( ! empty( $item['benefits'] ) && is_array( $item['benefits'] ) ) {
            foreach ( $item['benefits'] as $b ) {
                if ( empty( $b['title'] ) ) continue;
                $sv['benefits'][] = array(
                    'icon'  => sanitize_text_field( $b['icon'] ?? '' ),
                    'title' => sanitize_text_field( $b['title'] ),
                    'desc'  => sanitize_textarea_field( $b['desc'] ?? '' ),
                );
            }
        }

        // Process steps
        if ( ! empty( $item['process'] ) && is_array( $item['process'] ) ) {
            foreach ( $item['process'] as $p ) {
                if ( empty( $p['title'] ) ) continue;
                $sv['process'][] = array(
                    'number' => sanitize_text_field( $p['number'] ?? '' ),
                    'title'  => sanitize_text_field( $p['title'] ),
                    'desc'   => sanitize_textarea_field( $p['desc'] ?? '' ),
                );
            }
        }

        // Gallery
        if ( ! empty( $item['gallery'] ) && is_array( $item['gallery'] ) ) {
            foreach ( $item['gallery'] as $url ) {
                $url = esc_url_raw( $url );
                if ( $url ) $sv['gallery'][] = $url;
            }
        }

        // FAQs
        $sv['faqs'] = array();
        if ( ! empty( $item['faqs'] ) && is_array( $item['faqs'] ) ) {
            foreach ( $item['faqs'] as $f ) {
                if ( empty( $f['q'] ) ) continue;
                $sv['faqs'][] = array(
                    'q' => sanitize_text_field( $f['q'] ),
                    'a' => sanitize_textarea_field( $f['a'] ?? '' ),
                );
            }
        }

        $services[] = $sv;
    }

    usort( $services, function( $a, $b ) { return $a['order'] - $b['order']; } );
    update_option( 'freshm_services_data', $services );

    // Sync categories to taxonomy
    freshm_sync_service_cats( $cats );

    // Sync services to CPT
    freshm_sync_services_to_cpt( $services );

    $args = array( 'freshm_saved' => '1' );
    if ( ! empty( $_POST['freshm_tab'] ) ) {
        $args['tab'] = sanitize_key( $_POST['freshm_tab'] );
    }
    wp_safe_redirect( add_query_arg( $args ) );
    exit;
}
add_action( 'admin_init', 'freshm_save_services_handler' );

/* ---------- MIGRATE CPT SERVICES TO PLUGIN ---------- */
function freshm_migrate_services_handler() {
    if ( ! isset( $_POST['freshm_migrate_services'] ) || ! current_user_can( 'manage_options' ) ) return;
    check_admin_referer( 'freshm_migrate_services_action', 'freshm_migrate_services_nonce' );

    // Query all existing fresh_service CPT posts
    $posts = get_posts( array(
        'post_type'      => 'fresh_service',
        'posts_per_page' => -1,
        'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
        'orderby'        => 'menu_order',
        'order'          => 'ASC',
    ) );

    if ( empty( $posts ) ) {
        wp_safe_redirect( add_query_arg( array( 'freshm_migrated' => '0', 'tab' => 'list' ) ) );
        exit;
    }

    // Existing plugin data — we'll merge (skip duplicates by slug)
    $existing = get_option( 'freshm_services_data', array() );
    $existing_slugs = array();
    foreach ( $existing as $sv ) {
        $existing_slugs[] = $sv['slug'] ?? '';
    }

    // Migrate categories from taxonomy
    $terms = get_terms( array( 'taxonomy' => 'service_category', 'hide_empty' => false ) );
    $cat_data = get_option( 'freshm_service_categories', array() );
    $cat_slugs = array_column( $cat_data, 'slug' );
    if ( ! is_wp_error( $terms ) ) {
        foreach ( $terms as $i => $term ) {
            if ( ! in_array( $term->slug, $cat_slugs, true ) ) {
                $cat_data[] = array(
                    'name'  => $term->name,
                    'slug'  => $term->slug,
                    'order' => count( $cat_data ),
                );
            }
        }
        update_option( 'freshm_service_categories', $cat_data );
    }

    $migrated = 0;
    foreach ( $posts as $order => $post ) {
        $slug = $post->post_name;

        // Skip if slug already exists in plugin data
        if ( in_array( $slug, $existing_slugs, true ) ) continue;

        // Read CPT meta
        $icon       = get_post_meta( $post->ID, 'service_icon', true ) ?: '';
        $color      = get_post_meta( $post->ID, 'service_accent_color', true )
                      ?: get_post_meta( $post->ID, 'accent_color', true )
                      ?: '#c9a84c';
        $hero_image = get_post_meta( $post->ID, 'service_hero_image', true ) ?: '';
        $video_url  = get_post_meta( $post->ID, 'service_video_url', true )
                      ?: get_post_meta( $post->ID, 'video_url', true )
                      ?: '';
        $cta_title  = get_post_meta( $post->ID, 'service_cta_title', true ) ?: '';
        $cta_text   = get_post_meta( $post->ID, 'service_cta_text', true ) ?: '';
        $cta_btn    = get_post_meta( $post->ID, 'service_cta_btn', true ) ?: '';

        // Parse pipe-delimited meta for benefits: "icon | title | desc" per line
        $raw_benefits = get_post_meta( $post->ID, 'service_benefits', true );
        $benefits = array();
        if ( $raw_benefits ) {
            $parsed = freshm_parse_pipe_meta( $raw_benefits );
            foreach ( $parsed as $parts ) {
                $benefits[] = array(
                    'icon'  => isset( $parts[0] ) ? trim( $parts[0] ) : '',
                    'title' => isset( $parts[1] ) ? trim( $parts[1] ) : '',
                    'desc'  => isset( $parts[2] ) ? trim( $parts[2] ) : '',
                );
            }
        }

        // Parse pipe-delimited meta for process: "number | title | desc" per line
        $raw_process = get_post_meta( $post->ID, 'service_process', true );
        $process = array();
        if ( $raw_process ) {
            $parsed = freshm_parse_pipe_meta( $raw_process );
            foreach ( $parsed as $parts ) {
                $process[] = array(
                    'number' => isset( $parts[0] ) ? trim( $parts[0] ) : '',
                    'title'  => isset( $parts[1] ) ? trim( $parts[1] ) : '',
                    'desc'   => isset( $parts[2] ) ? trim( $parts[2] ) : '',
                );
            }
        }

        // Parse pipe-delimited meta for results/metrics: "number | desc" per line
        $raw_results = get_post_meta( $post->ID, 'service_results', true );
        $metrics = array();
        if ( $raw_results ) {
            $parsed = freshm_parse_pipe_meta( $raw_results );
            foreach ( $parsed as $parts ) {
                $metrics[] = array(
                    'number' => isset( $parts[0] ) ? trim( $parts[0] ) : '',
                    'desc'   => isset( $parts[1] ) ? trim( $parts[1] ) : '',
                );
            }
        }

        // Parse newline-delimited gallery URLs
        $raw_gallery = get_post_meta( $post->ID, 'service_gallery', true );
        $gallery = $raw_gallery ? freshm_parse_gallery( $raw_gallery ) : array();

        // Get category from taxonomy
        $terms_assigned = get_the_terms( $post->ID, 'service_category' );
        $category = '';
        if ( $terms_assigned && ! is_wp_error( $terms_assigned ) ) {
            $category = $terms_assigned[0]->slug;
        }

        // Use featured image as hero if no hero_image meta
        if ( ! $hero_image && has_post_thumbnail( $post->ID ) ) {
            $hero_image = get_the_post_thumbnail_url( $post->ID, 'full' ) ?: '';
        }

        // Build plugin data structure
        $existing[] = array(
            'name'       => $post->post_title,
            'slug'       => $slug,
            'category'   => $category,
            'icon'       => $icon,
            'excerpt'    => $post->post_excerpt,
            'color'      => $color,
            'order'      => $post->menu_order ?: ( count( $existing ) ),
            'status'     => $post->post_status === 'publish' ? 'publish' : 'draft',
            'hero_image' => $hero_image,
            'content'    => $post->post_content,
            'video_url'  => $video_url,
            'cta_title'  => $cta_title,
            'cta_text'   => $cta_text,
            'cta_btn'    => $cta_btn,
            'benefits'   => $benefits,
            'process'    => $process,
            'metrics'    => $metrics,
            'gallery'    => $gallery,
        );

        // Tag the CPT post so it knows it's been migrated
        update_post_meta( $post->ID, '_freshm_service_slug', $slug );

        $migrated++;
    }

    // Sort by order and save
    usort( $existing, function( $a, $b ) { return ( $a['order'] ?? 0 ) - ( $b['order'] ?? 0 ); } );
    update_option( 'freshm_services_data', $existing );

    wp_safe_redirect( add_query_arg( array( 'freshm_migrated' => $migrated, 'tab' => 'list' ) ) );
    exit;
}
add_action( 'admin_init', 'freshm_migrate_services_handler' );

/* ---------- SYNC CATEGORIES TO TAXONOMY ---------- */
function freshm_sync_service_cats( $cats ) {
    foreach ( $cats as $c ) {
        if ( ! term_exists( $c['slug'], 'service_category' ) ) {
            wp_insert_term( $c['name'], 'service_category', array( 'slug' => $c['slug'] ) );
        } else {
            $term = get_term_by( 'slug', $c['slug'], 'service_category' );
            if ( $term && $term->name !== $c['name'] ) {
                wp_update_term( $term->term_id, 'service_category', array( 'name' => $c['name'] ) );
            }
        }
    }
}

/* ---------- SYNC SERVICES TO CPT ---------- */
function freshm_sync_services_to_cpt( $services ) {
    $existing = get_posts( array(
        'post_type'      => 'fresh_service',
        'posts_per_page' => -1,
        'post_status'    => array( 'publish', 'draft', 'pending' ),
    ) );
    $by_slug = array();
    foreach ( $existing as $p ) $by_slug[ $p->post_name ] = $p;

    $synced = array();
    foreach ( $services as $sv ) {
        if ( empty( $sv['name'] ) ) continue;
        $slug = $sv['slug'];
        $synced[] = $slug;

        $post_data = array(
            'post_type'    => 'fresh_service',
            'post_title'   => $sv['name'],
            'post_name'    => $slug,
            'post_content' => $sv['content'],
            'post_status'  => $sv['status'],
            'post_excerpt' => $sv['excerpt'],
            'menu_order'   => $sv['order'],
        );

        if ( isset( $by_slug[ $slug ] ) ) {
            $post_data['ID'] = $by_slug[ $slug ]->ID;
            wp_update_post( $post_data );
            $pid = $by_slug[ $slug ]->ID;
        } else {
            $pid = wp_insert_post( $post_data );
        }

        if ( ! is_wp_error( $pid ) && $pid ) {
            update_post_meta( $pid, 'service_icon', $sv['icon'] );
            update_post_meta( $pid, 'accent_color', $sv['color'] );
            update_post_meta( $pid, 'video_url', $sv['video_url'] );
            update_post_meta( $pid, '_freshm_service_slug', $slug );

            // Set category taxonomy
            if ( $sv['category'] ) {
                $term = get_term_by( 'slug', $sv['category'], 'service_category' );
                if ( $term ) {
                    wp_set_object_terms( $pid, $term->term_id, 'service_category' );
                }
            }

            // Featured image
            if ( $sv['hero_image'] ) {
                freshm_set_featured_image_from_url( $pid, $sv['hero_image'] );
            }
        }
    }

    // Trash orphans
    foreach ( $by_slug as $slug => $post ) {
        if ( ! in_array( $slug, $synced, true ) ) {
            wp_trash_post( $post->ID );
        }
    }
}

/* ---------- ADMIN PAGE RENDERER ---------- */
function freshm_page_services_mgr() {
    $saved   = isset( $_GET['freshm_saved'] );
    $reset   = isset( $_GET['freshm_reset'] );
    $migrated = isset( $_GET['freshm_migrated'] ) ? intval( $_GET['freshm_migrated'] ) : false;
    ?>
    <div class="freshm-wrap">
        <div class="freshm-header">
            <h1><span class="freshm-logo">F</span> FRESH Manager — שירותים</h1>
        </div>
        <?php if ( $saved ) : ?>
            <div class="freshm-notice freshm-notice-success">✅ השינויים נשמרו והנתונים סונכרנו לאתר!</div>
        <?php endif; ?>
        <?php if ( $reset ) : ?>
            <div class="freshm-notice freshm-notice-success">✅ השירותים אופסו ל-12 ברירות המחדל בהצלחה!</div>
        <?php endif; ?>
        <?php if ( $migrated !== false ) :
            if ( $migrated > 0 ) : ?>
                <div class="freshm-notice freshm-notice-success">✅ הועברו <?php echo $migrated; ?> שירותים בהצלחה מה-CPT לפלאגין!</div>
            <?php else : ?>
                <div class="freshm-notice" style="background:rgba(201,168,76,0.1);border-color:var(--gold);color:#C9A84C;padding:1rem 1.5rem;border-radius:8px;margin-bottom:1.5rem;">ℹ️ לא נמצאו שירותים חדשים להעברה (כולם כבר קיימים בפלאגין).</div>
            <?php endif;
        endif; ?>
        <?php freshm_services_mgr_inner(); ?>
    </div>
    <?php
}

/**
 * Inner content for services manager — used standalone and inside unified tabs.
 */
function freshm_services_mgr_inner() {
    $services   = get_option( 'freshm_services_data', array() );
    $categories = get_option( 'freshm_service_categories', array() );
    ?>
    <!-- Migration Tool -->
    <?php
    $cpt_count = wp_count_posts( 'fresh_service' );
    $total_cpt = ( $cpt_count->publish ?? 0 ) + ( $cpt_count->draft ?? 0 ) + ( $cpt_count->pending ?? 0 ) + ( $cpt_count->private ?? 0 );
    if ( $total_cpt > 0 && empty( $services ) ) :
    ?>
    <div class="freshm-migrate-section" style="background:rgba(201,168,76,0.08);border:1px solid rgba(201,168,76,0.3);border-radius:12px;padding:1.5rem 2rem;margin-bottom:2rem;">
        <h3 style="margin:0 0 0.5rem;color:#C9A84C;">📦 העברת שירותים מה-CPT</h3>
        <p style="margin:0 0 1rem;opacity:0.8;">נמצאו <strong><?php echo $total_cpt; ?></strong> שירותים קיימים בפוסטים (CPT). לחצו להעברה אוטומטית לממשק הפלאגין.</p>
        <form method="post" style="display:inline;">
            <?php wp_nonce_field( 'freshm_migrate_services_action', 'freshm_migrate_services_nonce' ); ?>
            <input type="hidden" name="freshm_migrate_services" value="1">
            <input type="hidden" name="freshm_tab" value="list">
            <button type="submit" class="freshm-btn" style="background:#C9A84C;color:#0A0A0C;font-weight:600;" onclick="return confirm('להעביר את כל השירותים מה-CPT לפלאגין?');">📦 העבר שירותים לפלאגין</button>
        </form>
    </div>
    <?php endif; ?>

    <!-- Reset to Defaults -->
    <div style="margin-bottom:1.5rem;text-align:left;">
        <form method="post" style="display:inline;">
            <?php wp_nonce_field( 'freshm_reset_services_action', 'freshm_reset_services_nonce' ); ?>
            <input type="hidden" name="freshm_reset_services" value="1">
            <input type="hidden" name="freshm_tab" value="list">
            <button type="submit" class="freshm-btn" style="font-size:12px;opacity:0.7;" onclick="return confirm('לאפס את כל השירותים ל-12 ברירות המחדל? פעולה זו תמחק את כל השירותים הנוכחיים!');">🔄 אפס לברירת מחדל (12 שירותים)</button>
        </form>
    </div>

    <form method="post" enctype="multipart/form-data">
        <?php wp_nonce_field( 'freshm_services_action', 'freshm_services_nonce' ); ?>
        <input type="hidden" name="freshm_save_services" value="1">
        <input type="hidden" name="freshm_tab" value="list">

        <!-- Categories Section -->
        <div class="freshm-categories-section">
            <div class="freshm-section-title" style="padding: 1.5rem 2rem 0;">
                <h2>🏷️ ניהול קטגוריות</h2>
                <p>קטגוריות משמשות לסינון בטאבים, במגה-מנו, ובדפי שירותים.</p>
            </div>
            <div class="freshm-cats-list" style="padding: 0 2rem 1.5rem;">
                <div class="freshm-cats-items">
                    <?php if ( ! empty( $categories ) ) : foreach ( $categories as $ci => $c ) : ?>
                    <div class="freshm-cat-item">
                        <input type="text" name="freshm_svc_cats[<?php echo $ci; ?>][name]" value="<?php echo esc_attr( $c['name'] ); ?>" placeholder="שם קטגוריה">
                        <input type="text" name="freshm_svc_cats[<?php echo $ci; ?>][slug]" value="<?php echo esc_attr( $c['slug'] ); ?>" placeholder="slug" dir="ltr" class="freshm-cat-slug">
                        <input type="number" name="freshm_svc_cats[<?php echo $ci; ?>][order]" value="<?php echo intval( $c['order'] ); ?>" placeholder="סדר" class="freshm-cat-order">
                        <button type="button" class="freshm-mini-remove" title="הסר">✕</button>
                    </div>
                    <?php endforeach; endif; ?>
                </div>
                <button type="button" class="freshm-btn freshm-cat-add">+ הוסף קטגוריה</button>
            </div>
        </div>

        <!-- Services List -->
        <div class="freshm-cards-toolbar">
            <button type="button" class="freshm-btn freshm-add-card" data-target="services">+ הוסף שירות</button>
            <span class="freshm-cards-count"><?php echo count( $services ); ?> שירותים</span>
        </div>

        <div class="freshm-cards-list" id="freshm-services-list">
            <?php
            if ( ! empty( $services ) ) :
                foreach ( $services as $idx => $sv ) :
                    freshm_render_service_card( $idx, $sv, $categories );
                endforeach;
            endif;
            ?>
        </div>

        <!-- Service Card Template -->
        <script type="text/html" id="freshm-service-template">
            <?php freshm_render_service_card( '__IDX__', array(), $categories ); ?>
        </script>

        <div class="freshm-save-bar">
            <button type="submit" class="freshm-btn-save">💾 שמור הכל וסנכרן</button>
        </div>
    </form>
    <?php
}

/* ---------- SINGLE SERVICE CARD RENDERER ---------- */
function freshm_render_service_card( $idx, $sv, $categories ) {
    $sv = wp_parse_args( $sv, array(
        'name' => '', 'slug' => '', 'category' => '', 'icon' => '', 'custom_icon' => '', 'excerpt' => '',
        'color' => '#c9a84c', 'order' => 0, 'status' => 'publish',
        'hero_image' => '', 'content' => '', 'video_url' => '',
        'cta_title' => '', 'cta_text' => '', 'cta_btn' => '', 'closing_text' => '',
        'benefits' => array(), 'process' => array(), 'metrics' => array(), 'gallery' => array(),
        'faqs' => array(),
    ) );
    $n = "freshm_svcs[{$idx}]";
    $status_label = $sv['status'] === 'draft' ? 'טיוטה' : 'פורסם';
    $status_class = $sv['status'] === 'draft' ? 'draft' : 'published';
    ?>
    <div class="freshm-card" data-type="service">
        <div class="freshm-card-header" onclick="this.parentElement.classList.toggle('open')">
            <span class="freshm-card-handle">☰</span>
            <span class="freshm-card-title"><?php echo esc_html( $sv['name'] ?: 'שירות חדש' ); ?></span>
            <span class="freshm-card-badge <?php echo $status_class; ?>"><?php echo $status_label; ?></span>
            <span class="freshm-card-industry"><?php echo esc_html( $sv['category'] ); ?></span>
            <span class="freshm-card-toggle">▼</span>
        </div>
        <div class="freshm-card-body">
            <!-- Basic Info -->
            <div class="freshm-card-section">
                <h3>מידע בסיסי</h3>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label>שם השירות *</label>
                        <input type="text" name="<?php echo $n; ?>[name]" value="<?php echo esc_attr( $sv['name'] ); ?>" class="freshm-card-name-input">
                    </div>
                    <div class="freshm-field">
                        <label>סלאג (URL)</label>
                        <input type="text" name="<?php echo $n; ?>[slug]" value="<?php echo esc_attr( $sv['slug'] ); ?>" dir="ltr" placeholder="auto-generated">
                    </div>
                    <div class="freshm-field">
                        <label>קטגוריה</label>
                        <select name="<?php echo $n; ?>[category]">
                            <option value="">— ללא —</option>
                            <?php foreach ( $categories as $c ) : ?>
                            <option value="<?php echo esc_attr( $c['slug'] ); ?>" <?php selected( $sv['category'], $c['slug'] ); ?>><?php echo esc_html( $c['name'] ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php freshm_render_icon_selector( $n, $sv['icon'], $sv['custom_icon'] ); ?>
                    <div class="freshm-field">
                        <label>סדר תצוגה</label>
                        <input type="number" name="<?php echo $n; ?>[order]" value="<?php echo intval( $sv['order'] ); ?>" min="0">
                    </div>
                    <div class="freshm-field">
                        <label>סטטוס</label>
                        <select name="<?php echo $n; ?>[status]">
                            <option value="publish" <?php selected( $sv['status'], 'publish' ); ?>>פורסם</option>
                            <option value="draft" <?php selected( $sv['status'], 'draft' ); ?>>טיוטה</option>
                        </select>
                    </div>
                    <div class="freshm-field">
                        <label>צבע מבטא</label>
                        <input type="text" name="<?php echo $n; ?>[color]" value="<?php echo esc_attr( $sv['color'] ); ?>" class="freshm-color-picker">
                    </div>
                </div>
                <div class="freshm-field freshm-field-wide">
                    <label>תיאור קצר</label>
                    <textarea name="<?php echo $n; ?>[excerpt]" rows="2"><?php echo esc_textarea( $sv['excerpt'] ); ?></textarea>
                </div>
                <?php freshm_card_image_field( $n . '[hero_image]', 'תמונת Hero', $sv['hero_image'] ); ?>
            </div>

            <!-- Content -->
            <div class="freshm-card-section">
                <h3>תוכן מלא</h3>
                <div class="freshm-field freshm-field-wide">
                    <label>תוכן השירות (HTML מותר)</label>
                    <textarea name="<?php echo $n; ?>[content]" rows="8"><?php echo esc_textarea( $sv['content'] ); ?></textarea>
                </div>
            </div>

            <!-- Benefits -->
            <div class="freshm-card-section">
                <h3>יתרונות</h3>
                <div class="freshm-mini-repeater" data-max="8">
                    <div class="freshm-mini-items freshm-benefits-items">
                        <?php if ( ! empty( $sv['benefits'] ) ) : foreach ( $sv['benefits'] as $bi => $b ) : ?>
                        <div class="freshm-mini-item freshm-benefit-item">
                            <input type="text" name="<?php echo $n; ?>[benefits][<?php echo $bi; ?>][icon]" value="<?php echo esc_attr( $b['icon'] ); ?>" placeholder="אייקון" class="freshm-mini-icon" style="width:60px;text-align:center;">
                            <input type="text" name="<?php echo $n; ?>[benefits][<?php echo $bi; ?>][title]" value="<?php echo esc_attr( $b['title'] ); ?>" placeholder="כותרת">
                            <input type="text" name="<?php echo $n; ?>[benefits][<?php echo $bi; ?>][desc]" value="<?php echo esc_attr( $b['desc'] ); ?>" placeholder="תיאור">
                            <button type="button" class="freshm-mini-remove">✕</button>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add-benefit" data-name="<?php echo $n; ?>[benefits]">+ הוסף יתרון</button>
                </div>
            </div>

            <!-- Process Steps -->
            <div class="freshm-card-section">
                <h3>שלבי התהליך</h3>
                <div class="freshm-mini-repeater" data-max="8">
                    <div class="freshm-mini-items freshm-process-items">
                        <?php if ( ! empty( $sv['process'] ) ) : foreach ( $sv['process'] as $pi => $p ) : ?>
                        <div class="freshm-mini-item">
                            <input type="text" name="<?php echo $n; ?>[process][<?php echo $pi; ?>][number]" value="<?php echo esc_attr( $p['number'] ); ?>" placeholder="01" class="freshm-mini-num">
                            <input type="text" name="<?php echo $n; ?>[process][<?php echo $pi; ?>][title]" value="<?php echo esc_attr( $p['title'] ); ?>" placeholder="כותרת">
                            <input type="text" name="<?php echo $n; ?>[process][<?php echo $pi; ?>][desc]" value="<?php echo esc_attr( $p['desc'] ); ?>" placeholder="תיאור">
                            <button type="button" class="freshm-mini-remove">✕</button>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add-process" data-name="<?php echo $n; ?>[process]">+ הוסף שלב</button>
                </div>
            </div>

            <!-- Media -->
            <div class="freshm-card-section">
                <h3>מדיה</h3>
                <div class="freshm-field">
                    <label>סרטון (YouTube/Vimeo)</label>
                    <input type="url" name="<?php echo $n; ?>[video_url]" value="<?php echo esc_url( $sv['video_url'] ); ?>" dir="ltr" placeholder="https://...">
                </div>
            </div>

            <!-- CTA -->
            <div class="freshm-card-section">
                <h3>CTA (קריאה לפעולה)</h3>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label>כותרת CTA</label>
                        <input type="text" name="<?php echo $n; ?>[cta_title]" value="<?php echo esc_attr( $sv['cta_title'] ); ?>">
                    </div>
                    <div class="freshm-field">
                        <label>טקסט CTA</label>
                        <input type="text" name="<?php echo $n; ?>[cta_text]" value="<?php echo esc_attr( $sv['cta_text'] ); ?>">
                    </div>
                    <div class="freshm-field">
                        <label>טקסט כפתור</label>
                        <input type="text" name="<?php echo $n; ?>[cta_btn]" value="<?php echo esc_attr( $sv['cta_btn'] ); ?>">
                    </div>
                </div>
                <div class="freshm-field" style="margin-top:0.75rem;">
                    <label>פסקת סיום (מופיעה אחרי תהליך העבודה)</label>
                    <textarea name="<?php echo $n; ?>[closing_text]" rows="3" style="width:100%;"><?php echo esc_textarea( $sv['closing_text'] ); ?></textarea>
                    <p class="freshm-info">השאירו ריק לטקסט ברירת מחדל</p>
                </div>
            </div>

            <!-- FAQs -->
            <div class="freshm-card-section">
                <h3>שאלות נפוצות (FAQ)</h3>
                <div class="freshm-mini-repeater" data-max="8">
                    <div class="freshm-mini-items freshm-faq-items">
                        <?php if ( ! empty( $sv['faqs'] ) ) : foreach ( $sv['faqs'] as $fi => $fq ) : ?>
                        <div class="freshm-mini-item freshm-faq-item" style="flex-wrap:wrap;gap:6px;">
                            <input type="text" name="<?php echo $n; ?>[faqs][<?php echo $fi; ?>][q]" value="<?php echo esc_attr( $fq['q'] ); ?>" placeholder="שאלה" style="flex:1;min-width:200px;">
                            <button type="button" class="freshm-mini-remove">✕</button>
                            <textarea name="<?php echo $n; ?>[faqs][<?php echo $fi; ?>][a]" rows="2" placeholder="תשובה" style="width:100%;margin-top:2px;"><?php echo esc_textarea( $fq['a'] ); ?></textarea>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add-faq" data-name="<?php echo $n; ?>[faqs]">+ הוסף שאלה</button>
                </div>
            </div>

            <!-- Delete -->
            <div class="freshm-card-actions">
                <button type="button" class="freshm-btn freshm-delete-card">🗑️ מחק שירות</button>
            </div>
        </div>
    </div>
    <?php
}
