<?php
/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 *
 * Retrieving the values:
 * Reading Time = get_post_meta( get_the_ID(), 'textdomain_reading-time', true )
 */
class posts_advanced_options {
    private $config = '{"title":"تنظیمات","prefix":"'.TEXT_DOMAIN.'_options","domain":"'.TEXT_DOMAIN.'","class_name":"advanced_options","post-type":["post"],"context":"normal","priority":"default","fields":[{"type":"text","label":"تعداد دقیقه مطالعه","id":"'.TEXT_DOMAIN.'_reading-time"},'.
    '{"type":"checkbox","label":"مقاله ویژه","id":"'.TEXT_DOMAIN.'_featured","description":"با فعال سازی این گزینه، نوشته در اسلایدر ویژه برگه وبلاگ نمایش داده خواهد شد."}]}';

    public function __construct() {
        $this->config = json_decode( $this->config, true );
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'admin_head', [ $this, 'admin_head' ] );
        add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function add_meta_boxes() {
        foreach ( $this->config['post-type'] as $screen ) {
            add_meta_box(
                sanitize_title( $this->config['title'] ),
                $this->config['title'],
                [ $this, 'add_meta_box_callback' ],
                $screen,
                $this->config['context'],
                $this->config['priority']
            );
        }
    }

    public function admin_head() {
        global $typenow;
        if ( in_array( $typenow, $this->config['post-type'] ) ) {
            ?><style>.rwp-checkbox-label {
                    display: block;
                }</style><?php
        }
    }

    public function save_post( $post_id ) {
        foreach ( $this->config['fields'] as $field ) {
            switch ( $field['type'] ) {
                case 'checkbox':
                    update_post_meta( $post_id, $field['id'], isset( $_POST[ $field['id'] ] ) ? $_POST[ $field['id'] ] : '' );
                    break;
                default:
                    if ( isset( $_POST[ $field['id'] ] ) ) {
                        $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
                        update_post_meta( $post_id, $field['id'], $sanitized );
                    }
            }
        }
    }

    public function add_meta_box_callback() {
        $this->fields_table();
    }

    private function fields_table() {
        ?><table class="form-table" role="presentation">
        <tbody><?php
        foreach ( $this->config['fields'] as $field ) {
            ?><tr>
            <th scope="row"><?php $this->label( $field ); ?></th>
            <td><?php $this->field( $field ); ?></td>
            </tr><?php
        }
        ?></tbody>
        </table><?php
    }

    private function label( $field ) {
        switch ( $field['type'] ) {
            default:
                printf(
                    '<label class="" for="%s">%s</label>',
                    $field['id'], $field['label']
                );
        }
    }

    private function field( $field ) {
        switch ( $field['type'] ) {
            case 'checkbox':
                $this->checkbox( $field );
                break;
            default:
                $this->input( $field );
        }
    }

    private function checkbox( $field ) {
        printf(
            '<label class="rwp-checkbox-label"><input %s id="%s" name="%s" type="checkbox"> %s</label>',
            $this->checked( $field ),
            $field['id'], $field['id'],
            isset( $field['description'] ) ? $field['description'] : ''
        );
    }

    private function input( $field ) {
        printf(
            '<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
            isset( $field['class'] ) ? $field['class'] : '',
            $field['id'], $field['id'],
            isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
            $field['type'],
            $this->value( $field )
        );
    }

    private function value( $field ) {
        global $post;
        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
            $value = get_post_meta( $post->ID, $field['id'], true );
        } else if ( isset( $field['default'] ) ) {
            $value = $field['default'];
        } else {
            return '';
        }
        return str_replace( '\u0027', "'", $value );
    }

    private function checked( $field ) {
        global $post;
        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
            $value = get_post_meta( $post->ID, $field['id'], true );
            if ( $value === 'on' ) {
                return 'checked';
            }
            return '';
        } else if ( isset( $field['checked'] ) ) {
            return 'checked';
        }
        return '';
    }
}
new posts_advanced_options;


/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 *
 * Retrieving the values:
 * name = get_post_meta( get_the_ID(), 'textdomain_name', true )
 * title = get_post_meta( get_the_ID(), 'textdomain_specialty', true )
 * text = get_post_meta( get_the_ID(), 'textdomain_text', true )
 */
class feedbacks_advanced_options {
    private $config = '{"title":"تنظیمات","prefix":"'.TEXT_DOMAIN.'_","domain":"'.TEXT_DOMAIN.'","class_name":"advanced_options","post-type":[],"context":"normal","priority":"default","cpt":"feedbacks","fields":[{"type":"text","label":"نام","id":"'.TEXT_DOMAIN.'_name"},{"type":"text","label":"عنوان","id":"'.TEXT_DOMAIN.'_specialty"},{"type":"textarea","label":"متن","rows":"3","id":"'.TEXT_DOMAIN.'_text"}]}';

    public function __construct() {
        $this->config = json_decode( $this->config, true );
        $this->process_cpts();
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function process_cpts() {
        if ( !empty( $this->config['cpt'] ) ) {
            if ( empty( $this->config['post-type'] ) ) {
                $this->config['post-type'] = [];
            }
            $parts = explode( ',', $this->config['cpt'] );
            $parts = array_map( 'trim', $parts );
            $this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
        }
    }

    public function add_meta_boxes() {
        foreach ( $this->config['post-type'] as $screen ) {
            add_meta_box(
                sanitize_title( $this->config['title'] ),
                $this->config['title'],
                [ $this, 'add_meta_box_callback' ],
                $screen,
                $this->config['context'],
                $this->config['priority']
            );
        }
    }

//    public function save_post( $post_id ) {
//        foreach ( $this->config['fields'] as $field ) {
//            switch ( $field['type'] ) {
//                default:
//                    if ( isset( $_POST[ $field['id'] ] ) ) {
//                        $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
//                        update_post_meta( $post_id, $field['id'], $sanitized );
//                    }
//            }
//        }
//    }

    public function save_post( $post_id ) {
        // جلوگیری از auto-save یا درخواست‌های ajax
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
        if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) return;

        // بررسی افزونه چندزبانه فعال و شناسایی پست ترجمه‌شده
        $current_lang = '';
        $original_id  = $post_id;

        if ( function_exists('pll_get_post_language') ) {
            $current_lang = pll_get_post_language( $post_id );
            $original_id  = pll_get_post( $post_id, 'default' ); // پست مرجع زبان اصلی
        } elseif ( function_exists('apply_filters') && has_filter('wpml_element_trid') ) {
            $trid   = apply_filters( 'wpml_element_trid', null, $post_id, 'post_' . get_post_type($post_id) );
            $lang   = apply_filters( 'wpml_post_language_details', null, $post_id );
            $current_lang = $lang['language_code'] ?? '';
            $translations = apply_filters( 'wpml_get_element_translations', null, $trid, 'post_' . get_post_type($post_id) );
            if ( isset($translations['en']) ) {
                $original_id = $translations['en']->element_id;
            }
        }

        // اگر ترجمه‌ی زبان دیگر در حال ویرایش است، فقط همان متاها ذخیره شوند
        foreach ( $this->config['fields'] as $field ) {
            if ( isset( $_POST[ $field['id'] ] ) ) {
                $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );

                // اطمینان از ذخیره فقط برای همین زبان
                if ( !empty($current_lang) ) {
                    $meta_key = $field['id'] . '_' . $current_lang;
                    update_post_meta( $post_id, $meta_key, $sanitized );
                } else {
                    update_post_meta( $post_id, $field['id'], $sanitized );
                }
            }
        }
    }


    public function add_meta_box_callback() {
        $this->fields_table();
    }

    private function fields_table() {
        ?><table class="form-table" role="presentation">
        <tbody><?php
        foreach ( $this->config['fields'] as $field ) {
            ?><tr>
            <th scope="row"><?php $this->label( $field ); ?></th>
            <td><?php $this->field( $field ); ?></td>
            </tr><?php
        }
        ?></tbody>
        </table><?php
    }

    private function label( $field ) {
        switch ( $field['type'] ) {
            default:
                printf(
                    '<label class="" for="%s">%s</label>',
                    $field['id'], $field['label']
                );
        }
    }

    private function field( $field ) {
        switch ( $field['type'] ) {
            case 'textarea':
                $this->textarea( $field );
                break;
            default:
                $this->input( $field );
        }
    }

    private function input( $field ) {
        printf(
            '<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
            isset( $field['class'] ) ? $field['class'] : '',
            $field['id'], $field['id'],
            isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
            $field['type'],
            $this->value( $field )
        );
    }

    private function textarea( $field ) {
        printf(
            '<textarea class="regular-text" id="%s" name="%s" rows="%d">%s</textarea>',
            $field['id'], $field['id'],
            isset( $field['rows'] ) ? $field['rows'] : 5,
            $this->value( $field )
        );
    }

    private function value( $field ) {
        global $post;

        $meta_key = $field['id'];
        $lang = '';

        if ( function_exists('pll_get_post_language') ) {
            $lang = pll_get_post_language( $post->ID );
        } elseif ( function_exists('apply_filters') && has_filter('wpml_post_language_details') ) {
            $details = apply_filters( 'wpml_post_language_details', null, $post->ID );
            $lang = $details['language_code'] ?? '';
        }

        if ( !empty($lang) ) {
            $localized_key = $meta_key . '_' . $lang;
            if ( metadata_exists( 'post', $post->ID, $localized_key ) ) {
                return get_post_meta( $post->ID, $localized_key, true );
            }
        }

        if ( metadata_exists( 'post', $post->ID, $meta_key ) ) {
            return get_post_meta( $post->ID, $meta_key, true );
        }

        return isset( $field['default'] ) ? $field['default'] : '';
    }


//    private function value( $field ) {
//        global $post;
//        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
//            $value = get_post_meta( $post->ID, $field['id'], true );
//        } else if ( isset( $field['default'] ) ) {
//            $value = $field['default'];
//        } else {
//            return '';
//        }
//        return str_replace( '\u0027', "'", $value );
//    }

}
new feedbacks_advanced_options;


/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 *
 * Retrieving the values:
 * نوع اطلاعیه = get_post_meta( get_the_ID(), 'jiawaz_options%d9%86%d9%88%d8%b9-%d8%a7%d8%b7%d9%84%d8%a7%d8%b9%db%8c%d9%87', true )
 */
class alerts_options {
    private $config = '{"title":"\u062a\u0646\u0638\u06cc\u0645\u0627\u062a","prefix":"'.TEXT_DOMAIN.'_options","domain":"'.TEXT_DOMAIN.'","class_name":"advanced_options","post-type":["alerts"],"context":"normal","priority":"default","cpt":"","fields":[{"type":"select","label":"\u0646\u0648\u0639 \u0627\u0637\u0644\u0627\u0639\u06cc\u0647","default":"info","options":"info: \u0627\u0637\u0644\u0627\u0639\u0627\u062a\r\nsuccess: \u0645\u0648\u0641\u0642\u06cc\u062a\r\ndanger: \u062e\u0637\u0631\u0646\u0627\u06a9\r\ndark: \u062a\u06cc\u0631\u0647\r\nwarning: \u0647\u0634\u062f\u0627\u0631","id":"'.TEXT_DOMAIN.'_type"}]}';

    public function __construct() {
        $this->config = json_decode( $this->config, true );
        $this->process_cpts();
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function process_cpts() {
        if ( !empty( $this->config['cpt'] ) ) {
            if ( empty( $this->config['post-type'] ) ) {
                $this->config['post-type'] = [];
            }
            $parts = explode( ',', $this->config['cpt'] );
            $parts = array_map( 'trim', $parts );
            $this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
        }
    }

    public function add_meta_boxes() {
        foreach ( $this->config['post-type'] as $screen ) {
            add_meta_box(
                sanitize_title( $this->config['title'] ),
                $this->config['title'],
                [ $this, 'add_meta_box_callback' ],
                $screen,
                $this->config['context'],
                $this->config['priority']
            );
        }
    }

    public function save_post( $post_id ) {
        foreach ( $this->config['fields'] as $field ) {
            switch ( $field['type'] ) {
                default:
                    if ( isset( $_POST[ $field['id'] ] ) ) {
                        $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
                        update_post_meta( $post_id, $field['id'], $sanitized );
                    }
            }
        }
    }

    public function add_meta_box_callback() {
        $this->fields_table();
    }

    private function fields_table() {
        ?><table class="form-table" role="presentation">
        <tbody><?php
        foreach ( $this->config['fields'] as $field ) {
            ?><tr>
            <th scope="row"><?php $this->label( $field ); ?></th>
            <td><?php $this->field( $field ); ?></td>
            </tr><?php
        }
        ?></tbody>
        </table><?php
    }

    private function label( $field ) {
        switch ( $field['type'] ) {
            default:
                printf(
                    '<label class="" for="%s">%s</label>',
                    $field['id'], $field['label']
                );
        }
    }

    private function field( $field ) {
        switch ( $field['type'] ) {
            case 'select':
                $this->select( $field );
                break;
            default:
                $this->input( $field );
        }
    }

    private function input( $field ) {
        printf(
            '<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
            isset( $field['class'] ) ? $field['class'] : '',
            $field['id'], $field['id'],
            isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
            $field['type'],
            $this->value( $field )
        );
    }

    private function select( $field ) {
        printf(
            '<select id="%s" name="%s">%s</select>',
            $field['id'], $field['id'],
            $this->select_options( $field )
        );
    }

    private function select_selected( $field, $current ) {
        $value = $this->value( $field );
        if ( $value === $current ) {
            return 'selected';
        }
        return '';
    }

    private function select_options( $field ) {
        $output = [];
        $options = explode( "\r\n", $field['options'] );
        $i = 0;
        foreach ( $options as $option ) {
            $pair = explode( ':', $option );
            $pair = array_map( 'trim', $pair );
            $output[] = sprintf(
                '<option %s value="%s"> %s</option>',
                $this->select_selected( $field, $pair[0] ),
                $pair[0], $pair[1]
            );
            $i++;
        }
        return implode( '<br>', $output );
    }

    private function value( $field ) {
        global $post;
        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
            $value = get_post_meta( $post->ID, $field['id'], true );
        } else if ( isset( $field['default'] ) ) {
            $value = $field['default'];
        } else {
            return '';
        }
        return str_replace( '\u0027', "'", $value );
    }

}
new alerts_options;


/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 *
 * Retrieving the values:
 * name = get_post_meta( get_the_ID(), 'textdomain_name', true )
 * title = get_post_meta( get_the_ID(), 'textdomain_specialty', true )
 * text = get_post_meta( get_the_ID(), 'textdomain_text', true )
 */
class team_advanced_options {
    private $config = '{"title":"تنظیمات","prefix":"'.TEXT_DOMAIN.'_","domain":"'.TEXT_DOMAIN.'","class_name":"advanced_options","post-type":[],"context":"normal","priority":"default","cpt":"team","fields":[{"type":"text","label":"نام","id":"'.TEXT_DOMAIN.'_name"},{"type":"text","label":"عنوان","id":"'.TEXT_DOMAIN.'_specialty"}]}';

    public function __construct() {
        $this->config = json_decode( $this->config, true );
        $this->process_cpts();
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function process_cpts() {
        if ( !empty( $this->config['cpt'] ) ) {
            if ( empty( $this->config['post-type'] ) ) {
                $this->config['post-type'] = [];
            }
            $parts = explode( ',', $this->config['cpt'] );
            $parts = array_map( 'trim', $parts );
            $this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
        }
    }

    public function add_meta_boxes() {
        foreach ( $this->config['post-type'] as $screen ) {
            add_meta_box(
                sanitize_title( $this->config['title'] ),
                $this->config['title'],
                [ $this, 'add_meta_box_callback' ],
                $screen,
                $this->config['context'],
                $this->config['priority']
            );
        }
    }

    public function save_post( $post_id ) {
        foreach ( $this->config['fields'] as $field ) {
            switch ( $field['type'] ) {
                default:
                    if ( isset( $_POST[ $field['id'] ] ) ) {
                        $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
                        update_post_meta( $post_id, $field['id'], $sanitized );
                    }
            }
        }
    }

    public function add_meta_box_callback() {
        $this->fields_table();
    }

    private function fields_table() {
        ?><table class="form-table" role="presentation">
        <tbody><?php
        foreach ( $this->config['fields'] as $field ) {
            ?><tr>
            <th scope="row"><?php $this->label( $field ); ?></th>
            <td><?php $this->field( $field ); ?></td>
            </tr><?php
        }
        ?></tbody>
        </table><?php
    }

    private function label( $field ) {
        switch ( $field['type'] ) {
            default:
                printf(
                    '<label class="" for="%s">%s</label>',
                    $field['id'], $field['label']
                );
        }
    }

    private function field( $field ) {
        switch ( $field['type'] ) {
            case 'textarea':
                $this->textarea( $field );
                break;
            default:
                $this->input( $field );
        }
    }

    private function input( $field ) {
        printf(
            '<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
            isset( $field['class'] ) ? $field['class'] : '',
            $field['id'], $field['id'],
            isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
            $field['type'],
            $this->value( $field )
        );
    }

    private function textarea( $field ) {
        printf(
            '<textarea class="regular-text" id="%s" name="%s" rows="%d">%s</textarea>',
            $field['id'], $field['id'],
            isset( $field['rows'] ) ? $field['rows'] : 5,
            $this->value( $field )
        );
    }

    private function value( $field ) {
        global $post;
        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
            $value = get_post_meta( $post->ID, $field['id'], true );
        } else if ( isset( $field['default'] ) ) {
            $value = $field['default'];
        } else {
            return '';
        }
        return str_replace( '\u0027', "'", $value );
    }

}
new team_advanced_options;


/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 *
 * Retrieving the values:
 * نوع = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d9%86%d9%88%d8%b9', true )
 * تصویر یا ویدیو = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d8%aa%d8%b5%d9%88%db%8c%d8%b1-%db%8c%d8%a7-%d9%88%db%8c%d8%af%db%8c%d9%88', true )
 * (اختیاری) متن روی استوری = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d8%a7%d8%ae%d8%aa%db%8c%d8%a7%d8%b1%db%8c-%d9%85%d8%aa%d9%86-%d8%b1%d9%88%db%8c-%d8%a7%d8%b3%d8%aa%d9%88%d8%b1%db%8c', true )
 * متن دکمه (اختیاری) = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d9%85%d8%aa%d9%86-%d8%af%da%a9%d9%85%d9%87-%d8%a7%d8%ae%d8%aa%db%8c%d8%a7%d8%b1%db%8c', true )
 * لینک دکمه (اختیاری) = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d9%84%db%8c%d9%86%da%a9-%d8%af%da%a9%d9%85%d9%87-%d8%a7%d8%ae%d8%aa%db%8c%d8%a7%d8%b1%db%8c', true )
 * آیدی محصولات (با , از هم جدا کنید) (اختیاری) = get_post_meta( get_the_ID(), '%d8%aa%d9%86%d8%b8%db%8c%d9%85%d8%a7%d8%aa_%d8%a2%db%8c%d8%af%db%8c-%d9%85%d8%ad%d8%b5%d9%88%d9%84%d8%a7%d8%aa-%d8%a8%d8%a7-%d8%a7%d8%b2-%d9%87%d9%85-%d8%ac%d8%af%d8%a7-%da%a9%d9%86%db%8c%d8%af-%d8%a7%d8%ae%d8%aa%db%8c%d8%a7%d8%b1%db%8c', true )
 */
class stories_advanced_options {
    private $config = '{"title":"تنظیمات","prefix":"'.TEXT_DOMAIN.'_options","domain":"'.TEXT_DOMAIN.'","class_name":"advanced_options","post-type":["stories"],"context":"normal","priority":"default","cpt":"stories","fields":[{"type":"select","label":"\u0646\u0648\u0639","default":"image","options":"image: \u062a\u0635\u0648\u06cc\u0631\r\nvideo: \u0648\u06cc\u062f\u06cc\u0648","id":"'.TEXT_DOMAIN.'_type"},{"type":"media","label":"\u062a\u0635\u0648\u06cc\u0631 \u06cc\u0627 \u0648\u06cc\u062f\u06cc\u0648","button-text":"\u0622\u067e\u0644\u0648\u062f","return":"url","modal-title":"\u06cc\u06a9 \u0641\u0627\u06cc\u0644 \u0627\u0646\u062a\u062e\u0627\u0628 \u06a9\u0646\u06cc\u062f","modal-button":"\u0627\u0646\u062a\u062e\u0627\u0628 \u0627\u06cc\u0646 \u0641\u0627\u06cc\u0644","id":"'.TEXT_DOMAIN.'_media"},{"type":"textarea","label":"(\u0627\u062e\u062a\u06cc\u0627\u0631\u06cc) \u0645\u062a\u0646 \u0631\u0648\u06cc \u0627\u0633\u062a\u0648\u0631\u06cc","rows":"4","id":"'.TEXT_DOMAIN.'_text"},{"type":"text","label":"\u0645\u062a\u0646 \u062f\u06a9\u0645\u0647 (\u0627\u062e\u062a\u06cc\u0627\u0631\u06cc)","id":"'.TEXT_DOMAIN.'_btn_text"},{"type":"text","label":"\u0644\u06cc\u0646\u06a9 \u062f\u06a9\u0645\u0647 (\u0627\u062e\u062a\u06cc\u0627\u0631\u06cc)","id":"'.TEXT_DOMAIN.'_btn_link"},{"type":"text","label":"\u0622\u06cc\u062f\u06cc \u0645\u062d\u0635\u0648\u0644\u0627\u062a (\u0628\u0627 , \u0627\u0632 \u0647\u0645 \u062c\u062f\u0627 \u06a9\u0646\u06cc\u062f) (\u0627\u062e\u062a\u06cc\u0627\u0631\u06cc)","id":"'.TEXT_DOMAIN.'_product_ids"}]}';

    public function __construct() {
        $this->config = json_decode( $this->config, true );
        $this->process_cpts();
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
        add_action( 'admin_head', [ $this, 'admin_head' ] );
        add_action( 'save_post', [ $this, 'save_post' ] );
    }

    public function process_cpts() {
        if ( !empty( $this->config['cpt'] ) ) {
            if ( empty( $this->config['post-type'] ) ) {
                $this->config['post-type'] = [];
            }
            $parts = explode( ',', $this->config['cpt'] );
            $parts = array_map( 'trim', $parts );
            $this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
        }
    }

    public function add_meta_boxes() {
        foreach ( $this->config['post-type'] as $screen ) {
            add_meta_box(
                sanitize_title( $this->config['title'] ),
                $this->config['title'],
                [ $this, 'add_meta_box_callback' ],
                $screen,
                $this->config['context'],
                $this->config['priority']
            );
        }
    }

    public function admin_enqueue_scripts() {
        global $typenow;
        if ( in_array( $typenow, $this->config['post-type'] ) ) {
            wp_enqueue_media();
        }
    }

    public function admin_head() {
        global $typenow;
        if ( in_array( $typenow, $this->config['post-type'] ) ) {
            ?><script defer src="data:text/javascript;base64,CgkJCQlqUXVlcnkubm9Db25mbGljdCgpOwoJCQkJKGZ1bmN0aW9uKCQpIHsKCQkJCQkkKGZ1bmN0aW9uKCkgewoJCQkJCQkkKCdib2R5Jykub24oJ2NsaWNrJywgJy5yd3AtbWVkaWEtdG9nZ2xlJywgZnVuY3Rpb24oZSkgewoJCQkJCQkJZS5wcmV2ZW50RGVmYXVsdCgpOwoJCQkJCQkJbGV0IGJ1dHRvbiA9ICQodGhpcyk7CgkJCQkJCQlsZXQgcndwTWVkaWFVcGxvYWRlciA9IG51bGw7CgkJCQkJCQlyd3BNZWRpYVVwbG9hZGVyID0gd3AubWVkaWEoewoJCQkJCQkJCXRpdGxlOiBidXR0b24uZGF0YSgnbW9kYWwtdGl0bGUnKSwKCQkJCQkJCQlidXR0b246IHsKCQkJCQkJCQkJdGV4dDogYnV0dG9uLmRhdGEoJ21vZGFsLWJ1dHRvbicpCgkJCQkJCQkJfSwKCQkJCQkJCQltdWx0aXBsZTogdHJ1ZQoJCQkJCQkJfSkub24oJ3NlbGVjdCcsIGZ1bmN0aW9uKCkgewoJCQkJCQkJCWxldCBhdHRhY2htZW50ID0gcndwTWVkaWFVcGxvYWRlci5zdGF0ZSgpLmdldCgnc2VsZWN0aW9uJykuZmlyc3QoKS50b0pTT04oKTsKCQkJCQkJCQlidXR0b24ucHJldigpLnZhbChhdHRhY2htZW50W2J1dHRvbi5kYXRhKCdyZXR1cm4nKV0pOwoJCQkJCQkJfSkub3BlbigpOwoJCQkJCQl9KTsKCQkJCQl9KTsKCQkJCX0pKGpRdWVyeSk7CgkJCQ=="></script><?php
        }
    }

    public function save_post( $post_id ) {
        foreach ( $this->config['fields'] as $field ) {
            switch ( $field['type'] ) {
                default:
                    if ( isset( $_POST[ $field['id'] ] ) ) {
                        $sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
                        update_post_meta( $post_id, $field['id'], $sanitized );
                    }
            }
        }
    }

    public function add_meta_box_callback() {
        $this->fields_table();
    }

    private function fields_table() {
        ?><table class="form-table" role="presentation">
        <tbody><?php
        foreach ( $this->config['fields'] as $field ) {
            ?><tr>
            <th scope="row"><?php $this->label( $field ); ?></th>
            <td><?php $this->field( $field ); ?></td>
            </tr><?php
        }
        ?></tbody>
        </table><?php
    }

    private function label( $field ) {
        switch ( $field['type'] ) {
            case 'media':
                printf(
                    '<label class="" for="%s_button">%s</label>',
                    $field['id'], $field['label']
                );
                break;
            default:
                printf(
                    '<label class="" for="%s">%s</label>',
                    $field['id'], $field['label']
                );
        }
    }

    private function field( $field ) {
        switch ( $field['type'] ) {
            case 'media':
                $this->input( $field );
                $this->media_button( $field );
                break;
            case 'select':
                $this->select( $field );
                break;
            case 'textarea':
                $this->textarea( $field );
                break;
            default:
                $this->input( $field );
        }
    }

    private function input( $field ) {
        if ( $field['type'] === 'media' ) {
            $field['type'] = 'text';
        }
        printf(
            '<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
            isset( $field['class'] ) ? $field['class'] : '',
            $field['id'], $field['id'],
            isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
            $field['type'],
            $this->value( $field )
        );
    }

    private function media_button( $field ) {
        printf(
            ' <button class="button rwp-media-toggle" data-modal-button="%s" data-modal-title="%s" data-return="%s" id="%s_button" name="%s_button" type="button">%s</button>',
            isset( $field['modal-button'] ) ? $field['modal-button'] : __( 'Select this file', 'jiawaz' ),
            isset( $field['modal-title'] ) ? $field['modal-title'] : __( 'Choose a file', 'jiawaz' ),
            $field['return'],
            $field['id'], $field['id'],
            isset( $field['button-text'] ) ? $field['button-text'] : __( 'Upload', 'jiawaz' )
        );
    }

    private function select( $field ) {
        printf(
            '<select id="%s" name="%s">%s</select>',
            $field['id'], $field['id'],
            $this->select_options( $field )
        );
    }

    private function select_selected( $field, $current ) {
        $value = $this->value( $field );
        if ( $value === $current ) {
            return 'selected';
        }
        return '';
    }

    private function select_options( $field ) {
        $output = [];
        $options = explode( "\r\n", $field['options'] );
        $i = 0;
        foreach ( $options as $option ) {
            $pair = explode( ':', $option );
            $pair = array_map( 'trim', $pair );
            $output[] = sprintf(
                '<option %s value="%s"> %s</option>',
                $this->select_selected( $field, $pair[0] ),
                $pair[0], $pair[1]
            );
            $i++;
        }
        return implode( '<br>', $output );
    }

    private function textarea( $field ) {
        printf(
            '<textarea class="regular-text" id="%s" name="%s" rows="%d">%s</textarea>',
            $field['id'], $field['id'],
            isset( $field['rows'] ) ? $field['rows'] : 5,
            $this->value( $field )
        );
    }

    private function value( $field ) {
        global $post;
        if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
            $value = get_post_meta( $post->ID, $field['id'], true );
        } else if ( isset( $field['default'] ) ) {
            $value = $field['default'];
        } else {
            return '';
        }
        return str_replace( '\u0027', "'", $value );
    }

}
new stories_advanced_options;