<?php


namespace Eventman\Admin;

use \threewp_broadcast\ajax;
use threewp_broadcast\api\api;
use \threewp_broadcast\posts\actions\action as post_action;
use \threewp_broadcast\posts\actions\bulk\wp_ajax;
use threewp_broadcast\ThreeWP_Broadcast;
use WP_Site;

class ThreeWPFix
{

    use LogTrait {
        log as _log;
    }

    private $twp;

    public function __construct()
    {
    }

    /**
    @brief		Handle the display of the custom column.
    @since		2014-04-18 08:30:19
     **/
    public function fixPostCustomColumn( $action )
    {
        $this->twp = isset($this->twp) ? $this->twp : ThreeWP_Broadcast::instance();
        // Title when hovering over the links in the broadcast column
        $title = __( "Click to modify the post's linkage", 'threewp-broadcast' );
        $nonce = wp_create_nonce( 'broadcast_post_action_form' . $action->post->ID );
        $nonce = sprintf( 'data-nonce="%s"', $nonce );

        $html = '';

        if ( $action->broadcast_data->get_linked_parent() !== false )
        {
            $parent = $action->broadcast_data->get_linked_parent();
            $parent_blog_id = $parent[ 'blog_id' ];
            switch_to_blog( $parent_blog_id );

            $html = $this->twp->_(sprintf( '<a class="broadcast post" href="#" %s title="%s"><span class="dashicons dashicons-arrow-left-alt2"></span> %s</a>', $nonce, $title, get_bloginfo( 'name' ) ) );
            $action->html->put( 'linked_from', $html );
            restore_current_blog();
        }

        if ( $action->broadcast_data->has_linked_children() )
        {
            $children = $action->broadcast_data->get_linked_children();

            // Only display if there is something to display
            if ( count( $children ) > 0 )
            {
                // How many children to display?
                $max = get_site_option('blogs_hide_overview' );
                if( count( $children ) > 5 )
                {
                    $html = sprintf( '<a class="broadcast post counter" href="#" %s title="%s"><span class="dashicons dashicons-arrow-right-alt2"></span> %s</a>', $nonce, $title, count( $children ) );
                }
                else
                {
                    $links = [];
                    foreach( $children as $child_blog_id => $child_post_id )
                    {
                        switch_to_blog( $child_blog_id );
                        $info = get_blog_details();
                        $blogname = get_bloginfo('name') ? get_bloginfo('name') : $info->domain . $info->path;
                        $links[ $blogname ] = sprintf( '<span class="dashicons dashicons-arrow-right-alt2"></span> %s', $blogname );
                        restore_current_blog();
                    }
                    ksort( $links );
                    $html = sprintf( '<a class="broadcast post" href="#" %s title="%s">%s</a>',
                        $nonce,
                        $title,
                        implode( '<br/>', $links )
                    );
                }
                $action->html->put( 'broadcasted_to', $html );
            }
        } elseif ($action->broadcast_data->get_linked_parent() === false) {
            $html .= "<a class=\"broadcast post\" href=\"#\" $nonce title=\"$title\">None</a>";
            $action->html->put( 'broadcasted_to', $html );
        }

        $action->finish();
    }

    /**
    @brief		Display and handle the actions available for a post.
    @since		2014-11-02 20:44:32
     **/
    public function fixBroadcastFormBox()
    {
        $this->log('Launched ThreeWP Broadcast fix for Post Table Column popup');
        $this->twp = isset($this->twp) ? $this->twp : ThreeWP_Broadcast::instance();
        if ( ! isset( $_REQUEST[ 'nonce' ] ) )
            wp_die( 'No nonce.' );
        $nonce = $_REQUEST[ 'nonce' ];

        if ( ! isset( $_REQUEST[ 'post_id' ] ) )
            wp_die( 'No nonce.' );
        $post_id = intval( $_REQUEST[ 'post_id' ] );

        $action = 'broadcast_post_action_form';
        if ( ! wp_verify_nonce( $nonce, $action . $post_id ) )
            wp_die( 'Invalid nonce.' );

        // Everything is good to go.

        $blog_id = get_current_blog_id();
        $broadcast_data = $this->twp->get_post_broadcast_data( $blog_id, $post_id );


        $form = $this->twp->form2();
        $form->hidden_input( 'action', $nonce );
        $form->hidden_input( 'nonce', $nonce );
        $form->hidden_input( 'post_id', $post_id );
        $form->id( 'broadcast_post_action_form' );
        $json = new ajax\json();
        $json->html = '';
        $has_links = false;

        // Linked to a parent.
        $parent = $broadcast_data->get_linked_parent();
        if ( $parent !== false )
        {
            switch_to_blog( $parent[ 'blog_id' ] );

            $edit_link = sprintf( '<a href="%s">%s</a>',
                get_edit_post_link( $parent[ 'post_id' ] ),
                __( 'Edit' )
            );
            $view_link = sprintf( '<a href="%s">%s</a>',
                get_permalink( $parent[ 'post_id' ] ),
                __( 'View' )
            );

            $links = sprintf( '%s: %s | %s',
                // Parent post: VIEW / LINK, in the child post action popup.
                __( 'Parent post', 'threewp_broadcast' ),
                $edit_link,
                $view_link
            );

            $form->markup( 'm_parent_links' )
                ->p( $links );

            restore_current_blog();

            $unlink = $form->checkbox( 'unlink' )
                // Description of unlink checkbox
                ->description( __( 'Unlink this post from its parent.', 'threewp-broadcast' ) )
                // Label of unlink checkbox
                ->label( __( 'Unlink', 'threewp-broadcast' ) );
            $has_links = true;
        }

        if ( $broadcast_data->has_linked_children() )
        {
            $form->blogs = [];
            // Find all options for posts.
            $action = $this->twp->new_action( 'get_post_actions' );
            $action->post = get_post( $post_id );
            $action->execute();
            $options = [ '' => $this->twp->_( 'No change' ) ];
            foreach( $action->actions as $post_action )
            {
                $options[ $post_action->action ] = $post_action->get_name();
            }
            ksort( $options );

            $children = $broadcast_data->get_linked_children();
            foreach( $children as $child_blog_id => $child_post_id )
            {
                switch_to_blog( $child_blog_id );
                $info = get_blog_details();
                $blogname = get_bloginfo( 'name' ) ? get_bloginfo( 'name' ) : $info->domain . $info->path;
                $edit_link = sprintf( '<a href="%s">%s</a>',
                    get_edit_post_link( $child_post_id ),
                    __( 'Edit' )
                );
                $view_link = sprintf( '<a href="%s">%s</a>',
                    get_permalink( $child_post_id ),
                    __( 'View' )
                );
                $select = $form->select( $child_blog_id )
                    ->label( $blogname )
                    ->prefix( 'blogs' )
                    ->opts( $options )
                ;

                // The edit link we put in the description, but it requires that the HTML be set without escaping.
                $select->description->label->content = sprintf( '<div class="row-actions">%s | %s</a>', $edit_link, $view_link );;

                $select->blog_id = $child_blog_id;
                $select->post_id = $child_post_id;
                $form->blogs []= $select;
                restore_current_blog();
            }
            $has_links = true;
        }

        if ( ! $has_links )
            $json->html .= $this->twp->p( __( 'This post has no broadcast links.', 'threewp-broadcast' ) );

        if (is_main_site()) {
            foreach (get_sites() as $site) {
                /** @var WP_Site $site */
                if (get_main_site_id() != $site->blog_id
                    && !in_array($site->blog_id, array_keys($broadcast_data->get_linked_children()))
                    && !$site->archived
                    && !$site->deleted
                    && $site->public) {
                    $form->checkbox( 'link-' . $site->blog_id )
                        ->name('broadcast[' . $site->blog_id . ']')
                        // Description of unlink checkbox
                        ->description( __( 'Link this post to this blog.', 'threewp-broadcast' ) )
                        // Label of unlink checkbox
                        ->label( __( 'Link to ', 'threewp-broadcast' ) . $site->blogname );
                } else {
                    $this->log('Skipping site ' . $site->blogname);
                }
            }
        }

        $submit = $form->primary_button( 'submit' )
            // Submit button for post actions
            ->value( __( 'Submit', 'threewp-broadcast' ) );

        if ( $form->is_posting() )
        {
            $form->post()->use_post_values();
            // We have to check specifically for the submit.
            if ( $submit->pressed() )
            {
                if ( isset( $unlink ) && $unlink->is_checked() )
                {
                    $post_action = $this->twp->new_action( 'post_action' );
                    $post_action->action = 'unlink';
                    $post_action->post_id = $post_id;
                    $post_action->execute();
                }
                if ( isset( $form->blogs ) )
                {
                    foreach( $form->blogs as $select )
                    {
                        $value = $select->get_post_value();
                        if( $value == '' )
                            continue;
                        $post_action = $this->twp->new_action( 'post_action' );
                        $post_action->action = $value;
                        $post_action->post_id = $post_id;
                        $post_action->child_blog_id = $select->blog_id;
                        $post_action->execute();
                    }
                }
                if (isset($_POST['broadcast'])) {
                    $api = new api();
                    $blogs = [];
                    foreach($_POST['broadcast'] as $id => $val) {
                        if ($val == 'on') {
                            $blogs[] = $id;
                        }
                    }
                    $api->broadcast_children($post_id, $blogs);
                }

                unset( $_POST[ 'submit' ] );
                $this->fixBroadcastFormBox();
            }
        }

        $json->html .= $form->open_tag();
        $json->html .= $form->display_form_table();
        $json->html .= $form->open_tag();
        $json->output();
    }

    protected function log($msg)
    {
        $this->twp = isset($this->twp) ? $this->twp : ThreeWP_Broadcast::instance();
        $this->_log('ThreeWPFix: '.$msg);
        $this->twp->debug($msg);
    }
}