<?php
/**
 * Iliya theme functions.
 *
 * Persian (RTL) content/corporate theme. Tailwind v4 + Motion (motion.dev).
 *
 * @package Iliya
 */

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

define('ILIYA_VERSION', '1.0.0');

// Dynamic content: services/projects CPTs, site-settings page, one-time seeding.
require_once get_template_directory() . '/inc/cpt.php';
require_once get_template_directory() . '/inc/settings.php';
require_once get_template_directory() . '/inc/seed.php';

/**
 * Theme setup.
 */
function iliya_setup() {
    load_theme_textdomain('iliya', get_template_directory() . '/languages');

    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo', [
        'height'      => 120,
        'width'       => 120,
        'flex-height' => true,
        'flex-width'  => true,
    ]);
    add_theme_support('automatic-feed-links');
    add_theme_support('customize-selective-refresh-widgets');
    add_theme_support('html5', [
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
        'style',
        'script',
    ]);

    register_nav_menus([
        'primary' => __('منوی اصلی', 'iliya'),
        'footer'  => __('منوی فوتر', 'iliya'),
    ]);
}
add_action('after_setup_theme', 'iliya_setup');

/**
 * Content width.
 */
function iliya_content_width() {
    $GLOBALS['content_width'] = 1200;
}
add_action('after_setup_theme', 'iliya_content_width', 0);

/**
 * Enqueue styles and scripts.
 */
function iliya_assets() {
    $dir = get_template_directory();
    $uri = get_template_directory_uri();

    // Compiled Tailwind CSS.
    $css = $dir . '/assets/css/dist.css';
    wp_enqueue_style(
        'iliya-tailwind',
        $uri . '/assets/css/dist.css',
        [],
        file_exists($css) ? filemtime($css) : ILIYA_VERSION
    );

    // Bundled JS (Motion + theme behavior), IIFE — loads in footer.
    $js = $dir . '/assets/js/dist.js';
    if (file_exists($js)) {
        wp_enqueue_script(
            'iliya-app',
            $uri . '/assets/js/dist.js',
            [],
            filemtime($js),
            true
        );
        wp_localize_script('iliya-app', 'iliya', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('iliya_nonce'),
            'isHome'  => is_front_page(),
        ]);
    }

    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}
add_action('wp_enqueue_scripts', 'iliya_assets');

/**
 * Preload fonts for faster first paint.
 */
function iliya_preload_fonts() {
    $uri = get_template_directory_uri();
    printf(
        '<link rel="preload" href="%s/assets/fonts/AzarMehr-FD-Variable.woff2" as="font" type="font/woff2" crossorigin>' . "\n",
        esc_url($uri)
    );
}
add_action('wp_head', 'iliya_preload_fonts', 1);

/**
 * Preload the cinematic hero image on the front page (LCP).
 */
function iliya_preload_hero() {
    if (! is_front_page()) {
        return;
    }
    printf(
        '<link rel="preload" as="image" href="%s/assets/images/hero-steel.webp" fetchpriority="high">' . "\n",
        esc_url(get_template_directory_uri())
    );
}
add_action('wp_head', 'iliya_preload_hero', 1);

/**
 * Use the brand body font (AzarMehr) across the wp-admin dashboard.
 * No `*` selectors — dashicons (icon font) and code blocks stay intact via
 * their own rules / inheritance.
 */
function iliya_admin_font() {
    $url = get_template_directory_uri() . '/assets/fonts/AzarMehr-FD-Variable.woff2';
    ?>
    <style id="iliya-admin-font">
        @font-face {
            font-family: "AzarMehr";
            src: url("<?php echo esc_url($url); ?>") format("woff2");
            font-weight: 100 900;
            font-style: normal;
            font-display: swap;
        }
        body.wp-admin, #wpwrap, #wpadminbar, #adminmenu, #adminmenu a,
        .wp-core-ui, .wp-core-ui .button, .wp-heading-inline, .wrap,
        input, select, textarea, button, .wp-editor-area, .media-frame {
            font-family: "AzarMehr", Tahoma, Arial, sans-serif !important;
        }
        .dashicons, .dashicons-before:before,
        [class^="dashicons-"]:before, [class*=" dashicons-"]:before {
            font-family: "dashicons" !important;
        }
        code, kbd, pre, .code, textarea.code {
            font-family: Consolas, Monaco, "Courier New", monospace !important;
        }
    </style>
    <?php
}
add_action('admin_head', 'iliya_admin_font');

/**
 * Sidebar / widget areas.
 */
function iliya_widgets_init() {
    register_sidebar([
        'name'          => __('ساید‌بار', 'iliya'),
        'id'            => 'sidebar-1',
        'description'   => __('ویجت‌های ستون کناری', 'iliya'),
        'before_widget' => '<section id="%1$s" class="widget %2$s mb-8">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title mb-4 text-lg font-bold text-dark">',
        'after_title'   => '</h3>',
    ]);

    register_sidebar([
        'name'          => __('فوتر', 'iliya'),
        'id'            => 'footer-1',
        'description'   => __('ویجت‌های فوتر', 'iliya'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title mb-4 text-base font-bold text-white">',
        'after_title'   => '</h4>',
    ]);
}
add_action('widgets_init', 'iliya_widgets_init');

/**
 * Excerpt tweaks.
 */
function iliya_excerpt_length($length) {
    return 28;
}
add_filter('excerpt_length', 'iliya_excerpt_length');

function iliya_excerpt_more($more) {
    return ' …';
}
add_filter('excerpt_more', 'iliya_excerpt_more');

/**
 * Body classes.
 */
function iliya_body_classes($classes) {
    if (! is_singular()) {
        $classes[] = 'hfeed';
    }
    return $classes;
}
add_filter('body_class', 'iliya_body_classes');

/**
 * Default section nav used when no `primary` menu is assigned.
 * Points at homepage section anchors (corporate one-page layout).
 *
 * @param string $class Optional <ul> class override.
 */
function iliya_default_nav($class = 'flex items-center gap-8 text-sm font-medium text-steel-700') {
    $home = home_url('/');
    $items = [
        '#hero'     => __('خانه', 'iliya'),
        '#about'    => __('درباره ما', 'iliya'),
        '#services' => __('خدمات', 'iliya'),
        '#projects' => __('نمونه کارها', 'iliya'),
        '#contact'  => __('تماس با ما', 'iliya'),
    ];
    echo '<ul class="' . esc_attr($class) . '">';
    foreach ($items as $anchor => $label) {
        printf(
            '<li><a href="%s" class="relative transition-colors hover:text-accent">%s</a></li>',
            esc_url($home . $anchor),
            esc_html($label)
        );
    }
    echo '</ul>';
}

/**
 * Inline SVG icon helper. Add icons to the map as the design needs them.
 * Usage: iliya_icon('menu', 24, 'text-dark');
 */
function iliya_icon($name, $size = 24, $class = '') {
    // Brand logos kept as full SVG files (custom viewBoxes) — a file wins when present.
    // To enable rubika, drop its real logo at assets/images/social/rubika.svg.
    static $brand = ['bale', 'eitaa', 'rubika'];
    static $brand_cache = [];
    if (in_array($name, $brand, true)) {
        if (! array_key_exists($name, $brand_cache)) {
            $f = get_template_directory() . '/assets/images/social/' . $name . '.svg';
            $brand_cache[$name] = is_readable($f) ? file_get_contents($f) : '';
        }
        if ($brand_cache[$name] !== '') {
            return preg_replace(
                '/<svg /',
                sprintf('<svg class="%s" width="%d" height="%d" aria-hidden="true" focusable="false" ', esc_attr($class), (int) $size, (int) $size),
                $brand_cache[$name],
                1
            );
        }
        // No file yet (e.g. rubika) → fall through to the inline placeholder below.
    }

    static $icons = [
        // UI
        'menu'     => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-width="1.8" d="M4 7h16M4 12h16M4 17h16"/>',
        'close'    => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-width="1.8" d="M6 6l12 12M18 6L6 18"/>',
        'search'   => '<g fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="7"/><path stroke-linecap="round" d="m20 20l-3-3"/></g>',
        'chevron-start' => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M9 18l6-6l-6-6"/>',
        'chevron-end'   => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M15 18l-6-6l6-6"/>',
        'arrow-up'      => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 19V5M5 12l7-7l7 7"/>',
        'arrow-up-left' => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M17 17L7 7M7 17V7h10"/>',
        'arrow-start'   => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M19 12H5m7-7l-7 7l7 7"/>',
        'plus'          => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-width="1.8" d="M12 5v14M5 12h14"/>',
        'check'         => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>',

        // Services / industrial
        'recycle'  => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M7 19H4.8c-1.4 0-2.1-1.5-1.4-2.7L4.9 13"/><path d="m9 22l-2-3l3-2"/><path d="M10.1 4.5L8.9 6.6m6-3.6l1.9 3.2c.7 1.2 0 2.7-1.4 2.7H12"/><path d="m18 7l1 3.5l-3 .5"/><path d="M14 19h4.3c1.4 0 2.1-1.5 1.4-2.7l-1.1-1.8"/><path d="M9.6 4.6L7.7 8c-.7 1.2 0 2.7 1.4 2.7"/></g>',
        'crane'    => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M3 21h18"/><path d="M5 21V8l14-3v4"/><path d="M5 8l14-3"/><path d="M9 21v-6h4v6"/><path d="M19 9v5"/><path d="M17 14h4"/></g>',
        'bolt'     => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M13 2L4.5 13.5H11l-1 8.5L18.5 10H12z"/>',
        'structure'=> '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M3 21h18M5 21V5h14v16"/><path d="M5 5l14 16M19 5L5 21M5 13h14"/></g>',
        'leaf'     => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8c0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6"/></g>',
        'globe'    => '<g fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18"/></g>',
        'shield'   => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M12 22s8-4 8-10V5l-8-3l-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2l4-4"/></g>',
        'medal'    => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><circle cx="12" cy="15" r="5"/><path d="M12 13.5v3l1.5.9M8.2 10L6 2m9.8 8L18 2M9.5 3.5L12 7l2.5-3.5"/></g>',
        'clock'    => '<g fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="9"/><path stroke-linecap="round" d="M12 7v5l3 2"/></g>',
        'users'    => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13A4 4 0 0 1 16 11"/></g>',

        // Contact
        'phone'    => '<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M22 16.92v3a2 2 0 0 1-2.18 2a19.8 19.8 0 0 1-8.63-3.07a19.5 19.5 0 0 1-6-6a19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>',
        'mail'     => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><rect x="3" y="5" width="18" height="14"/><path d="m3 6l9 6l9-6"/></g>',
        'location' => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></g>',
        'id'       => '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="11" r="2"/><path d="M5.5 16.5c.6-1.5 1.7-2.2 3-2.2s2.4.7 3 2.2M14 9.5h4M14 13h4M14 16h2.5"/></g>',
        'whatsapp' => '<path fill="currentColor" d="M12.04 2c-5.46 0-9.91 4.45-9.91 9.91c0 1.75.46 3.45 1.32 4.95L2.05 22l5.25-1.38c1.45.79 3.08 1.21 4.74 1.21c5.46 0 9.91-4.45 9.91-9.91S17.5 2 12.04 2zm5.8 14.01c-.24.68-1.42 1.31-1.96 1.36c-.5.05-1.14.21-3.69-.77c-3.1-1.22-5.08-4.42-5.24-4.63c-.15-.21-1.26-1.67-1.26-3.19s.8-2.27 1.08-2.58c.28-.31.61-.39.81-.39c.2 0 .41 0 .58.01c.19.01.44-.07.69.53c.24.6.83 2.07.9 2.22c.07.15.12.32.02.53c-.1.21-.15.34-.3.52c-.15.18-.31.4-.45.54c-.15.15-.3.31-.13.6c.17.29.76 1.25 1.63 2.03c1.12 1 2.07 1.31 2.36 1.46c.29.15.46.12.63-.07c.17-.2.73-.85.92-1.14c.19-.29.39-.24.65-.15c.27.1 1.71.81 2 .96c.29.15.49.22.56.34c.07.12.07.72-.17 1.4z"/>',
        'telegram' => '<path fill="currentColor" d="M22 4.5L2.5 12l5.3 1.7L19 6.5l-8.5 8.3l-.3 4.2l2.6-2.5l4.4 3.2z"/>',
        'instagram'=> '<g fill="none" stroke="currentColor" stroke-width="1.6"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></g>',
        // bale + eitaa come from assets/images/social/*.svg (real brand logos).
        // rubika placeholder until its real logo file is supplied:
        'rubika'   => '<g fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="17" height="17" rx="5.5"/><path d="M9 16.5V8h3.2a2.4 2.4 0 0 1 0 4.8H9m3.6 0l2.6 3.7"/></g>',
    ];
    if (! isset($icons[$name])) {
        return '';
    }
    return sprintf(
        '<svg class="%s" width="%d" height="%d" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">%s</svg>',
        esc_attr($class),
        (int) $size,
        (int) $size,
        $icons[$name]
    );
}

/* ──────────────────────────────────────────────────────────────────────────
 * Contact form — store submissions as a private CPT, viewable in wp-admin.
 * No email; messages live under «پیام‌های تماس» in the dashboard.
 * ────────────────────────────────────────────────────────────────────────── */

/** Register the contact-message post type. */
function iliya_register_messages_cpt() {
    register_post_type('iliya_message', [
        'labels' => [
            'name'          => 'پیام‌های تماس',
            'singular_name' => 'پیام',
            'menu_name'     => 'پیام‌های تماس',
            'all_items'     => 'همه پیام‌ها',
            'edit_item'     => 'مشاهده پیام',
            'view_item'     => 'مشاهده پیام',
            'search_items'  => 'جستجوی پیام‌ها',
            'not_found'     => 'پیامی یافت نشد',
            'not_found_in_trash' => 'پیامی در زباله‌دان نیست',
        ],
        'public'              => false,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 26,
        'menu_icon'           => 'dashicons-email-alt',
        'supports'            => ['title'],
        'capability_type'     => 'post',
        'map_meta_cap'        => true,
        'capabilities'        => ['create_posts' => 'do_not_allow'], // form-only, no manual add
        'exclude_from_search' => true,
        'has_archive'         => false,
        'rewrite'             => false,
    ]);
}
add_action('init', 'iliya_register_messages_cpt');

/** Handle the AJAX contact submission (logged-in + anonymous). */
function iliya_handle_contact() {
    check_ajax_referer('iliya_nonce', 'nonce');

    // Honeypot: bots fill the hidden field — pretend success, store nothing.
    if (! empty($_POST['website'])) {
        wp_send_json_success(['message' => 'پیام شما با موفقیت ارسال شد. به‌زودی با شما تماس می‌گیریم.']);
    }

    $name    = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));
    $phone   = sanitize_text_field(wp_unslash($_POST['phone'] ?? ''));
    $subject = sanitize_text_field(wp_unslash($_POST['subject'] ?? ''));
    $message = sanitize_textarea_field(wp_unslash($_POST['message'] ?? ''));

    if ($name === '' || $phone === '' || $message === '') {
        wp_send_json_error(['message' => 'لطفاً نام، شماره تماس و پیام را کامل وارد کنید.'], 422);
    }

    $post_id = wp_insert_post([
        'post_type'    => 'iliya_message',
        'post_status'  => 'publish',
        'post_title'   => $name . ($subject !== '' ? ' — ' . $subject : ''),
        'post_content' => $message,
    ], true);

    if (is_wp_error($post_id)) {
        wp_send_json_error(['message' => 'خطا در ثبت پیام. لطفاً دوباره تلاش کنید.'], 500);
    }

    update_post_meta($post_id, '_iliya_name', $name);
    update_post_meta($post_id, '_iliya_phone', $phone);
    update_post_meta($post_id, '_iliya_subject', $subject);
    update_post_meta($post_id, '_iliya_ip', sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'] ?? '')));

    wp_send_json_success(['message' => 'پیام شما با موفقیت ارسال شد. به‌زودی با شما تماس می‌گیریم.']);
}
add_action('wp_ajax_iliya_contact', 'iliya_handle_contact');
add_action('wp_ajax_nopriv_iliya_contact', 'iliya_handle_contact');

/** Admin list columns. */
function iliya_message_columns($cols) {
    return [
        'cb'            => $cols['cb'] ?? '<input type="checkbox" />',
        'title'         => 'فرستنده / موضوع',
        'iliya_phone'   => 'شماره تماس',
        'iliya_excerpt' => 'پیام',
        'date'          => 'تاریخ',
    ];
}
add_filter('manage_iliya_message_posts_columns', 'iliya_message_columns');

function iliya_message_column_content($col, $post_id) {
    if ($col === 'iliya_phone') {
        echo '<span dir="ltr">' . esc_html(get_post_meta($post_id, '_iliya_phone', true)) . '</span>';
    } elseif ($col === 'iliya_excerpt') {
        echo esc_html(wp_trim_words(get_post_field('post_content', $post_id), 14));
    }
}
add_action('manage_iliya_message_posts_custom_column', 'iliya_message_column_content', 10, 2);

/** Read-only detail meta box. */
function iliya_message_metabox() {
    add_meta_box('iliya_message_detail', 'جزئیات پیام', 'iliya_message_metabox_render', 'iliya_message', 'normal', 'high');
}
add_action('add_meta_boxes', 'iliya_message_metabox');

function iliya_message_metabox_render($post) {
    $name    = get_post_meta($post->ID, '_iliya_name', true);
    $phone   = get_post_meta($post->ID, '_iliya_phone', true);
    $subject = get_post_meta($post->ID, '_iliya_subject', true);
    $ip      = get_post_meta($post->ID, '_iliya_ip', true);
    echo '<table class="widefat striped" style="margin-top:8px"><tbody>';
    printf('<tr><th style="width:160px">نام</th><td>%s</td></tr>', esc_html($name));
    printf('<tr><th>شماره تماس</th><td dir="ltr">%s</td></tr>', esc_html($phone));
    printf('<tr><th>موضوع</th><td>%s</td></tr>', esc_html($subject !== '' ? $subject : '—'));
    printf('<tr><th>پیام</th><td>%s</td></tr>', nl2br(esc_html($post->post_content)));
    printf('<tr><th>IP</th><td dir="ltr">%s</td></tr>', esc_html($ip !== '' ? $ip : '—'));
    echo '</tbody></table>';
}
