<?php namespace Webien\Setup\Scheduling;

/*
 *
 * Cron job need to exist on server for anything to happen:
 1 * * * * www-data cd /mnt/persist/www/xxx.se/current/web && /usr/local/bin/wp webien-scheduling run > /dev/null
 *
 * */

class Scheduling
{

    static function init()
    {
        $useScheduling = get_option('options_webien_use_scheduling', false);
        if(!$useScheduling) return;


        // Add body class for css
        add_filter( 'admin_body_class', function( $classes ) {
            $classes .= ' use-webien-scheduling';
            return $classes;
        });

        add_action('post_submitbox_misc_actions', [__CLASS__, 'add_meta_box_functionality'], 2);

        // Save inputs
        add_action( 'save_post', [__CLASS__, 'after_save'] );

    }


    static function after_save( $post_id ) {
        if( !current_user_can( 'edit_post', $post_id ) ) return;

        $startUnix = isset( $_POST['webien_schedule_start'] ) && $_POST['webien_schedule_start'] != '' ? strtotime($_POST['webien_schedule_start']) : false;
        $stopUnix = isset( $_POST['webien_schedule_stop'] ) && $_POST['webien_schedule_stop'] != '' ? strtotime($_POST['webien_schedule_stop']) : false;

        if ( $startUnix ) {
            update_post_meta( $post_id, 'webien_schedule_start', $_POST['webien_schedule_start'] );
        } else {
            delete_post_meta( $post_id, 'webien_schedule_start' );
        }

        if ( $stopUnix ) {
            update_post_meta( $post_id, 'webien_schedule_stop', $_POST['webien_schedule_stop'] );
        } else {
            delete_post_meta( $post_id, 'webien_schedule_stop' );
        }


        $offset = 0;
        $schedulingOffset = get_option('options_webien_scheduling_offset', 1);
        if($schedulingOffset) $offset = (int)$schedulingOffset * 3600;

        $now = time() + $offset;

        // Publish now?
        if($startUnix && $startUnix < $now){
            if($stopUnix){
                if($stopUnix > $now){
                    self::publishPost($post_id);
                }
            } else {
                self::publishPost($post_id);
            }
        }

        // Draft now?
        if($stopUnix && $stopUnix < $now){
            self::unpublishPost($post_id);
        }

        // Draft if resaving and start date is in the future
        if($startUnix && $startUnix > $now){
            self::unpublishPost($post_id, true);
        }

    }

    static function publishPost($id){
        $status = get_post_status($id);
        if($status === 'draft'){
            wp_update_post([
                'ID' => $id,
                'post_status' => 'publish'
            ]);

            // Emit action
            do_action('webien/scheduling/publish', $id);
        }
    }

    static function unpublishPost($id, $scheduled = false){
        $status = get_post_status($id);
        if($status === 'publish'){
            // Future status do not seem to work, set it to draft always.
            $newStatus = $scheduled ? 'future' : 'draft';
            wp_update_post([
                'ID' => $id,
                'post_status' => 'draft'
            ]);
        }
    }





    static function add_meta_box_functionality() {

        $post_id = get_the_ID();

        $publish = get_post_meta($post_id, 'webien_schedule_start', true) ?? '';
        $unpublish = get_post_meta($post_id, 'webien_schedule_stop', true) ?? '';

        $dirty = !empty($publish) || !empty($unpublish);
        $scheduled = false;
        $expired = false;
        $active = false;

        if($dirty){

            $startUnix = !empty($publish) ? strtotime($publish) : false;
            $stopUnix = !empty($unpublish) ? strtotime($unpublish) : false;

            $offset = 0;
            $schedulingOffset = get_option('options_webien_scheduling_offset', 1);
            if($schedulingOffset) $offset = (int)$schedulingOffset * 3600;

            $now = time() + $offset;

            // Scheduled for future?
            if($startUnix && $startUnix > $now){
                $scheduled = true;
            }

            // Expired?
            if($stopUnix && $stopUnix < $now){
                $expired = true;
            }

            // Active?
            if($startUnix && $stopUnix && $startUnix < $now && $stopUnix > $now){
                $active = true;
            }

        }

        ?>
        <div class="misc-pub-section misc-webien-schedule <?= $dirty ? 'open':'' ?>" id="webien_schedule_container">

            <button type="button" id="toggle-webien-schedule">
                <div class="first">
                    <span class="dashicons dashicons-calendar"></span>
                    <span class="title"><?= __('Schemalägg', 'webien') ?></span>
                </div>
                <span class="toggle-indicator" aria-hidden="true"></span>
            </button>

            <div class="inputs">
                    <div class="published-msg <?= $active ? 'active':'' ?>">
                        <?php if($active){ ?>
                            <span><?= __('Denna post är inom schemalagd period och därför publicerad. Om publicering inte skett automatiskt, vänligen <a href="mailto:support@haus.se">kontakta support</a>.', 'webien') ?></span>
                        <?php } ?>

                        <?php if($scheduled){ ?>
                        <span><?= __('Denna post är satt till <b>draft</b> tills tiden för publicering infaller. Posten kommer då automatiskt publiceras. Om publicering inte sker, vänligen <a href="mailto:support@haus.se">kontakta support</a>.', 'webien') ?></span>
                        <?php } ?>

                        <?php if($expired){ ?>
                            <span><?= __('Denna post har passerat utgångsdatumet och är därför satt till <b>draft</b>. Om avpublicering inte skett automatiskt, vänligen <a href="mailto:support@haus.se">kontakta support</a>.', 'webien') ?></span>
                        <?php } ?>
                    </div>

                <div class="start">
                    <input placeholder="<?= __('Tid för publicering') ?>" autocomplete="off" type="text" id="webien_schedule_start" name="webien_schedule_start" value="<?= $publish ?>" />
                    <span class="icon" title="<?= __('Tid för publicering') ?>"><?= file_get_contents(WEBIEN_PLUGIN_PATH . '/assets/images/in.svg') ?></span>
                </div>
                <div class="stop">
                    <input placeholder="<?= __('Tid för avpublicering') ?>" autocomplete="off" type="text" id="webien_schedule_stop" name="webien_schedule_stop" value="<?= $unpublish ?>" />
                    <span class="icon" title="<?= __('Tid för avpublicering') ?>"><?= file_get_contents(WEBIEN_PLUGIN_PATH . '/assets/images/out.svg') ?></span>
                </div>
            </div>
        </div>

        <?php
    }

}
