<?php

function drk_add_country_meta_boxes()
{
    add_meta_box(
        "post_metadata_country_id",
        "Country",
        "drk_meta_box_country",
        array('venders', 'markets', 'tlg_channels', 'other_services', 'top_forums'),
        "normal",
        'default'
    );
}

add_action('add_meta_boxes', "drk_add_country_meta_boxes");

function drk_meta_box_country()
{
    global $post;
    $country_code = get_post_meta($post->ID, '_country_code', true);

    $countries_json = file_get_contents(plugin_dir_path(__DIR__) . "../lib/flag-icons-main/country.json");
    $flags_obj = json_decode($countries_json, true);
    ?>
    <?php
        if ($country_code == NULL) { ?>
    <div class="EntriesContainer" id="itemsList">
    <label for="_country_code">Select country</label>
<?php
        } ?>
    <select name="_country_code" id="_country_code" class="postbox">
        <option value="">Select something...</option>
        <?php
        foreach ($flags_obj as $country) { ?>
            <option <?php
            echo ($country_code == $country["code"]) ? "selected" : " " ?>
                    value="<?php
                    echo $country["code"] ?>"><?= $country["name"] ?></option>
        <?php
        }
        ?>
    </select>
    </div>
    <?php
}

function drk_save_country_meta_boxes()
{
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    update_post_meta($post->ID, "_country_code", sanitize_key($_POST["_country_code"]));
}

add_action("save_post", "drk_save_country_meta_boxes");
