<?php
/**
 * FRESH Manager — עמודי קטגוריות שירות (Service Category Pages) Admin Page
 */
defined( 'ABSPATH' ) || exit;

/* ---------- CATEGORIES LIST ---------- */
function freshm_get_service_categories_list() {
    return array(
        'strategy'              => 'אסטרטגיה',
        'paid-ads'              => 'קידום ממומן',
        'social-media'          => 'ניהול רשתות חברתיות',
        'google-business'       => 'ניהול פרופיל עסקי בגוגל',
        'content-creation'      => 'יצירת תוכן',
        'delivery-platforms'    => 'ניהול פלטפורמות משלוחים',
        'reservation-platforms' => 'ניהול פלטפורמות להזמנת שולחן',
        'loyalty-club'          => 'ניהול מערכות מועדון לקוחות',
        'influencer-collabs'    => 'שיתופי פעולה עם משפיענים',
        'reviews'               => 'שיפור ביקורות',
        'branding'              => 'מיתוג',
        'websites'              => 'בניית אתרים',
        'analytics'             => 'אנליטיקס ודוחות',
        'digital-menus'         => 'תפריטים דיגיטליים',
    );
}

/* ---------- DEFAULT EMOJI ICONS ---------- */
function freshm_category_default_icons() {
    return array(
        'strategy'              => '🎯',
        'paid-ads'              => '📢',
        'social-media'          => '📱',
        'google-business'       => '📍',
        'content-creation'      => '🎬',
        'delivery-platforms'    => '🛵',
        'reservation-platforms' => '📋',
        'loyalty-club'          => '💳',
        'influencer-collabs'    => '🤝',
        'reviews'               => '⭐',
        'branding'              => '🎨',
        'websites'              => '🌐',
        'analytics'             => '📊',
        'digital-menus'         => '📜',
    );
}

/* ---------- SAVE HANDLER ---------- */
function freshm_save_category_pages_handler() {
    if ( ! isset( $_POST['freshm_save_category_pages'] ) || ! current_user_can( 'manage_options' ) ) return;
    check_admin_referer( 'freshm_categories_action', 'freshm_categories_nonce' );

    $raw             = wp_unslash( $_POST );
    $categories_data = isset( $raw['freshm_category_page'] ) ? $raw['freshm_category_page'] : array();

    foreach ( $categories_data as $slug => $fields ) {
        $slug = sanitize_key( $slug );
        $data = array(
            'name'              => sanitize_text_field( $fields['name'] ?? '' ),
            'hero_icon'         => sanitize_text_field( $fields['hero_icon'] ?? '' ),
            'hero_title'        => sanitize_text_field( $fields['hero_title'] ?? '' ),
            'hero_subtitle'     => wp_kses_post( $fields['hero_subtitle'] ?? '' ),
            'hero_bg_image'     => esc_url_raw( $fields['hero_bg_image'] ?? '' ),
            'problem_title'     => sanitize_text_field( $fields['problem_title'] ?? 'הבעיה שאנחנו פותרים' ),
            'problem_content'   => wp_kses_post( $fields['problem_content'] ?? '' ),
            'process'           => array(),
            'stats'             => array(),
            'faq'               => array(),
            'cta_title'         => sanitize_text_field( $fields['cta_title'] ?? '' ),
            'cta_subtitle'      => wp_kses_post( $fields['cta_subtitle'] ?? '' ),
            'cta_btn_text'      => sanitize_text_field( $fields['cta_btn_text'] ?? '' ),
            'cta_btn_url'       => esc_url_raw( $fields['cta_btn_url'] ?? '#' ),
            'cta_show_whatsapp' => sanitize_text_field( $fields['cta_show_whatsapp'] ?? '1' ),
        );

        // Process repeater
        if ( ! empty( $fields['process'] ) && is_array( $fields['process'] ) ) {
            foreach ( $fields['process'] as $step ) {
                if ( empty( $step['title'] ) ) continue;
                $data['process'][] = array(
                    'title'       => sanitize_text_field( $step['title'] ),
                    'description' => wp_kses_post( $step['description'] ?? '' ),
                );
            }
        }

        // FAQ repeater
        if ( ! empty( $fields['faq'] ) && is_array( $fields['faq'] ) ) {
            foreach ( $fields['faq'] as $item ) {
                if ( empty( $item['question'] ) ) continue;
                $data['faq'][] = array(
                    'question' => sanitize_text_field( $item['question'] ),
                    'answer'   => wp_kses_post( $item['answer'] ?? '' ),
                );
            }
        }

        update_option( 'freshm_category_page_' . $slug, $data );
    }

    $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_category_pages_handler' );

/* ---------- RESET HANDLER ---------- */
function freshm_reset_category_pages_handler() {
    if ( ! isset( $_POST['freshm_reset_categories'] ) || ! current_user_can( 'manage_options' ) ) return;
    check_admin_referer( 'freshm_categories_action', 'freshm_categories_nonce' );
    freshm_seed_category_pages( true );
    delete_transient( 'freshm_cats_terms_checked' ); // re-check terms on next init
    wp_safe_redirect( add_query_arg( array( 'freshm_saved' => '1', 'tab' => 'pages' ) ) );
    exit;
}
add_action( 'admin_init', 'freshm_reset_category_pages_handler' );

/* ---------- ADMIN PAGE RENDERER ---------- */
function freshm_page_categories() {
    $saved = isset( $_GET['freshm_saved'] );
    ?>
    <div class="freshm-wrap">
        <div class="freshm-header">
            <h1><span class="freshm-logo">F</span> FRESH Manager — <?php echo esc_html( 'עמודי קטגוריות שירות' ); ?></h1>
        </div>

        <?php if ( $saved ) : ?>
            <div class="freshm-notice freshm-notice-success"><?php echo esc_html( 'השינויים נשמרו בהצלחה!' ); ?></div>
        <?php endif; ?>
        <?php freshm_categories_inner(); ?>
    </div>
    <?php
}

/**
 * Inner content for category pages — used standalone and inside unified tabs.
 */
function freshm_categories_inner() {
    $categories = freshm_get_service_categories_list();
    $icons      = freshm_category_default_icons();
    ?>
    <!-- Reset Form -->
    <form method="post" style="display:inline-block;margin-bottom:1rem;">
        <?php wp_nonce_field( 'freshm_categories_action', 'freshm_categories_nonce' ); ?>
        <input type="hidden" name="freshm_tab" value="pages">
        <button type="submit" name="freshm_reset_categories" value="1" class="freshm-btn" style="background:rgba(201,168,76,0.15);color:#C9A84C;border:1px solid rgba(201,168,76,0.3);" onclick="return confirm('<?php echo esc_js( 'האם לאפס את כל עמודי הקטגוריות לברירת המחדל? כל השינויים יאבדו.' ); ?>');">
            <?php echo esc_html( 'איפוס לברירת מחדל' ); ?>
        </button>
    </form>

    <!-- Main Form -->
    <form method="post" enctype="multipart/form-data">
        <?php wp_nonce_field( 'freshm_categories_action', 'freshm_categories_nonce' ); ?>
        <input type="hidden" name="freshm_save_category_pages" value="1">
        <input type="hidden" name="freshm_tab" value="pages">

        <div class="freshm-cards-toolbar">
            <span class="freshm-cards-count"><?php echo count( $categories ); ?> <?php echo esc_html( 'קטגוריות' ); ?></span>
            <button type="button" class="freshm-btn" onclick="document.querySelectorAll('.freshm-card[data-type=category]').forEach(c=>c.classList.add('open'))">
                <?php echo esc_html( 'פתח הכל' ); ?>
            </button>
            <button type="button" class="freshm-btn" onclick="document.querySelectorAll('.freshm-card[data-type=category]').forEach(c=>c.classList.remove('open'))">
                <?php echo esc_html( 'סגור הכל' ); ?>
            </button>
        </div>

        <div class="freshm-cards-list" id="freshm-categories-list">
            <?php
            foreach ( $categories as $slug => $name ) :
                $data = freshm_get_category_page_data( $slug );
                freshm_render_category_card( $slug, $name, $data );
            endforeach;
            ?>
        </div>

        <div class="freshm-save-bar">
            <button type="submit" class="freshm-btn-save"><?php echo esc_html( 'שמור הכל' ); ?></button>
        </div>
    </form>

    <!-- Category page JS for mini-repeaters -->
    <script>
    (function(){
        'use strict';

        /* ---------- ACCORDION TOGGLE ---------- */
        document.addEventListener('click', function(e) {
            var header = e.target.closest('.freshm-card-header');
            if ( header && header.closest('#freshm-categories-list') ) {
                header.parentElement.classList.toggle('open');
            }
        });

        /* ---------- MINI REMOVE ---------- */
        document.addEventListener('click', function(e) {
            if ( e.target.classList.contains('freshm-mini-remove') ) {
                var item = e.target.closest('.freshm-mini-item') || e.target.closest('.freshm-faq-item');
                if ( item ) item.remove();
            }
        });

        /* ---------- ADD PROCESS STEP ---------- */
        document.addEventListener('click', function(e) {
            if ( ! e.target.classList.contains('freshm-mini-add-process') ) return;
            var slug  = e.target.getAttribute('data-slug');
            var wrap  = e.target.closest('.freshm-mini-repeater').querySelector('.freshm-mini-items');
            var idx   = wrap.querySelectorAll('.freshm-mini-item').length;
            var base  = 'freshm_category_page[' + slug + '][process][' + idx + ']';
            var div   = document.createElement('div');
            div.className = 'freshm-mini-item';
            div.innerHTML =
                '<input type="text" name="' + base + '[title]" placeholder="<?php echo esc_js( 'כותרת שלב' ); ?>" class="freshm-mini-num" style="flex:1;">' +
                '<input type="text" name="' + base + '[description]" placeholder="<?php echo esc_js( 'תיאור השלב' ); ?>" class="freshm-mini-label" style="flex:2;">' +
                '<button type="button" class="freshm-mini-remove" title="<?php echo esc_js( 'הסר' ); ?>">✕</button>';
            wrap.appendChild(div);
        });

        /* ---------- ADD FAQ ---------- */
        document.addEventListener('click', function(e) {
            if ( ! e.target.classList.contains('freshm-mini-add-faq') ) return;
            var slug  = e.target.getAttribute('data-slug');
            var wrap  = e.target.closest('.freshm-mini-repeater').querySelector('.freshm-faq-items');
            var idx   = wrap.querySelectorAll('.freshm-faq-item').length;
            var base  = 'freshm_category_page[' + slug + '][faq][' + idx + ']';
            var div   = document.createElement('div');
            div.className = 'freshm-faq-item';
            div.style.cssText = 'display:flex;flex-direction:column;gap:0.5rem;padding:0.8rem;background:rgba(255,255,255,0.02);border-radius:8px;margin-bottom:0.5rem;';
            div.innerHTML =
                '<input type="text" name="' + base + '[question]" placeholder="<?php echo esc_js( 'שאלה' ); ?>" style="font-weight:600;">' +
                '<textarea name="' + base + '[answer]" rows="2" placeholder="<?php echo esc_js( 'תשובה' ); ?>"></textarea>' +
                '<button type="button" class="freshm-mini-remove" style="align-self:flex-end;">✕ <?php echo esc_js( 'הסר' ); ?></button>';
            wrap.appendChild(div);
        });

    })();
    </script>
    <?php
}

/* ---------- SINGLE CATEGORY CARD RENDERER ---------- */
function freshm_render_category_card( $slug, $name, $data ) {
    $data = wp_parse_args( $data, array(
        'name'              => $name,
        'hero_icon'         => '',
        'hero_title'        => '',
        'hero_subtitle'     => '',
        'hero_bg_image'     => '',
        'problem_title'     => 'הבעיה שאנחנו פותרים',
        'problem_content'   => '',
        'process'           => array(),
        'stats'             => array(),
        'faq'               => array(),
        'cta_title'         => '',
        'cta_subtitle'      => '',
        'cta_btn_text'      => '',
        'cta_btn_url'       => '#',
        'cta_show_whatsapp' => '1',
    ) );
    $n = "freshm_category_page[{$slug}]";
    $icon = $data['hero_icon'] ?: '';
    ?>
    <div class="freshm-card" data-type="category">
        <div class="freshm-card-header">
            <span class="freshm-card-handle"><?php echo $icon ? esc_html( $icon ) : '📁'; ?></span>
            <span class="freshm-card-title"><?php echo esc_html( $name ); ?></span>
            <span class="freshm-card-badge" style="font-size:0.75rem;opacity:0.6;"><?php echo esc_html( $slug ); ?></span>
            <span class="freshm-card-toggle">▼</span>
        </div>
        <div class="freshm-card-body">
            <!-- Hidden name field -->
            <input type="hidden" name="<?php echo esc_attr( $n ); ?>[name]" value="<?php echo esc_attr( $name ); ?>">

            <!-- Hero Section -->
            <div class="freshm-card-section">
                <h3><?php echo esc_html( 'Hero - כותרת עליונה' ); ?></h3>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'אייקון (אמוג\'י)' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[hero_icon]" value="<?php echo esc_attr( $data['hero_icon'] ); ?>" placeholder="🎯" style="max-width:80px;text-align:center;font-size:1.5rem;">
                    </div>
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'כותרת Hero' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[hero_title]" value="<?php echo esc_attr( $data['hero_title'] ); ?>" placeholder="<?php echo esc_attr( $name ); ?>">
                    </div>
                </div>
                <div class="freshm-field freshm-field-wide">
                    <label><?php echo esc_html( 'תת-כותרת Hero' ); ?></label>
                    <input type="text" name="<?php echo esc_attr( $n ); ?>[hero_subtitle]" value="<?php echo esc_attr( $data['hero_subtitle'] ); ?>" placeholder="<?php echo esc_attr( 'תיאור קצר של הקטגוריה' ); ?>">
                </div>
                <div class="freshm-grid">
                    <?php freshm_card_image_field( $n . '[hero_bg_image]', 'תמונת רקע Hero', $data['hero_bg_image'] ); ?>
                </div>
            </div>

            <!-- Problem Section -->
            <div class="freshm-card-section">
                <h3><?php echo esc_html( 'הבעיה' ); ?></h3>
                <div class="freshm-field">
                    <label><?php echo esc_html( 'כותרת סקשן' ); ?></label>
                    <input type="text" name="<?php echo esc_attr( $n ); ?>[problem_title]" value="<?php echo esc_attr( $data['problem_title'] ); ?>" placeholder="<?php echo esc_attr( 'הבעיה שאנחנו פותרים' ); ?>">
                </div>
                <div class="freshm-field freshm-field-wide">
                    <label><?php echo esc_html( 'תוכן (HTML מותר)' ); ?></label>
                    <textarea name="<?php echo esc_attr( $n ); ?>[problem_content]" rows="4"><?php echo esc_textarea( $data['problem_content'] ); ?></textarea>
                </div>
            </div>

            <!-- Work Process -->
            <div class="freshm-card-section">
                <h3><?php echo esc_html( 'תהליך עבודה' ); ?></h3>
                <p class="freshm-hint"><?php echo esc_html( '3-5 שלבים בתהליך.' ); ?></p>
                <div class="freshm-mini-repeater">
                    <div class="freshm-mini-items">
                        <?php if ( ! empty( $data['process'] ) ) :
                            foreach ( $data['process'] as $pi => $step ) : ?>
                                <div class="freshm-mini-item">
                                    <input type="text" name="<?php echo esc_attr( $n ); ?>[process][<?php echo (int) $pi; ?>][title]" value="<?php echo esc_attr( $step['title'] ); ?>" placeholder="<?php echo esc_attr( 'כותרת שלב' ); ?>" class="freshm-mini-num" style="flex:1;">
                                    <input type="text" name="<?php echo esc_attr( $n ); ?>[process][<?php echo (int) $pi; ?>][description]" value="<?php echo esc_attr( $step['description'] ?? '' ); ?>" placeholder="<?php echo esc_attr( 'תיאור השלב' ); ?>" class="freshm-mini-label" style="flex:2;">
                                    <button type="button" class="freshm-mini-remove" title="<?php echo esc_attr( 'הסר' ); ?>">✕</button>
                                </div>
                            <?php endforeach;
                        endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add-process" data-slug="<?php echo esc_attr( $slug ); ?>">+ <?php echo esc_html( 'הוסף שלב' ); ?></button>
                </div>
            </div>

            <!-- FAQ -->
            <div class="freshm-card-section">
                <h3><?php echo esc_html( 'שאלות נפוצות (FAQ)' ); ?></h3>
                <p class="freshm-hint"><?php echo esc_html( '4-5 שאלות ותשובות.' ); ?></p>
                <div class="freshm-mini-repeater">
                    <div class="freshm-faq-items">
                        <?php if ( ! empty( $data['faq'] ) ) :
                            foreach ( $data['faq'] as $fi => $faq ) : ?>
                                <div class="freshm-faq-item" style="display:flex;flex-direction:column;gap:0.5rem;padding:0.8rem;background:rgba(255,255,255,0.02);border-radius:8px;margin-bottom:0.5rem;">
                                    <input type="text" name="<?php echo esc_attr( $n ); ?>[faq][<?php echo (int) $fi; ?>][question]" value="<?php echo esc_attr( $faq['question'] ); ?>" placeholder="<?php echo esc_attr( 'שאלה' ); ?>" style="font-weight:600;">
                                    <textarea name="<?php echo esc_attr( $n ); ?>[faq][<?php echo (int) $fi; ?>][answer]" rows="2" placeholder="<?php echo esc_attr( 'תשובה' ); ?>"><?php echo esc_textarea( $faq['answer'] ?? '' ); ?></textarea>
                                    <button type="button" class="freshm-mini-remove" style="align-self:flex-end;">✕ <?php echo esc_html( 'הסר' ); ?></button>
                                </div>
                            <?php endforeach;
                        endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add-faq" data-slug="<?php echo esc_attr( $slug ); ?>">+ <?php echo esc_html( 'הוסף שאלה' ); ?></button>
                </div>
            </div>

            <!-- CTA Section -->
            <div class="freshm-card-section">
                <h3><?php echo esc_html( 'קריאה לפעולה (CTA)' ); ?></h3>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'כותרת CTA' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[cta_title]" value="<?php echo esc_attr( $data['cta_title'] ); ?>" placeholder="<?php echo esc_attr( 'מוכנים להתחיל?' ); ?>">
                    </div>
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'תת-כותרת CTA' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[cta_subtitle]" value="<?php echo esc_attr( $data['cta_subtitle'] ); ?>" placeholder="<?php echo esc_attr( 'צרו קשר עוד היום' ); ?>">
                    </div>
                </div>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'טקסט כפתור' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[cta_btn_text]" value="<?php echo esc_attr( $data['cta_btn_text'] ); ?>" placeholder="<?php echo esc_attr( 'דברו איתנו' ); ?>">
                    </div>
                    <div class="freshm-field">
                        <label><?php echo esc_html( 'קישור כפתור' ); ?></label>
                        <input type="text" name="<?php echo esc_attr( $n ); ?>[cta_btn_url]" value="<?php echo esc_attr( $data['cta_btn_url'] ); ?>" placeholder="#" dir="ltr">
                    </div>
                    <div class="freshm-field freshm-field-checkbox">
                        <input type="hidden" name="<?php echo esc_attr( $n ); ?>[cta_show_whatsapp]" value="">
                        <label>
                            <input type="checkbox" name="<?php echo esc_attr( $n ); ?>[cta_show_whatsapp]" value="1" <?php checked( $data['cta_show_whatsapp'], '1' ); ?>>
                            <?php echo esc_html( 'הצג כפתור WhatsApp' ); ?>
                        </label>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <?php
}
