<?php
/**
 * FRESH Manager — הצלחת לקוחות (Client Success Stories) Admin Page
 */
defined( 'ABSPATH' ) || exit;

/* ---------- SAVE HANDLER ---------- */
function freshm_save_stories_handler() {
    if ( ! isset( $_POST['freshm_save_stories'] ) || ! current_user_can( 'manage_options' ) ) return;
    check_admin_referer( 'freshm_stories_action', 'freshm_stories_nonce' );

    $raw = isset( $_POST['freshm_stories'] ) ? $_POST['freshm_stories'] : array();
    $stories = array();

    foreach ( $raw as $item ) {
        if ( empty( $item['name'] ) ) continue;
        $s = array(
            'name'              => sanitize_text_field( $item['name'] ),
            'industry'          => sanitize_text_field( $item['industry'] ?? '' ),
            'slug'              => sanitize_title( $item['slug'] ?: $item['name'] ),
            'image'             => esc_url_raw( $item['image'] ?? '' ),
            'logo'              => esc_url_raw( $item['logo'] ?? '' ),
            'excerpt'           => sanitize_textarea_field( $item['excerpt'] ?? '' ),
            'status'            => ( $item['status'] ?? 'publish' ) === 'draft' ? 'draft' : 'publish',
            'hero_image'        => esc_url_raw( $item['hero_image'] ?? '' ),
            'challenge_title'   => sanitize_text_field( $item['challenge_title'] ?? 'האתגר' ),
            'challenge_content' => wp_kses_post( $item['challenge_content'] ?? '' ),
            'solution_title'    => sanitize_text_field( $item['solution_title'] ?? 'הפתרון' ),
            'solution_content'  => wp_kses_post( $item['solution_content'] ?? '' ),
            'results_title'     => sanitize_text_field( $item['results_title'] ?? 'התוצאות' ),
            'results_content'   => wp_kses_post( $item['results_content'] ?? '' ),
            'quote_text'        => sanitize_textarea_field( $item['quote_text'] ?? '' ),
            'quote_author'      => sanitize_text_field( $item['quote_author'] ?? '' ),
            'quote_role'        => sanitize_text_field( $item['quote_role'] ?? '' ),
            'video_url'         => esc_url_raw( $item['video_url'] ?? '' ),
            'duration'          => sanitize_text_field( $item['duration'] ?? '' ),
            'metrics'           => array(),
            'gallery'           => array(),
        );

        // Metrics sub-repeater
        if ( ! empty( $item['metrics'] ) && is_array( $item['metrics'] ) ) {
            foreach ( $item['metrics'] as $m ) {
                if ( empty( $m['number'] ) && empty( $m['label'] ) ) continue;
                $s['metrics'][] = array(
                    'number' => sanitize_text_field( $m['number'] ?? '' ),
                    'label'  => sanitize_text_field( $m['label'] ?? '' ),
                );
            }
        }

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

        $stories[] = $s;
    }

    update_option( 'freshm_client_stories', $stories );
    freshm_sync_stories_to_cpt( $stories );

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

/* ---------- AUTO-SYNC TO CPT ---------- */
function freshm_sync_stories_to_cpt( $stories ) {
    $existing = get_posts( array(
        'post_type'      => 'fresh_case_study',
        '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 ( $stories as $s ) {
        if ( empty( $s['name'] ) ) continue;
        $slug = $s['slug'];
        $synced[] = $slug;

        // Build structured content from sections
        $content = '';
        if ( $s['challenge_content'] ) {
            $content .= '<h2>' . esc_html( $s['challenge_title'] ?: 'האתגר' ) . '</h2>' . "\n" . $s['challenge_content'] . "\n\n";
        }
        if ( $s['solution_content'] ) {
            $content .= '<h2>' . esc_html( $s['solution_title'] ?: 'הפתרון' ) . '</h2>' . "\n" . $s['solution_content'] . "\n\n";
        }
        if ( $s['results_content'] ) {
            $content .= '<h2>' . esc_html( $s['results_title'] ?: 'התוצאות' ) . '</h2>' . "\n" . $s['results_content'] . "\n\n";
        }

        $post_data = array(
            'post_type'    => 'fresh_case_study',
            'post_title'   => $s['name'],
            'post_name'    => $slug,
            'post_content' => $content,
            'post_status'  => $s['status'],
            'post_excerpt' => $s['excerpt'],
        );

        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, 'client_name', $s['name'] );
            update_post_meta( $pid, 'industry', $s['industry'] );
            update_post_meta( $pid, 'duration', $s['duration'] );
            update_post_meta( $pid, 'client_logo', $s['logo'] );
            update_post_meta( $pid, 'client_quote', $s['quote_text'] );
            update_post_meta( $pid, 'client_quote_author', $s['quote_author'] . ( $s['quote_role'] ? ', ' . $s['quote_role'] : '' ) );
            update_post_meta( $pid, 'video_url', $s['video_url'] );

            // Main result from first metric
            if ( ! empty( $s['metrics'][0] ) ) {
                update_post_meta( $pid, 'main_result', $s['metrics'][0]['number'] . ' ' . $s['metrics'][0]['label'] );
            }
            // Individual result metas
            update_post_meta( $pid, 'result_leads', isset( $s['metrics'][1] ) ? $s['metrics'][1]['number'] : '' );
            update_post_meta( $pid, 'result_roi', isset( $s['metrics'][2] ) ? $s['metrics'][2]['number'] : '' );
            update_post_meta( $pid, 'result_engagement', isset( $s['metrics'][3] ) ? $s['metrics'][3]['number'] : '' );

            // Set featured image from URL
            if ( $s['image'] ) {
                freshm_set_featured_image_from_url( $pid, $s['image'] );
            }

            // Set taxonomy
            if ( $s['industry'] ) {
                $term = get_term_by( 'name', $s['industry'], 'case_study_industry' );
                if ( ! $term ) {
                    $term_data = wp_insert_term( $s['industry'], 'case_study_industry' );
                    if ( ! is_wp_error( $term_data ) ) {
                        wp_set_object_terms( $pid, $term_data['term_id'], 'case_study_industry' );
                    }
                } else {
                    wp_set_object_terms( $pid, $term->term_id, 'case_study_industry' );
                }
            }

            // Store full plugin data reference
            update_post_meta( $pid, '_freshm_story_slug', $slug );
        }
    }

    // Trash CPT posts no longer in plugin data
    foreach ( $by_slug as $slug => $post ) {
        if ( ! in_array( $slug, $synced, true ) ) {
            wp_trash_post( $post->ID );
        }
    }
}

/** Set featured image from URL (if not already set to same URL) */
function freshm_set_featured_image_from_url( $post_id, $url ) {
    if ( ! $url ) return;
    $current = get_post_meta( $post_id, '_freshm_feat_img_url', true );
    if ( $current === $url ) return; // Already set
    update_post_meta( $post_id, '_freshm_feat_img_url', $url );
    // Try to find attachment by URL
    $att_id = attachment_url_to_postid( $url );
    if ( $att_id ) {
        set_post_thumbnail( $post_id, $att_id );
    }
}

/* ---------- ADMIN PAGE RENDERER ---------- */
function freshm_page_stories() {
    $saved = isset( $_GET['freshm_saved'] );
    ?>
    <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 freshm_stories_inner(); ?>
    </div>
    <?php
}

/**
 * Inner content for stories — used standalone and inside unified tabs.
 */
function freshm_stories_inner() {
    $stories = get_option( 'freshm_client_stories', array() );
    ?>
    <form method="post" enctype="multipart/form-data">
        <?php wp_nonce_field( 'freshm_stories_action', 'freshm_stories_nonce' ); ?>
        <input type="hidden" name="freshm_save_stories" value="1">
        <input type="hidden" name="freshm_tab" value="stories">

        <div class="freshm-cards-toolbar">
            <button type="button" class="freshm-btn freshm-add-card" data-target="stories">+ הוסף הצלחת לקוח</button>
            <span class="freshm-cards-count"><?php echo count( $stories ); ?> פריטים</span>
        </div>

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

        <!-- Card Template (hidden) -->
        <script type="text/html" id="freshm-story-template">
            <?php freshm_render_story_card( '__IDX__', array() ); ?>
        </script>

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

/* ---------- SINGLE STORY CARD RENDERER ---------- */
function freshm_render_story_card( $idx, $s ) {
    $s = wp_parse_args( $s, array(
        'name' => '', 'industry' => '', 'slug' => '', 'image' => '', 'logo' => '', 'excerpt' => '',
        'status' => 'publish', 'hero_image' => '',
        'challenge_title' => 'האתגר', 'challenge_content' => '',
        'solution_title' => 'הפתרון', 'solution_content' => '',
        'results_title' => 'התוצאות', 'results_content' => '',
        'quote_text' => '', 'quote_author' => '', 'quote_role' => '',
        'video_url' => '', 'duration' => '',
        'metrics' => array(), 'gallery' => array(),
    ) );
    $n = "freshm_stories[{$idx}]";
    $status_label = $s['status'] === 'draft' ? 'טיוטה' : 'פורסם';
    $status_class = $s['status'] === 'draft' ? 'draft' : 'published';
    ?>
    <div class="freshm-card" data-type="story">
        <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( $s['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( $s['industry'] ); ?></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( $s['name'] ); ?>" class="freshm-card-name-input">
                    </div>
                    <div class="freshm-field">
                        <label>תעשייה</label>
                        <input type="text" name="<?php echo $n; ?>[industry]" value="<?php echo esc_attr( $s['industry'] ); ?>" placeholder="מסעדה איטלקית">
                    </div>
                    <div class="freshm-field">
                        <label>סלאג (URL)</label>
                        <input type="text" name="<?php echo $n; ?>[slug]" value="<?php echo esc_attr( $s['slug'] ); ?>" placeholder="auto-generated" dir="ltr">
                    </div>
                    <div class="freshm-field">
                        <label>משך הפרויקט</label>
                        <input type="text" name="<?php echo $n; ?>[duration]" value="<?php echo esc_attr( $s['duration'] ); ?>" placeholder="3 חודשים">
                    </div>
                    <div class="freshm-field">
                        <label>סטטוס</label>
                        <select name="<?php echo $n; ?>[status]">
                            <option value="publish" <?php selected( $s['status'], 'publish' ); ?>>פורסם</option>
                            <option value="draft" <?php selected( $s['status'], 'draft' ); ?>>טיוטה</option>
                        </select>
                    </div>
                </div>
                <div class="freshm-field freshm-field-wide">
                    <label>תיאור קצר</label>
                    <textarea name="<?php echo $n; ?>[excerpt]" rows="2"><?php echo esc_textarea( $s['excerpt'] ); ?></textarea>
                </div>
                <div class="freshm-grid">
                    <?php freshm_card_image_field( $n . '[image]', 'תמונה ראשית', $s['image'] ); ?>
                    <?php freshm_card_image_field( $n . '[hero_image]', 'תמונת Hero', $s['hero_image'] ); ?>
                    <?php freshm_card_image_field( $n . '[logo]', 'לוגו הלקוח', $s['logo'] ); ?>
                </div>
            </div>

            <!-- Content Sections -->
            <div class="freshm-card-section">
                <h3>תוכן</h3>
                <div class="freshm-content-block">
                    <div class="freshm-field">
                        <label>כותרת אתגר</label>
                        <input type="text" name="<?php echo $n; ?>[challenge_title]" value="<?php echo esc_attr( $s['challenge_title'] ); ?>">
                    </div>
                    <div class="freshm-field freshm-field-wide">
                        <label>תוכן האתגר (HTML מותר)</label>
                        <textarea name="<?php echo $n; ?>[challenge_content]" rows="4"><?php echo esc_textarea( $s['challenge_content'] ); ?></textarea>
                    </div>
                </div>
                <div class="freshm-content-block">
                    <div class="freshm-field">
                        <label>כותרת פתרון</label>
                        <input type="text" name="<?php echo $n; ?>[solution_title]" value="<?php echo esc_attr( $s['solution_title'] ); ?>">
                    </div>
                    <div class="freshm-field freshm-field-wide">
                        <label>תוכן הפתרון (HTML מותר)</label>
                        <textarea name="<?php echo $n; ?>[solution_content]" rows="4"><?php echo esc_textarea( $s['solution_content'] ); ?></textarea>
                    </div>
                </div>
                <div class="freshm-content-block">
                    <div class="freshm-field">
                        <label>כותרת תוצאות</label>
                        <input type="text" name="<?php echo $n; ?>[results_title]" value="<?php echo esc_attr( $s['results_title'] ); ?>">
                    </div>
                    <div class="freshm-field freshm-field-wide">
                        <label>תוכן התוצאות (HTML מותר)</label>
                        <textarea name="<?php echo $n; ?>[results_content]" rows="4"><?php echo esc_textarea( $s['results_content'] ); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Metrics -->
            <div class="freshm-card-section">
                <h3>מדדים (עד 6)</h3>
                <p class="freshm-hint">אחוזים, מכפילים, כמויות, זמנים — ללא סכומים כספיים.</p>
                <div class="freshm-mini-repeater" data-max="6">
                    <div class="freshm-mini-items">
                        <?php
                        if ( ! empty( $s['metrics'] ) ) :
                            foreach ( $s['metrics'] as $mi => $m ) :
                        ?>
                        <div class="freshm-mini-item">
                            <input type="text" name="<?php echo $n; ?>[metrics][<?php echo $mi; ?>][number]" value="<?php echo esc_attr( $m['number'] ); ?>" placeholder="+85%" class="freshm-mini-num">
                            <input type="text" name="<?php echo $n; ?>[metrics][<?php echo $mi; ?>][label]" value="<?php echo esc_attr( $m['label'] ); ?>" placeholder="גידול בהכנסות" class="freshm-mini-label">
                            <button type="button" class="freshm-mini-remove" title="הסר">✕</button>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="button" class="freshm-btn freshm-mini-add" data-name-num="<?php echo $n; ?>[metrics][__MI__][number]" data-name-label="<?php echo $n; ?>[metrics][__MI__][label]">+ הוסף מדד</button>
                </div>
            </div>

            <!-- Quote -->
            <div class="freshm-card-section">
                <h3>ציטוט לקוח</h3>
                <div class="freshm-field freshm-field-wide">
                    <label>טקסט הציטוט</label>
                    <textarea name="<?php echo $n; ?>[quote_text]" rows="2"><?php echo esc_textarea( $s['quote_text'] ); ?></textarea>
                </div>
                <div class="freshm-grid">
                    <div class="freshm-field">
                        <label>שם המצטט</label>
                        <input type="text" name="<?php echo $n; ?>[quote_author]" value="<?php echo esc_attr( $s['quote_author'] ); ?>">
                    </div>
                    <div class="freshm-field">
                        <label>תפקיד</label>
                        <input type="text" name="<?php echo $n; ?>[quote_role]" value="<?php echo esc_attr( $s['quote_role'] ); ?>" placeholder="בעלים, מנכ&quot;ל...">
                    </div>
                </div>
            </div>

            <!-- Media -->
            <div class="freshm-card-section">
                <h3>מדיה</h3>
                <div class="freshm-field">
                    <label>סרטון (YouTube/Vimeo URL)</label>
                    <input type="url" name="<?php echo $n; ?>[video_url]" value="<?php echo esc_url( $s['video_url'] ); ?>" dir="ltr" placeholder="https://www.youtube.com/watch?v=...">
                </div>
                <div class="freshm-field freshm-field-wide">
                    <label>גלריית תמונות</label>
                    <div class="freshm-gallery-repeater">
                        <div class="freshm-gallery-items">
                            <?php if ( ! empty( $s['gallery'] ) ) : foreach ( $s['gallery'] as $gi => $gurl ) : ?>
                            <div class="freshm-gallery-item">
                                <div class="freshm-image-field">
                                    <input type="hidden" name="<?php echo $n; ?>[gallery][<?php echo $gi; ?>]" value="<?php echo esc_url( $gurl ); ?>" class="freshm-image-input">
                                    <div class="freshm-image-preview"><?php if ( $gurl ) echo '<img src="' . esc_url( $gurl ) . '">'; ?></div>
                                    <button type="button" class="freshm-btn freshm-upload-btn">📷</button>
                                    <button type="button" class="freshm-btn freshm-gallery-remove">✕</button>
                                </div>
                            </div>
                            <?php endforeach; endif; ?>
                        </div>
                        <button type="button" class="freshm-btn freshm-gallery-add" data-name="<?php echo $n; ?>[gallery]">+ הוסף תמונה</button>
                    </div>
                </div>
            </div>

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

/* ---------- HELPER: Image field inside card ---------- */
function freshm_card_image_field( $name, $label, $value ) {
    ?>
    <div class="freshm-field">
        <label><?php echo esc_html( $label ); ?></label>
        <div class="freshm-image-field">
            <input type="hidden" name="<?php echo $name; ?>" value="<?php echo esc_attr( $value ); ?>" class="freshm-image-input">
            <div class="freshm-image-preview"><?php if ( $value ) echo '<img src="' . esc_url( $value ) . '">'; ?></div>
            <button type="button" class="freshm-btn freshm-upload-btn">📷 בחר</button>
            <button type="button" class="freshm-btn freshm-remove-btn" <?php echo $value ? '' : 'style="display:none"'; ?>>✕</button>
        </div>
    </div>
    <?php
}
