<?php

namespace Fab\Controller;

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

use Fab\Interfaces\JIT_Interface;

/**
 * Total Clicks
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Insight_Total_Clicks extends Insight_Type_Main implements JIT_Interface {

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
        $this->insight_id           = 'total_clicks';
        $this->transient_name       = 'fab_insights_total_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 0;
        }

        // Calculate the total clicks.
        $data = array_reduce(
            $fabs ?? array(),
            function ( $acc, $fab ) {
                return $acc + (int) get_post_meta( $fab['ID'], 'fab_total_clicked', true );
            },
            0
        );

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

        // On save post, regenerate the insight.
        add_action( 'fab_insights_total_clicks_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' ) );
    }
}
