<?php

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

//新規登録か更新かの峻別
$editID = 0;
$base_url = '';

if (isset($_GET['editpostID'], $_GET['itmar_nonce'])) {
    $post_id = absint(wp_unslash($_GET['editpostID']));

    // GETでもOK。第2引数にクエリ名を渡す
    check_admin_referer('itmar_edit_post_' . $post_id, 'itmar_nonce');
    if (! current_user_can('edit_post', $post_id)) {
        wp_die(esc_html__('Permission denied.', 'itmaroon-social-post-sync'));
    }

    $editID = $post_id;
} else {
    //新規投稿
    global $POST_GET_TYPE;
    $post_option = array(
        'post_status' => 'pending',
        'post_title' => 'new_post',
        'post_type' => $POST_GET_TYPE,
    );
    $editID = wp_insert_post($post_option);
}
//仮置きのパーマリンクを取得
require_once ABSPATH . '/wp-admin/includes/post.php';
list($permalink, $postname) = get_sample_permalink($editID);
$base_url = str_replace('/%postname%', '', $permalink);
$base_url = str_replace('/%pagename%', '', $base_url);

//編集対象のIDとステータスを取得
$post_obj = get_post($editID);
$post_status = $post_obj->post_status;
//ここでSNS投稿エディタ用のJSをエンキュー
$script_path = ITMAR_SNS_PLUGIN_PATH . 'js/sns_edit_render.js';
wp_enqueue_script('sns_edit_render', ITMAR_SNS_PLUGIN_URL . 'js/sns_edit_render.js', array('jquery', 'wp-i18n'), filemtime($script_path), true);
// その後、このハンドルを使用してスクリプトの翻訳をセット
wp_set_script_translations('sns_edit_render', 'itmaroon-social-post-sync', plugin_dir_path(__FILE__) . 'languages');

function itmar_defaultDataLocalize($editID, $post_status, $post_obj, $media_items)
{
    //デフォルトデータのフロントエンドへの受け渡し
    if ($editID !== 0 && $post_status !== 'pending') {

        $field_arr   = [];
        $media_fields = [];

        // 1) ACFフィールドタイプを構築
        $acf_field_types = [];
        if (function_exists('acf_get_field_groups')) {
            $groups = acf_get_field_groups();
            foreach ($groups as $g) {
                $fields = acf_get_fields($g['key']) ?: [];
                foreach ($fields as $f) {
                    if ($f['type'] === 'group' && !empty($f['sub_fields'])) {
                        foreach ($f['sub_fields'] as $sf) {
                            $acf_field_types[$f['name'] . '_' . $sf['name']] = $sf['type'];
                        }
                    } else {
                        $acf_field_types[$f['name']] = $f['type'];
                    }
                }
            }
        }
        //meta情報を取得
        foreach (get_post_meta($editID) as $key => $meta) {
            if (strpos($key, '_') === 0) continue; // 内部キー除外
            $type  = $acf_field_types[$key] ?? null;
            $value = $type ? get_field($key, $editID) : maybe_unserialize($meta[0]);
            if (!in_array($type, ['image', 'gallery'], true)) {
                $field_arr[$key] = $value;
            }
        }
        // メディアフィールド情報を取得
        foreach ($media_items as $media_item) {
            $key = $media_item['field_type'];
            $media_fields[] = $key;

            if (!isset($field_arr[$key])) {
                // 初登場 → スカラーで保存
                $field_arr[$key] = $media_item['id'];
            } elseif (is_array($field_arr[$key])) {
                // すでに配列 → 末尾に追加
                $field_arr[$key][] = $media_item['id'];
            } else {
                // 2回目の登場 → スカラーを配列に昇格
                $field_arr[$key] = [
                    $field_arr[$key],
                    $media_item['id'],
                ];
            }
        }

        // タクソノミー情報からフロントエンドに渡すデータを構築
        $taxonomies = get_object_taxonomies($post_obj->post_type, 'names');
        $term_arr = [];
        foreach ($taxonomies as $tax) {
            $terms = wp_get_object_terms($editID, $tax, ['hide_empty' => false]);
            if (is_wp_error($terms) || empty($terms)) {
                continue;
            }

            foreach ($terms as $term) {
                // kind を決定
                if ($term->taxonomy === 'category') {
                    $kind = 'catg_item';
                    $slug = $term->slug;
                } elseif ($term->taxonomy === 'post_tag') {
                    $kind = 'tag_item';
                    $slug = $term->slug;
                } else {
                    $kind = 'term_item';
                    // 元コードの挙動に合わせて「slug,taxonomy」を slug に入れる
                    $slug = $term->slug . ',' . $term->taxonomy;
                }

                $term_arr[] = [
                    'slug' => $slug,
                    'kind' => $kind,
                ];
            }
        }
        //フロントエンドへ送る
        wp_localize_script('sns_edit_render', 'sns_edit_option', [
            'editID' => $editID,
            'field_arr'    => $field_arr,
            'media_fields' => $media_fields,
            'term_arr' => $term_arr,
            'post_status' => $post_status
        ]);
    } else {
        wp_localize_script('sns_edit_render', 'sns_edit_option', [
            'editID' => $editID,
            'field_arr'    => new stdClass(), // 空オブジェクト
            'media_fields' => [],
            'term_arr' => [],
        ]);
    }
}
?>

<!-- 画面表示のHTML -->
<div class="wrap sns-relate-editor">
    <div class="page_title">
        <?php esc_html_e('Creating and editing posts', 'itmaroon-social-post-sync') ?>
        <div class="title_postType">
            <?php esc_html_e('Save the post to this post type:', 'itmaroon-social-post-sync') ?><br class="sp_br">
            <span>
                <?php
                global $POST_GET_TYPE;
                $obj_postType = get_post_type_object($POST_GET_TYPE);
                echo '<span class="wp-menu-image dashicons-before ' . esc_attr($obj_postType->menu_icon) . '"></span>';
                echo '<span>' . esc_attr($obj_postType->labels->name) . '</span>';
                ?>
            </span>

        </div><!-- /.title_postType -->
    </div><!-- /.page_title -->

    <div class="edit_snspost">
        <!-- progressbar -->
        <ul id="progressbar">
            <li class="active"><?php esc_html_e('Text information', 'itmaroon-social-post-sync') ?></li>
            <li><?php esc_html_e('Media Selection', 'itmaroon-social-post-sync') ?></li>
            <li><?php esc_html_e('Option Selection', 'itmaroon-social-post-sync') ?></li>
        </ul>

        <div class="modal_ctrl edit">
            <div class="fieldset_btn_wrapper">
                <div class="btn_move">
                    <div class="btn_prev"><?php esc_html_e('Previous screen', 'itmaroon-social-post-sync') ?></div>
                    <div class="btn_next appear"><?php esc_html_e('Next screen', 'itmaroon-social-post-sync') ?></div>
                </div><!-- /.btn_move -->
                <div class="btn_exec">
                    <?php if ($post_status != 'pending'): ?>
                        <!-- 投稿ボタン -->
                        <div class="sns_exec modify"><?php esc_html_e('Update Post', 'itmaroon-social-post-sync') ?></div>
                        <!-- 削除ボタン -->
                        <div class="sns_delete"><?php esc_html_e('Delete Post', 'itmaroon-social-post-sync') ?></div>
                    <?php else: ?>
                        <!-- 投稿ボタン -->
                        <div class="sns_exec"><?php esc_html_e('New Post', 'itmaroon-social-post-sync') ?></div>
                    <?php endif; ?>
                </div><!-- /.btn_exec -->
            </div><!-- /.fieldset_btn_wrapper -->

        </div><!-- /.ctrl_wrapper -->

        <fieldset class="text_input_area">
            <div class="content_title text">
                <?php esc_html_e('Text information', 'itmaroon-social-post-sync') ?>
            </div><!-- /.content_title -->
            <div id="focus"></div>
            <div class="input_box date_picker">
                <label for="title"><?php esc_html_e('Post date', 'itmaroon-social-post-sync') ?></label>
                <input id="postdate_id" type="text"
                    value="<?php echo esc_attr(
                                ($editID != 0 && $post_status !== 'pending') ? get_the_date('Y/m/d H:i', $editID) : ''
                            ); ?>" />
            </div>

            <div class="input_box title">
                <label for="title"><?php esc_html_e('Title', 'itmaroon-social-post-sync') ?><strong><?php esc_html_e('(required)', 'itmaroon-social-post-sync') ?></strong></label>
                <input id="title" type="text"
                    value="<?php echo esc_attr(
                                ($editID != 0 && $post_status !== 'pending') ? get_the_title($editID) : ''
                            ); ?>" />
                <div class=" info_btn">
                    <img src="<?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/info.png'); ?>" alt="">
                    <div class="ballon under">
                        <span>
                            <?php esc_html_e('The title will be displayed on social media surrounded by 【】.', 'itmaroon-social-post-sync') ?>
                        </span>
                    </div>
                </div><!-- /.info_btn -->
            </div>
            <div class="input_box url_box">
                <label for="title" class="active">URL</label>
                <div class="home_url">
                    <?php echo esc_url($base_url); ?>
                </div><!-- /.home_url -->
                <input id="url_id" type="text"
                    value="<?php echo esc_attr(
                                ($editID != 0 && $post_status !== 'pending') ? $post_obj->post_name : ''
                            ); ?>" />

                <?php
                if (function_exists('sl_trans_exec_translate')): //翻訳関数が存在するか
                ?>
                    <div class="info_btn url_input">
                        <img src="<?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/info.png'); ?>" alt="">
                        <div class="ballon under">
                            <span>
                                <?php esc_html_e('The URL will be generated based on the title and translated into English.', 'itmaroon-social-post-sync') ?><br class='sp_br'><?php esc_html_e('Corrections are possible.', 'itmaroon-social-post-sync') ?>
                            </span>
                        </div>
                    </div><!-- /.info_btn -->
                <?php endif; ?>
                <div class="url_check">
                    <label><input type="checkbox" name="url_entry"><span></span>
                        <p rel="<?php esc_html_e('Add a URL to the text', 'itmaroon-social-post-sync') ?>"><?php esc_html_e('Add a URL to the text', 'itmaroon-social-post-sync') ?></p>
                    </label>
                </div><!-- /.url_check -->
            </div>

            <div class="input_box" id="id_textArea">
                <label for="content"><?php esc_html_e('Main text (comments)', 'itmaroon-social-post-sync') ?></label>
                <textarea id="id_comment" name="content"><?php echo esc_textarea(($editID != 0 && $post_status !== 'pending') ? get_the_excerpt($editID) : ''); ?></textarea>
                <div class="tw_check">
                    <label><input type="checkbox" name="entry_wp"><span></span>
                        <p rel="<?php esc_html_e('Set the scope of your Twitter posts', 'itmaroon-social-post-sync') ?>"><?php esc_html_e('Set the scope of your Twitter posts', 'itmaroon-social-post-sync') ?></p>
                    </label>
                </div><!-- /.tw_check -->
                <div class="char_count">
                    <label><?php esc_html_e('Number of characters to enter：', 'itmaroon-social-post-sync') ?><span class="input_count"></span></label>
                    <label><?php esc_html_e('Twitter Limit：', 'itmaroon-social-post-sync') ?><span class="tw_limit"></span></label>
                </div><!-- /.char_count -->
                <div class="info_btn">
                    <img src="<?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/info.png'); ?>" alt="">
                    <div class="ballon under">
                        <span>
                            <?php esc_html_e('Drag the entered text', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('As text in a Twitter post', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('You can choose.', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('If it is not selected', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('From the beginning, including the title', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('140 characters will be set.', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('(A line break counts as one character.', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('If the message exceeds 140 characters, "..." will be added to the end.', 'itmaroon-social-post-sync') ?>
                            <br class='sp_br'><?php esc_html_e('Only 137 characters will be posted.)', 'itmaroon-social-post-sync') ?>
                        </span>
                    </div>
                </div><!-- /.info_btn -->
                <div class="ballon twArea">
                    <div>
                        <div class="tw_icon">
                            <div class="img_wrapper">
                                <img src="<?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/x-black.png'); ?>" alt="">
                                <div class="bullet">
                                    <div class="line zero"></div>
                                    <div class="line one"></div>
                                    <div class="line two"></div>
                                    <div class="line three"></div>
                                    <div class="line four"></div>
                                    <div class="line five"></div>
                                    <div class="line six"></div>
                                    <div class="line seven"></div>
                                </div>
                            </div><!-- /.img_wrapper -->

                        </div><!-- /.tw_icon -->
                    </div>
                </div>

            </div>
        </fieldset><!-- /.text_input_area -->

        <fieldset class="input_image_erea">
            <div class="content_title image">
                <?php esc_html_e('Media Selection', 'itmaroon-social-post-sync') ?>
            </div><!-- /.content_title -->
            <div class="image_caution">
                <?php esc_html_e('To display multiple images, you must set up a gallery, an ACF or SCF custom field named "gallery".', 'itmaroon-social-post-sync') ?>
            </div><!-- /.content_title -->


            <?php
            $media_items = itmar_sns_image_ui($editID);
            itmar_defaultDataLocalize($editID, $post_status, $post_obj, $media_items);
            ?>

        </fieldset><!-- /.input_image_erea -->

        <fieldset class="option_input_area">
            <div class="content_title option">
                <?php esc_html_e('Option Selection', 'itmaroon-social-post-sync') ?>
            </div><!-- /.content_title -->
            <div class="select_wapper">
                <div class="option_title">
                    <?php esc_html_e('Select categories, tags, etc.', 'itmaroon-social-post-sync') ?>
                </div>
                <?php itmar_category_select(); ?>
                <div class="info_btn">
                    <img src="<?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/info.png'); ?>" alt="">
                    <div class="ballon under">
                        <span>
                            <?php esc_html_e('Select the WordPress categories, tags, and terms you want to set for your post.', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('Only items that are already registered can be set.', 'itmaroon-social-post-sync') ?>
                            <br><?php esc_html_e('Please register new ones from the management screen.', 'itmaroon-social-post-sync') ?>
                        </span>
                    </div>
                </div><!-- /.info_btn -->
            </div><!-- /.select_wapper -->
            <div class="snsSel_wrapper">
                <div class="snsSel_title">
                    <?php esc_html_e('Select the SNS to post to simultaneously', 'itmaroon-social-post-sync') ?>
                </div>
                <select name="target_sns" class="radio" multiple>
                    <option class="sns_sel" value="Twitter" selected><?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/x-black.png'); ?></option>
                    <option class="sns_sel" value="Facebook" selected><?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/facebook_b.png'); ?></option>
                    <option class="sns_sel" value="Instagram" selected><?php echo esc_url(ITMAR_SNS_PLUGIN_URL . '/img/instagram_logo.png'); ?></option>
                </select>
            </div><!-- /.snsSel_wrapper -->

        </fieldset><!-- /.option_input_area -->

    </div><!-- /.edit_snspost -->

    <!-- modal 背景-->
    <div class="modal_bg">
    </div><!-- /.modal_bg -->

    <!-- modal dialog 投稿情報確認-->
    <div class="modal_frame modal">
        <div class="modal_title">
            <?php esc_html_e('Check SNS posting information', 'itmaroon-social-post-sync') ?>
        </div><!-- /.modal_title -->
        <div class="modal_message">
        </div><!-- /.modal_message -->
        <div class="top_section">
            <div class="progress">
                <div class="target_title">
                    <?php esc_html_e('【Submission progress】', 'itmaroon-social-post-sync') ?>
                </div><!-- /.target_title -->
                <div class="target_wrapper">
                    <ul class="target_sns">
                        <li class="post_prg Twitter">
                            X : <span><?php esc_html_e('Waiting.', 'itmaroon-social-post-sync') ?></span>
                        </li><!-- /.post_prg -->
                        <li class="post_prg Facebook">
                            Facebook : <span><?php esc_html_e('Waiting.', 'itmaroon-social-post-sync') ?></span>
                        </li><!-- /.post_prg -->
                        <li class="post_prg Instagram">
                            Instagram : <span><?php esc_html_e('Waiting.', 'itmaroon-social-post-sync') ?></span>
                        </li><!-- /.post_prg -->
                    </ul><!-- /.target_sns -->
                    <div class="return_box">
                        <div id="btn_end">
                            <?php esc_html_e('Exit and return to list', 'itmaroon-social-post-sync') ?>
                        </div><!-- /#btn_end -->
                    </div><!-- /.return_box -->
                </div><!-- /.target_wrapper -->
            </div><!-- /.progress -->

            <div class="exec">
                <div id="sns_entry">
                    <?php esc_html_e('Executing the post', 'itmaroon-social-post-sync') ?>
                </div><!-- /#sns_entry -->
                <div class="cansel_check">
                    <label><input type="checkbox" name="save_cansel"><span></span>
                        <p rel="<?php esc_html_e('Do not post on social media, only post on the homepage.', 'itmaroon-social-post-sync') ?>"><?php esc_html_e('Do not post on social media, only post on the homepage.', 'itmaroon-social-post-sync') ?></p>
                    </label>
                </div><!-- /.cansel_check -->
                <div class="wp_save_mode">
                    <div class="save_title">
                        <?php esc_html_e('Homepage Posting', 'itmaroon-social-post-sync') ?>
                        <span><?php
                                switch ($post_status) {
                                    case 'pending':
                                        $disp_status = __('(New)', 'itmaroon-social-post-sync');
                                        break;
                                    case 'publish':
                                        $disp_status = __('(Available)', 'itmaroon-social-post-sync');
                                        break;
                                    case 'draft':
                                        $disp_status = __('(Draft)', 'itmaroon-social-post-sync');
                                        break;
                                    case 'future':
                                        $disp_status = __('(Reservations)', 'itmaroon-social-post-sync');
                                        break;
                                    default:
                                        $disp_status = '';
                                }
                                echo esc_html($disp_status);
                                ?></span>
                    </div>

                    <div class="draft_radio">
                        <label><input type="radio" name="post_radio" value="publish" checked><span><?php esc_html_e('Publish', 'itmaroon-social-post-sync') ?></span></label>
                        <label><input type="radio" name="post_radio" value="draft"><span><?php esc_html_e('Save as draft', 'itmaroon-social-post-sync') ?></span></label>
                    </div><!-- /.draft_radio -->
                </div><!-- /.wp_savemode -->

            </div><!-- /.exec -->
        </div><!-- /.top_section -->

        <div class="modal_close">
            <div class="drawer_icon_bars">
                <div class="drawer_icon_bar1"></div>
                <div class="drawer_icon_bar2"></div>
            </div><!-- drawer_icon_bars -->
        </div><!-- /.modal_close -->

        <div class="sns_section Twitter">
            <div class="sns_title">
                <?php esc_html_e('X post content', 'itmaroon-social-post-sync') ?>
            </div><!-- /.sns_title -->
            <div class="content">
                <div class="content_title text">
                    <?php esc_html_e('text', 'itmaroon-social-post-sync') ?>
                </div><!-- /.content_title -->
                <div class="text_description">
                </div><!-- /.text_description -->

                <div class="image_erea">
                    <div class="content_title image">
                        <?php esc_html_e('media', 'itmaroon-social-post-sync') ?>
                    </div><!-- /.content_title -->
                    <div class="sns_image">
                        <div class="empty_msg">
                            <?php esc_html_e('No media has been selected to post.', 'itmaroon-social-post-sync') ?>
                        </div><!-- /.empty_msg -->
                    </div><!-- /.sns_image -->
                </div><!-- /.image_erea -->

            </div><!-- /.content -->
        </div><!-- /.sns_section -->

        <div class="sns_section Facebook">
            <div class="sns_title">
                <?php esc_html_e('Facebook post content', 'itmaroon-social-post-sync') ?>
            </div><!-- /.sns_title -->
            <div class="content">
                <div class="content_title text">
                    <?php esc_html_e('text', 'itmaroon-social-post-sync') ?>
                </div><!-- /.content_title -->
                <div class="text_description">
                </div><!-- /.text_description -->

                <div class="image_erea">
                    <div class="content_title image">
                        <?php esc_html_e('media', 'itmaroon-social-post-sync') ?>
                    </div><!-- /.content_title -->
                    <div class="sns_image">
                        <div class="empty_msg">
                            <?php esc_html_e('No media has been selected to post.', 'itmaroon-social-post-sync') ?>
                        </div><!-- /.empty_msg -->
                    </div><!-- /.sns_image -->
                </div><!-- /.image_erea -->

            </div><!-- /.content -->
        </div><!-- /.sns_section -->

        <div class="sns_section Instagram">
            <div class="sns_title">
                <?php esc_html_e('Instagram post content', 'itmaroon-social-post-sync') ?>
            </div><!-- /.sns_title -->
            <div class="content">
                <div class="content_title text">
                    <?php esc_html_e('caption', 'itmaroon-social-post-sync') ?>
                </div><!-- /.content_title -->
                <div class="text_caption">
                </div><!-- /.text_caption -->

                <div class="image_erea">
                    <div class="content_title image">
                        <?php esc_html_e('media', 'itmaroon-social-post-sync') ?>
                    </div><!-- /.content_title -->
                    <div class="sns_image">
                        <div class="empty_msg">
                            <?php esc_html_e('No media has been selected to post.', 'itmaroon-social-post-sync') ?>
                        </div>
                    </div><!-- /.sns_image -->
                </div><!-- /.image_erea -->

            </div><!-- /.content -->
        </div><!-- /.sns_section -->
    </div><!-- /.modal_frame -->

    <!-- modal dialog 削除確認-->
    <div class="modal_delete modal">
        <div class="modal_close">
            <div class="drawer_icon_bars">
                <div class="drawer_icon_bar1"></div>
                <div class="drawer_icon_bar2"></div>
            </div><!-- drawer_icon_bars -->
        </div><!-- /.modal_close -->
        <div class="del_msg">
            <?php esc_html_e('Would you like to delete the social media posts linked to this article at the same time?', 'itmaroon-social-post-sync') ?>
        </div><!-- /.del_msg -->
        <div class="del_list">
            <div class="del_check" rel="twitter_id">
                <label><input type="checkbox" name="del_sns"><span></span>
                    <p rel="Twitter:">Twitter:</p>
                </label>
                <div class='info'></div>
            </div><!-- /.del_check -->
            <div class="del_check" rel="facebook_id">
                <label><input type="checkbox" name="del_sns"><span></span>
                    <p rel="Facebook:">Facebook:</p>
                </label>
                <div class='info'></div>
            </div><!-- /.del_check -->

        </div><!-- /.del_list -->

        <div class="del_coution">
            <?php esc_html_e('(Instagram posts cannot be deleted from this app. Please delete them from the Instagram app.)', 'itmaroon-social-post-sync') ?>
        </div> <!-- /.del_coution-->
        <div id="btn_delete">
            <?php esc_html_e('Delete execution', 'itmaroon-social-post-sync') ?>
        </div><!-- /#btn_end -->
    </div><!-- /.modal_delete -->

    <!-- modal dialog 画像の拡大-->
    <div class="modal_media modal">
        <div class="modal_close">
            <div class="drawer_icon_bars">
                <div class="drawer_icon_bar1"></div>
                <div class="drawer_icon_bar2"></div>
            </div><!-- drawer_icon_bars -->
        </div><!-- /.modal_close -->
        <div class="media_frame">

        </div><!-- /.media_frame -->
    </div><!-- /.modal_media -->

</div>