<?php

namespace Fab\Controller;

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

use Fab\Interfaces\JIT_Interface;

/**
 * Daily Clicks
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Insight_Daily_Clicks extends Insight_Type_Main implements JIT_Interface {

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
        $this->insight_id           = 'daily_clicks';
        $this->transient_name       = 'fab_insights_daily_clicks';
        $this->transient_expiration = 12 * HOUR_IN_SECONDS;
    }

    /**
     * Generate insight.
     *
     * @return int
     */
    public function generate_insight() {
        // Load all fabs.
        $fabs = \Fab\Api\Insights::get_instance()->load_all_fabs();

        // If $fabs is not an array, early return.
        if ( ! is_array( $fabs ) ) {
            return array();
        }

        // Group fabs by daily clicks.
        $data = array();
        foreach ( $fabs as $fab ) {
            $daily_data = get_post_meta( $fab['ID'], 'fab_daily_clicked', true );

            // If $daily_data is not an array, early return.
            if ( ! is_array( $daily_data ) ) {
                continue;
            }

            foreach ( $daily_data as $date => $clicks ) {
                if ( ! isset( $data[ $date ] ) ) {
                    $data[ $date ] = 0;
                }
                $data[ $date ] += $clicks;
            }
        }

        // Sort the array by key.
        ksort( $data );

        // Set the data to the cache.
        $this->set_transient( $data );

        // Return the data.
        return $data;
    }

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

    /**
     * JIT method.
     *
     * @return void
     */
    public static function jit() {
        // Load insight.
        add_filter( 'fab_insights_dashboard', array( __CLASS__, 'jit_load_insight' ), 10, 2 );

        // Schedule cron to regenerate insight.
        add_action( 'init', array( __CLASS__, 'jit_schedule_regenerate_insight' ) );
        add_action( 'fab_insights_daily_clicks_schedule_action', array( __CLASS__, 'jit_generate_insight' ) );
        add_action( 'fab_insights_daily_clicks_regenerate_insight', array( __CLASS__, 'jit_regenerate_insight' ) );
    }
}
