<?php

namespace Fab\Controller;

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

use Fab\Interfaces\JIT_Interface;

/**
 * Type
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Insight_Type extends Insight_Type_Main implements JIT_Interface {

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
        $this->insight_id           = 'type';
        $this->transient_name       = 'fab_insights_type';
        $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 type.
        $data = array();
        foreach ( $fabs as $fab ) {
            if ( ! isset( $fab['type'] ) || empty( $fab['type'] ) ) {
                continue;
            }
            if ( ! isset( $data[ $fab['type'] ] ) ) {
                $data[ $fab['type'] ] = 0;
            }
            ++$data[ $fab['type'] ];
        }

        // 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 the insight on the dashboard.
        add_filter( 'fab_insights_dashboard', array( __CLASS__, 'jit_load_insight' ), 10, 2 );

        // On save post, regenerate the insight.
        add_action( 'fab_insights_type_schedule_action', array( __CLASS__, 'jit_generate_insight' ) );
        add_action( 'fab_save_post', array( __CLASS__, 'jit_regenerate_insight' ) );
        add_action( 'fab_after_add_new_template', array( __CLASS__, 'jit_regenerate_insight' ) );
    }
}
