<?php
/**
 * FRESH Theme — The Culinary Edge
 * שיווק דיגיטלי למסעדות
 *
 * @package Fresh_Custom_Theme
 * @version 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

define( 'FRESH_VERSION', '1.0.0' );
define( 'FRESH_DIR', get_template_directory() );
define( 'FRESH_URI', get_template_directory_uri() );

/* -------------------------------------------------------
 * 1. Theme Setup
 * ----------------------------------------------------- */
function fresh_setup() {
    load_theme_textdomain( 'fresh-theme', FRESH_DIR . '/languages' );

    add_theme_support( 'title-tag' );
    add_theme_support( 'post-thumbnails' );
    add_theme_support( 'html5', [
        'search-form', 'comment-form', 'comment-list',
        'gallery', 'caption', 'style', 'script',
    ]);
    add_theme_support( 'custom-logo', [
        'height'      => 60,
        'width'       => 200,
        'flex-height' => true,
        'flex-width'  => true,
    ]);
    add_theme_support( 'editor-styles' );
    add_editor_style( 'assets/css/editor-style.css' );
    add_theme_support( 'responsive-embeds' );
    add_theme_support( 'align-wide' );
    add_theme_support( 'wp-block-styles' );

    // Custom image sizes
    add_image_size( 'fresh-hero',    1920, 1080, true );
    add_image_size( 'fresh-card',    600,  400,  true );
    add_image_size( 'fresh-case',    800,  560,  true );
    add_image_size( 'fresh-thumb',   300,  200,  true );

    // Menus
    register_nav_menus( [
        'primary' => __( 'תפריט ראשי', 'fresh-theme' ),
        'footer'  => __( 'תפריט פוטר', 'fresh-theme' ),
    ]);
}
add_action( 'after_setup_theme', 'fresh_setup' );


/* -------------------------------------------------------
 * 2. Assets (CSS + JS)
 * ----------------------------------------------------- */
function fresh_enqueue() {
    // Fonts: Secular One (display), Heebo (heading), Assistant (body), IBM Plex Mono
    wp_enqueue_style( 'fresh-fonts',
        'https://fonts.googleapis.com/css2?family=Assistant:wght@300;400;500;600;700&family=Heebo:wght@400;500;600;700;800;900&family=IBM+Plex+Mono:wght@400;500&family=Secular+One&display=swap',
        [], null
    );

    wp_enqueue_style( 'fresh-style', get_stylesheet_uri(), [ 'fresh-fonts' ], FRESH_VERSION );

    wp_enqueue_script( 'fresh-main',
        FRESH_URI . '/assets/js/main.js',
        [], FRESH_VERSION, true
    );

    wp_localize_script( 'fresh-main', 'freshTheme', [
        'ajax'  => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'fresh_nonce' ),
    ]);
}
add_action( 'wp_enqueue_scripts', 'fresh_enqueue' );


/* -------------------------------------------------------
 * 3. Custom Post Type: Case Studies
 * ----------------------------------------------------- */
function fresh_register_cpt() {
    // --- Case Studies ---
    register_post_type( 'fresh_case_study', [
        'labels' => [
            'name'               => __( 'קייס סטאדי', 'fresh-theme' ),
            'singular_name'      => __( 'קייס סטאדי', 'fresh-theme' ),
            'add_new'            => __( 'הוסף קייס חדש', 'fresh-theme' ),
            'add_new_item'       => __( 'הוסף קייס סטאדי חדש', 'fresh-theme' ),
            'edit_item'          => __( 'ערוך קייס סטאדי', 'fresh-theme' ),
            'view_item'          => __( 'צפה בקייס סטאדי', 'fresh-theme' ),
            'all_items'          => __( 'כל הקייסים', 'fresh-theme' ),
            'search_items'       => __( 'חפש קייס סטאדי', 'fresh-theme' ),
            'not_found'          => __( 'לא נמצאו קייסים', 'fresh-theme' ),
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => [ 'slug' => 'case-studies' ],
        'menu_icon'    => 'dashicons-awards',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ],
        'show_in_rest' => true,
        'template' => [
            [ 'core/paragraph', [ 'placeholder' => 'תיאור הפרויקט...' ] ],
        ],
    ]);

    // Case Study Category Taxonomy
    register_taxonomy( 'case_category', 'fresh_case_study', [
        'labels' => [
            'name'          => __( 'קטגוריות קייס', 'fresh-theme' ),
            'singular_name' => __( 'קטגוריית קייס', 'fresh-theme' ),
            'add_new_item'  => __( 'הוסף קטגוריה', 'fresh-theme' ),
        ],
        'public'       => true,
        'hierarchical' => true,
        'rewrite'      => [ 'slug' => 'case-category' ],
        'show_in_rest' => true,
    ]);

    // --- Services ---
    register_post_type( 'fresh_service', [
        'labels' => [
            'name'               => __( 'שירותים', 'fresh-theme' ),
            'singular_name'      => __( 'שירות', 'fresh-theme' ),
            'add_new'            => __( 'הוסף שירות', 'fresh-theme' ),
            'add_new_item'       => __( 'הוסף שירות חדש', 'fresh-theme' ),
            'edit_item'          => __( 'ערוך שירות', 'fresh-theme' ),
            'all_items'          => __( 'כל השירותים', 'fresh-theme' ),
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => [ 'slug' => 'services' ],
        'menu_icon'    => 'dashicons-hammer',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt', 'page-attributes' ],
        'show_in_rest' => true,
    ]);
}
add_action( 'init', 'fresh_register_cpt' );


/* -------------------------------------------------------
 * 4. Custom Meta Boxes for Case Studies
 * ----------------------------------------------------- */
function fresh_register_meta() {
    // Key metric number (e.g. "+340%")
    register_post_meta( 'fresh_case_study', '_fresh_metric_number', [
        'show_in_rest'  => true,
        'single'        => true,
        'type'          => 'string',
        'auth_callback' => function() { return current_user_can( 'edit_posts' ); },
    ]);

    // Key metric label (e.g. "גידול בהזמנות")
    register_post_meta( 'fresh_case_study', '_fresh_metric_label', [
        'show_in_rest'  => true,
        'single'        => true,
        'type'          => 'string',
        'auth_callback' => function() { return current_user_can( 'edit_posts' ); },
    ]);

    // Service icon (emoji or dashicon class)
    register_post_meta( 'fresh_service', '_fresh_service_icon', [
        'show_in_rest'  => true,
        'single'        => true,
        'type'          => 'string',
        'default'       => '🎯',
        'auth_callback' => function() { return current_user_can( 'edit_posts' ); },
    ]);
}
add_action( 'init', 'fresh_register_meta' );

// Classic meta box UI for Case Studies
function fresh_case_study_meta_box() {
    add_meta_box(
        'fresh_case_metrics',
        __( 'מדד הצלחה ראשי', 'fresh-theme' ),
        'fresh_case_metrics_callback',
        'fresh_case_study',
        'side'
    );
}
add_action( 'add_meta_boxes', 'fresh_case_study_meta_box' );

function fresh_case_metrics_callback( $post ) {
    wp_nonce_field( 'fresh_case_meta', 'fresh_case_nonce' );
    $number = get_post_meta( $post->ID, '_fresh_metric_number', true );
    $label  = get_post_meta( $post->ID, '_fresh_metric_label', true );
    ?>
    <p>
        <label for="fresh_metric_number"><strong>מספר (לדוג' +340%)</strong></label><br>
        <input type="text" id="fresh_metric_number" name="fresh_metric_number"
               value="<?php echo esc_attr( $number ); ?>" style="width:100%;">
    </p>
    <p>
        <label for="fresh_metric_label"><strong>תיאור (לדוג' גידול בהזמנות)</strong></label><br>
        <input type="text" id="fresh_metric_label" name="fresh_metric_label"
               value="<?php echo esc_attr( $label ); ?>" style="width:100%;">
    </p>
    <?php
}

function fresh_save_case_meta( $post_id ) {
    if ( ! isset( $_POST['fresh_case_nonce'] ) || ! wp_verify_nonce( $_POST['fresh_case_nonce'], 'fresh_case_meta' ) ) return;
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    if ( isset( $_POST['fresh_metric_number'] ) ) {
        update_post_meta( $post_id, '_fresh_metric_number', sanitize_text_field( $_POST['fresh_metric_number'] ) );
    }
    if ( isset( $_POST['fresh_metric_label'] ) ) {
        update_post_meta( $post_id, '_fresh_metric_label', sanitize_text_field( $_POST['fresh_metric_label'] ) );
    }
}
add_action( 'save_post_fresh_case_study', 'fresh_save_case_meta' );


/* -------------------------------------------------------
 * 5. Block Patterns
 * ----------------------------------------------------- */
function fresh_register_block_patterns() {
    // Register pattern category
    register_block_pattern_category( 'fresh-theme', [
        'label' => __( 'FRESH — The Culinary Edge', 'fresh-theme' ),
    ]);

    // Load patterns from files
    $patterns_dir = FRESH_DIR . '/block-patterns/';
    $pattern_files = [
        'hero'     => [
            'title'       => __( 'FRESH — Hero Section', 'fresh-theme' ),
            'description' => __( 'סקשן Hero ראשי עם כותרת וכפתור CTA', 'fresh-theme' ),
            'categories'  => [ 'fresh-theme', 'featured' ],
            'keywords'    => [ 'hero', 'banner', 'fresh' ],
        ],
        'services' => [
            'title'       => __( 'FRESH — שירותים (3 עמודות)', 'fresh-theme' ),
            'description' => __( 'רשת שירותים עם אייקונים וטקסט', 'fresh-theme' ),
            'categories'  => [ 'fresh-theme' ],
            'keywords'    => [ 'services', 'grid', 'fresh' ],
        ],
        'stats'    => [
            'title'       => __( 'FRESH — בר סטטיסטיקות', 'fresh-theme' ),
            'description' => __( 'מספרים מרשימים ברוחב מלא', 'fresh-theme' ),
            'categories'  => [ 'fresh-theme' ],
            'keywords'    => [ 'stats', 'numbers', 'fresh' ],
        ],
        'cta'      => [
            'title'       => __( 'FRESH — Call to Action', 'fresh-theme' ),
            'description' => __( 'סקשן קריאה לפעולה', 'fresh-theme' ),
            'categories'  => [ 'fresh-theme' ],
            'keywords'    => [ 'cta', 'contact', 'fresh' ],
        ],
        'about'    => [
            'title'       => __( 'FRESH — אודות (פיצול)', 'fresh-theme' ),
            'description' => __( 'סקשן אודות עם תמונה וטקסט', 'fresh-theme' ),
            'categories'  => [ 'fresh-theme' ],
            'keywords'    => [ 'about', 'split', 'fresh' ],
        ],
    ];

    foreach ( $pattern_files as $slug => $meta ) {
        $file = $patterns_dir . $slug . '.php';
        if ( file_exists( $file ) ) {
            ob_start();
            include $file;
            $content = ob_get_clean();

            register_block_pattern( "fresh/{$slug}", array_merge( $meta, [
                'content' => $content,
            ]));
        }
    }
}
add_action( 'init', 'fresh_register_block_patterns' );


/* -------------------------------------------------------
 * 6. Widgets
 * ----------------------------------------------------- */
function fresh_widgets() {
    register_sidebar( [
        'name'          => __( 'פוטר עמודה 1', 'fresh-theme' ),
        'id'            => 'footer-1',
        'before_widget' => '<div class="footer-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h4 class="footer__heading">',
        'after_title'   => '</h4>',
    ]);

    register_sidebar( [
        'name'          => __( 'פוטר עמודה 2', 'fresh-theme' ),
        'id'            => 'footer-2',
        'before_widget' => '<div class="footer-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h4 class="footer__heading">',
        'after_title'   => '</h4>',
    ]);

    register_sidebar( [
        'name'          => __( 'פוטר עמודה 3', 'fresh-theme' ),
        'id'            => 'footer-3',
        'before_widget' => '<div class="footer-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h4 class="footer__heading">',
        'after_title'   => '</h4>',
    ]);
}
add_action( 'widgets_init', 'fresh_widgets' );


/* -------------------------------------------------------
 * 7. AJAX Contact Form
 * ----------------------------------------------------- */
function fresh_contact_handler() {
    check_ajax_referer( 'fresh_nonce', 'nonce' );

    $name    = sanitize_text_field( $_POST['name'] ?? '' );
    $email   = sanitize_email( $_POST['email'] ?? '' );
    $phone   = sanitize_text_field( $_POST['phone'] ?? '' );
    $biz     = sanitize_text_field( $_POST['business'] ?? '' );
    $message = sanitize_textarea_field( $_POST['message'] ?? '' );

    if ( empty( $name ) || empty( $phone ) ) {
        wp_send_json_error( [ 'message' => 'נא למלא שם וטלפון' ] );
    }

    $to      = get_option( 'admin_email' );
    $subject = "FRESH — פנייה חדשה מ-{$name}";
    $body    = "שם: {$name}\nטלפון: {$phone}\nאימייל: {$email}\nעסק: {$biz}\n\nהודעה:\n{$message}";
    $headers = [ 'Content-Type: text/plain; charset=UTF-8' ];

    wp_mail( $to, $subject, $body, $headers );
    wp_send_json_success( [ 'message' => 'תודה! נחזור אליך תוך 24 שעות.' ] );
}
add_action( 'wp_ajax_fresh_contact', 'fresh_contact_handler' );
add_action( 'wp_ajax_nopriv_fresh_contact', 'fresh_contact_handler' );


/* -------------------------------------------------------
 * 8. Performance & Cleanup
 * ----------------------------------------------------- */
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );

// Remove emoji scripts
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

// Disable XML-RPC
add_filter( 'xmlrpc_enabled', '__return_false' );

// Excerpt length
add_filter( 'excerpt_length', function() { return 20; } );
add_filter( 'excerpt_more', function() { return '...'; } );


/* -------------------------------------------------------
 * 9. Body Classes
 * ----------------------------------------------------- */
function fresh_body_class( $classes ) {
    $classes[] = 'fresh-theme';
    if ( is_front_page() ) $classes[] = 'is-front';
    return $classes;
}
add_filter( 'body_class', 'fresh_body_class' );


/* -------------------------------------------------------
 * 10. Custom Nav Walker (for knife-cut styled nav)
 * ----------------------------------------------------- */
class Fresh_Nav_Walker extends Walker_Nav_Menu {
    function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
        $classes = implode( ' ', $item->classes ?? [] );
        $active  = in_array( 'current-menu-item', $item->classes ?? [] ) ? ' is-active' : '';

        $output .= '<li class="' . esc_attr( $classes ) . '">';
        $output .= '<a href="' . esc_url( $item->url ) . '" class="main-nav__link' . $active . '">';
        $output .= esc_html( $item->title );
        $output .= '</a>';
    }
}

/* -------------------------------------------------------
 * 11. Flush rewrite on activation
 * ----------------------------------------------------- */
function fresh_activate() {
    fresh_register_cpt();
    flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'fresh_activate' );
