<?php

namespace Fab\Controller;

defined( 'WPINC' ) || die;

use Fab\Interfaces\JIT_Interface;
use Fab\Interfaces\Deactivatable_Interface;
/**
 * Plugin hooks in a backend.
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Legacy_Option extends Base implements JIT_Interface, Deactivatable_Interface {

    /**
     * Cron action name.
     *
     * @var string $_schedule_name Schedule name
     */
    private $_schedule_name = 'fab_legacy_option_cron';

    /**
     * Remove legacy options.
     *
     * @return void
     */
    public function remove_legacy_options() {
        $options = get_option( 'fab_config' );
        $options = (object) array_diff_key( (array) $options, array_flip( array( 'fab_config', 'fab_assets' ) ) );
        update_option( 'fab_config', $options );
    }

    /**
     * Register schedule.
     *
     * @access public
     */
    public function register_schedule() {
        $main_schedule = wp_next_scheduled( $this->_schedule_name );

        // Return if schedule is already set.
        if ( $main_schedule ) {
            return;
        }

        // Generate random time components.
        $random_time = array(
            'day'    => wp_rand( 0, 6 ),
            'hour'   => wp_rand( 0, 23 ),
            'minute' => wp_rand( 0, 59 ),
            'second' => wp_rand( 0, 59 ),
        );

        // Calculate total offset in seconds.
        $offset = $random_time['day'] * DAY_IN_SECONDS
                + $random_time['hour'] * HOUR_IN_SECONDS
                + $random_time['minute'] * MINUTE_IN_SECONDS
                + $random_time['second'];

        // Calculate initial send time.
        $init_send = strtotime( 'next sunday' ) + $offset;

        // Schedule new weekly event if none exists.
        if ( ! $main_schedule ) {
            wp_schedule_event( $init_send, 'weekly', $this->_schedule_name );
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * Execute codes that needs to run plugin deactivation.
     *
     * @return void
     */
    public function deactivate() {
        $timestamp = wp_next_scheduled( $this->_schedule_name );

        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, $this->_schedule_name );
        }
    }

    /**
     * JIT method.
     *
     * @return void
     */
    public static function jit() {
        // Register schedule.
        add_action( 'init', array( __CLASS__, 'jit_register_schedule' ) );

        // Schedule legacy option cron.
        add_action( 'fab_legacy_option_cron', array( __CLASS__, 'jit_remove_legacy_options' ) );
    }
}
