<?php
if (!defined('ABSPATH')) {
    die('-1');
}
/*
 * Hide publish metabox
 *
 *
 * */
function cmplz_remove_publish_box() {
    remove_meta_box( 'submitdiv', 'cmplz-processing', 'side' );
    remove_meta_box( 'submitdiv', 'cmplz-dataleak', 'side' );
}
add_action( 'admin_menu', 'cmplz_remove_publish_box' );
/*
 *
 * Add our custom post types to the complianz menu
 *
 * */

add_action('cmplz_admin_menu', 'cmplz_admin_menu_submenu', 30);
function cmplz_admin_menu_submenu() {
    if (!cmplz_user_can_manage()) return;

    add_submenu_page('complianz', _x('Processing agreements', 'Name of post type in menu', 'complianz-gdpr'), _x('Processing agreements', 'Name of post type', 'complianz-gdpr'), 'manage_options' , 'edit.php?post_type=cmplz-processing');
    add_submenu_page('complianz', _x('Dataleak reports', 'Name of post type in menu', 'complianz-gdpr'), _x('Dataleak reports', 'Name of post type', 'complianz-gdpr'), 'manage_options' , 'edit.php?post_type=cmplz-dataleak');
}

/*
 * As there are no filters we know of to add buttons on a post page, we use an ugly hack.
 *
 *
 *
 * */

add_action('admin_head-edit.php','cmplz_custom_add_new');
function cmplz_custom_add_new()
{
    global $current_screen;
    if ('cmplz-processing' != $current_screen->post_type && 'cmplz-dataleak' != $current_screen->post_type) {
        return;
    }

    $regions = cmplz_get_regions();
    foreach ($regions as $region => $label) {
        ?>
        <script type="text/javascript">
            jQuery(document).ready( function($)
            {
                //in older wp versions, the wp-heading inline class is not available
                if (!$(".wrap .wp-heading-inline").length){
                    $(".wrap").after('<a href="<?php echo admin_url("admin.php?page=" . $current_screen->post_type . "-" . $region)?>" class="page-title-action"><?php printf(__('Add new %s', 'complianz-gdpr'), $label)?></a>');
                } else {
                    $(".wrap .wp-heading-inline").after('<a href="<?php echo admin_url("admin.php?page=" . $current_screen->post_type . "-" . $region)?>" class="page-title-action"><?php printf(__('Add new %s', 'complianz-gdpr'), $label)?></a>');
                }
            });
        </script>
        <?php
    }
}

add_action('cmplz_admin_menu', 'cmplz_admin_menu', 30, 1);
function cmplz_admin_menu()
{

    if (!cmplz_user_can_manage()) return;

    $regions = cmplz_get_regions();
    foreach ($regions as $region => $label) {
        add_submenu_page(
            "edit.php?post_type=cmplz-processing",
            sprintf(__('Add new (%s)', 'complianz-gdpr'), $label),
            sprintf(__('Add new (%s)', 'complianz-gdpr'), $label),
            'manage_options',
            "cmplz-processing-$region",
            "cmplz_processing_page_$region"
        );

        add_submenu_page(
            "edit.php?post_type=cmplz-dataleak",
            sprintf(__('Add new (%s)', 'complianz-gdpr'), $label),
            sprintf(__('Add new (%s)', 'complianz-gdpr'), $label),
            'manage_options',
            "cmplz-dataleak-$region",
            "cmplz_dataleak_page_$region"
        );
    }
}


// Set the "example_parent_page_id" submenu as active/current when creating/editing a "example_cpt" post
add_filter('parent_file', 'cmplz_admin_parent_file');
function cmplz_admin_parent_file($parent_file){
    global $submenu_file, $current_screen;

    // Set correct active/current menu and submenu in the WordPress Admin menu for the "example_cpt" Add-New/Edit/List
    if($current_screen->post_type == 'cmplz-processing') {
        $submenu_file = 'edit.php?post_type=cmplz-processing';
        $parent_file = 'complianz';
    }

    if($current_screen->post_type == 'cmplz-dataleak') {
        $submenu_file = 'edit.php?post_type=cmplz-dataleak';
        $parent_file = 'complianz';
    }

    return $parent_file;
}


// add custom post type
function cmplz_register_post_type()
{
    register_post_type(
        "cmplz-processing", //post name to use in code
        array(
            'labels' => array(
                'name' => _x('Processing agreements', 'Name of post type', 'complianz-gdpr'),
                'singular_name' => _x('Processing agreement (%s)', 'Singular name of post type', 'complianz-gdpr'),
                'add_new' => __('Add new', 'complianz-gdpr'),
                'add_new_item' => __('Add new', 'complianz-gdpr'),
                'parent_item_colon' => __('Processing agreement', 'complianz-gdpr'),
                'parent' => __('Processing agreement parent item', 'complianz-gdpr'),
            ),

            //'menu_icon' => 'dashicons-hammer',
            'menu_icon' => cmplz_url . "assets/images/processing.png", //https://developer.wordpress.org/resource/dashicons/#editor-code
            'menu_position' => CMPLZ_PROCESSING_MENU_POSITION,
            'rewrite' => array(
                'slug' => "processing-agreement",
                'pages' => true
            ),
            'exclude_from_search' => true,
            'supports' => array(
                'title',
                'author',
                'revisions',
                //'page-attributes'
            ),
            'publicly_queryable' => false,
            'query_var' => false,
            'public' => true,
            'has_archive' => false,
            'taxonomies' => array('region'),
            'hierarchical' => false,
            'map_meta_cap' => true, //enable capability handling
            'capabilities' => array(
                'create_posts' => 'do_not_allow',
                'delete_post' => true,
            ),
            'show_in_menu' => false
        )
    );

    register_post_type(
        "cmplz-dataleak", //post name to use in code
        array(
            'labels' => array(
                'name' => __('Dataleaks', 'complianz-gdpr'),
                'add_new' => __('Add new', 'complianz-gdpr'),
                'add_new_item' => __('Add new', 'complianz-gdpr'),
                'parent_item_colon' => __('Dataleak', 'complianz-gdpr'),
                'parent' => __('Dataleak parent item', 'complianz-gdpr'),
            ),

            'menu_icon' => cmplz_url . "assets/images/dataleak.png",
            'menu_position' => CMPLZ_DATALEAK_MENU_POSITION,
            'rewrite' => array(
                'slug' => "dataleak",
                'pages' => true
            ),
            'exclude_from_search' => true,
            'supports' => array(
                'title',
                'author',
                //'page-attributes'
            ),
            'publicly_queryable' => false,
            'query_var' => false,
            'public' => true,
            'has_archive' => false,
            'taxonomies' => array('region'),
            'hierarchical' => false,
            'map_meta_cap' => true, //enable capability handling
            'capabilities' => array(
                'create_posts' => 'do_not_allow',
                'delete_post' => true,
            ),
            'show_in_menu' => false

        )
    );
}
add_action('init', 'cmplz_register_post_type', 99, 1);





function cmplz_register_regions() {
    register_taxonomy(
        'cmplz-region',
        array('cmplz-dataleak','cmplz-processing'),
        array(
            'label' => __( 'Region', 'complianz-gdpr'),
            'publicly_queryable' => false,
            'hierarchical' => true,
            'show_ui' => false,
            'capabilities'      => array(
                'assign_terms' => 'manage_options',
                'edit_terms'   => 'NOT_EXISTING_CAPABILITY',
                'manage_terms' => 'NOT_EXISTING_CAPABILITY',
            ),
            'show_in_nav_menus' => false,
            'show_in_rest' => false,
            'rewrite' => array( 'slug' => 'region' ),
        )
    );
}
add_action( 'init', 'cmplz_register_regions' );

/**
 *  create the dropdown
 */
 function cmplz_add_dropdown_filter(){
     $post_type = isset($_GET['post_type']) ? sanitize_title($_GET['post_type']) : false;

    if ($post_type === 'cmplz-dataleak' || $post_type ==='cmplz-processing') {
            $values = cmplz_get_regions();
            ?>
            <select name="_cmplz_region">
                <option value=""><?php _e('All regions', 'complianz-gdpr'); ?></option>
                <?php
                $current_v = isset($_GET['_cmplz_region']) ? $_GET['_cmplz_region'] : 'on';
                foreach ($values as $value => $label) {
                    printf
                    (
                        '<option value="%s"%s>%s</option>',
                        $value,
                        $value == $current_v ? ' selected="selected"' : '',
                        $label
                    );
                }
                ?>
            </select>
            <?php
    }
}
add_action( 'restrict_manage_posts', 'cmplz_add_dropdown_filter' );


/**
 * if submitted filter by post meta
 */
 function cmplz_filter_posts( $query ){
    global $pagenow;
    $post_type = isset($_GET['post_type']) ? sanitize_title($_GET['post_type']) : false;
     if (($post_type === 'cmplz-dataleak' || $post_type ==='cmplz-processing') && is_admin() && $pagenow=='edit.php') {
        if (isset($_GET['_cmplz_region'])){
            $region = sanitize_title($_GET['_cmplz_region']);
            $query->query_vars['tax_query'] = array(array('taxonomy' =>'cmplz-region','field' => 'slug','terms' => $region));
        }
    }
}
add_filter( 'parse_query', 'cmplz_filter_posts' );


/*
 * Add a column "region"
 *
 *
 * */
add_filter( 'manage_cmplz-dataleak_posts_columns', 'cmplz_set_edit_field_columns' );
add_filter( 'manage_cmplz-processing_posts_columns', 'cmplz_set_edit_field_columns' );

function cmplz_set_edit_field_columns($columns) {

    $columns['region'] = __('Region', 'complianz-gdpr');

    return $columns;
}

/*
 * Fill the column "region"
 *
 * */
add_action( 'manage_cmplz-dataleak_posts_custom_column' , 'cmplz_custom_field_column', 10, 2 );
add_action( 'manage_cmplz-processing_posts_custom_column' , 'cmplz_custom_field_column', 10, 2 );
function cmplz_custom_field_column( $column, $post_id ) {
    if ($column==='region') {
        $region = COMPLIANZ::$document->get_region($post_id);
        if ($region) {
            echo '<img width="25px" src="'.cmplz_url.'/assets/images/'.$region.'.png">';
        }

//        if ($region) {
//            echo COMPLIANZ::$config->regions[$region]['label'];
//        }
    }
}



add_filter('manage_posts_columns', 'cmplz_add_pdf_column');
// add a thumbnail column to the edit posts screen
function cmplz_add_pdf_column($cols)
{
    if (!isset($_GET['post_type']) || strpos($_GET['post_type'], 'cmplz-') === FALSE) return $cols;
    $cols['PDF'] = _x('Download', 'Column title in custom post type overview', 'complianz-gdpr');
    return $cols;
}

// go get the attached images for   the logo and thumbnail columns
add_action('manage_cmplz-processing_posts_custom_column', 'cmplz_add_pdf_icon', 10, 2);
add_action('manage_cmplz-dataleak_posts_custom_column', 'cmplz_add_pdf_icon', 10, 2);
function cmplz_add_pdf_icon($column_name, $post_id)
{
    if (('PDF' == $column_name)) {
        if (strpos(get_post_type($post_id), 'cmplz-') === FALSE) return;
        if (get_post_type($post_id) === 'cmplz-dataleak' && !COMPLIANZ::$dataleak->dataleak_has_to_be_reported_to_involved($post_id)) return;

        echo '<a target="_blank" href="' . cmplz_url . 'pro/pdf.php?nonce=' . wp_create_nonce("cmplz_pdf_nonce") .'&region=' . COMPLIANZ::$document->get_region($post_id). '&post_id=' . $post_id . '&token=' . time() . '"><img src="' . cmplz_url . 'assets/images/pdf.png" width=20px height=20px></a>';
    }

}


add_filter('manage_posts_columns', 'cmplz_add_mail_sent_column');
// add a thumbnail column to the edit posts screen
function cmplz_add_mail_sent_column($cols)
{
    if (!isset($_GET['post_type']) || $_GET['post_type'] !== 'cmplz-dataleak') return $cols;

    $cols['mail_sending_complete'] = _x('Email sent', 'Column header in posts overview','complianz-gdpr');
    return $cols;
}

// go get the attached images for   the logo and thumbnail columns
add_action('manage_cmplz-dataleak_posts_custom_column', 'cmplz_add_mail_sent_icon', 10, 2);
function cmplz_add_mail_sent_icon($column_name, $post_id)
{
    if (('mail_sending_complete' == $column_name)) {
        if (COMPLIANZ::$dataleak->get_email_batch_progress($post_id) >= 100) {
            echo '<i class="fa fa-check"></i>';
        } elseif (COMPLIANZ::$dataleak->get_email_batch_progress($post_id) == 0) {
            echo '';
        } else {
            echo '<i class="fa fa-envelope"></i>';
        }
    }

}


add_action('add_meta_boxes', 'cmplz_add_custom_meta_box');
function cmplz_add_custom_meta_box($post_type)
{
    global $post;

    if (strpos($post_type, 'cmplz-') === FALSE) return;
    add_meta_box('cmplz_document_meta_box_html', __('Document contents', 'complianz-gdpr'), 'cmplz_show_document', null, 'normal', 'high', array());
    add_meta_box('cmplz_edit_meta_box', __('Edit', 'complianz-gdpr'), 'cmplz_show_edit_metabox', null, 'side', 'high', array());

    add_meta_box('cmplz_region_meta_box', __('Region', 'complianz-gdpr'), 'cmplz_show_region', null, 'side', 'high', array());

    //if it doesn't have to be reported, don't show the email option
    if ($post_type === 'cmplz-dataleak' && $post && COMPLIANZ::$dataleak->dataleak_has_to_be_reported_to_involved($post->ID)) {
        add_meta_box('cmplz_email_meta_box', __('Email', 'complianz-gdpr'), 'cmplz_mail_option', null, 'side', 'high', array(//'__block_editor_compatible_meta_box' => true,
        ));
    }

    if (($post_type !== 'cmplz-dataleak') || ($post_type === 'cmplz-dataleak' && $post && COMPLIANZ::$dataleak->dataleak_has_to_be_reported_to_involved($post->ID))) {
        add_meta_box('cmplz_download_meta_box', __('Download', 'complianz-gdpr'), 'cmplz_download_option', null, 'side', 'high', array(//'__block_editor_compatible_meta_box' => true,
        ));
    }

}

function cmplz_mail_option()
{
    COMPLIANZ::$dataleak->send_mail_button();
}

function cmplz_download_option()
{
    global $post;
    $permalink = cmplz_url . 'pro/pdf.php?nonce=' . wp_create_nonce("cmplz_pdf_nonce") . '&region=' . COMPLIANZ::$document->get_region($post->ID). '&post_id=' . $post->ID . '&token=' . time();

    ?>
    <a target="_blank" href="<?php echo $permalink ?>" class="button"><?php _e('Download PDF', 'complianz-gdpr') ?></a>
    <?php
}

function cmplz_show_region(){
    global $post;
    $region = COMPLIANZ::$document->get_region($post->ID);
    echo '<img width="40px" src="'.cmplz_url.'/assets/images/'.$region.'.png">';

}

function cmplz_show_edit_metabox(){
    global $post;

    $region = COMPLIANZ::$document->get_region($post->ID);
    $supported_regions = cmplz_get_regions();
    if (array_key_exists($region, $supported_regions)) {
        $edit_link = admin_url('admin.php?page=' . get_post_type($post) . '-' . $region . '&post_id=' . $post->ID . '&step=2');
        ?>
        <a href="<?php echo $edit_link ?>" class="button"><?php _e('Edit document', 'complianz-gdpr') ?></a>
        <?php
    } else {
        cmplz_notice(__('Because you have disabled the region connected to this document, editing is currently not possbile.','complianz-gdpr'),'warning');
    }
}

function cmplz_show_document()
{
    global $post;
    $region = COMPLIANZ::$document->get_region($post->ID);
    $type = str_replace('cmplz-', '', get_post_type($post));

    if ($type === 'dataleak') {
        COMPLIANZ::$dataleak->dataleak_conclusion($post->ID);
    }

    if ($type === 'processing'){
        echo COMPLIANZ::$document->get_document_html('processing', $region, $post->ID);
    }

    if ($type === 'dataleak') {
        if ($region!=='eu' || COMPLIANZ::$dataleak->dataleak_has_to_be_reported_to_involved($post->ID)) {
            echo COMPLIANZ::$document->get_document_html('dataleak', $region, $post->ID);
        }
    }
}

/*
 * Add a region query arg, so we know which region we're in for the localization.
 *
 *
 * */

add_filter( 'get_edit_post_link', 'cmplz_edit_post_link', 10, 1 );
function cmplz_edit_post_link( $url ) {
    $region = COMPLIANZ::$document->get_region(get_the_ID());
    return  add_query_arg( 'region', $region, $url);
}

/*
 *
 *
 * */

add_filter( 'gutenberg_can_edit_post_type', 'cmplz_gutenberg_can_edit_post_type' , 15, 1);
function cmplz_gutenberg_can_edit_post_type($can_edit)
{
    global $post;

    if ($post && get_post_type($post->ID) == 'cmplz-processing' || get_post_type($post->ID) == 'cmplz-dataleak') {
        return false;
    }

    return $can_edit;
}
