<?php

namespace Fab\Controller;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Insight
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Insight extends Base {

    // Load Traits.
    use \Fab\Plugin\Helper\Transient;

    /**
     * Transient name.
     *
     * @var string
     */
    protected $insight_id;

    /**
     * Insight type.
     *
     * @var string
     */
    protected $insight_type;

    /**
     * Insight schedule.
     * - every_minute, hourly, daily, weekly, monthly, etc.
     *
     * @var string
     */
    protected $insight_schedule;

    /**
     * Load insight.
     *
     * @param array  $instances Instances.
     * @param string $type Insight type.
     * @return array
     */
    public function load_insight( $instances = array(), $type = 'main' ) {
        // If insight type is not set, early return.
        if ( ! $this->insight_type || $type !== $this->insight_type ) {
            return $instances;
        }

        // Add the insight to the instances.
        $instances[ $this->insight_id ] = $this;
        return $instances;
    }

    /**
     * Regenerate the insight.
     *
     * @return void
     */
    public function regenerate_insight() {
        // Delete the transient to force regeneration.
        delete_transient( $this->transient_name );

        // Schedule cron to regenerate insight.
        $schedule_action = sprintf( '%s_schedule_action', $this->transient_name );
        if ( ! wp_next_scheduled( $schedule_action ) ) {
            wp_schedule_single_event( time(), $schedule_action );
        }
    }

    /**
     * Schedule cron to regenerate insight.
     *
     * @return void
     */
    public function schedule_regenerate_insight() {
        // Return if schedule is already set.
        $schedule_action = sprintf( '%s_regenerate_insight', $this->transient_name );
        $main_schedule   = wp_next_scheduled( $schedule_action );
        if ( $main_schedule ) {
            return;
        }

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

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

        // Calculate initial send time.
        $init_send = time() + $offset;

        // Schedule new event if none exists.
        if ( ! $main_schedule ) {
            $schedule = $this->insight_schedule ? $this->insight_schedule : 'daily';
            wp_schedule_event( $init_send, $schedule, $schedule_action );
        }
    }

    /**
     * Get insight id.
     *
     * @return string
     */
    public function get_insight_id() {
        return $this->insight_id;
    }
}
