<?php

namespace Fab\Controller;

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

use Fab\Metabox\FABMetaboxSetting;
use Fab\Interfaces\JIT_Interface;

/**
 * Single Post.
 *
 * @package    Fab
 * @subpackage Fab/Module
 */
class Single_Post_Type_Template extends Single_Post_Type implements JIT_Interface {

    /**
     * Filter template title.
     *
     * @template
     *
     * @param string $title Title.
     * @param string $type Type.
     * @param object $data Data.
     * @return string
     */
    public function filter_template_title( $title, $type, $data ) {
        if ( $this->type !== $type || ! isset( $data->post_id ) ) {
            return $title;
        }

        // Get post title.
        $post = get_post( $data->post_id );
        if ( $post ) {
            // translators: %s will be replaced button title.
            $title = sprintf( __( '%s Button', 'floating-awesome-button' ), $post->post_title );
        }

        return $title;
    }

    /**
     * Filter template postmeta.
     *
     * @template
     *
     * @param array  $postmeta Array of postmeta.
     * @param string $type Type of postmeta.
     * @param object $data Data of postmeta.
     */
    public function filter_template_postmeta( $postmeta, $type, $data ) {
        if ( $this->type !== $type ) {
            return $postmeta;
        }

        // If post_id is empty, get random public post.
        if ( ! isset( $data->post_id ) || ! $data->post_id ) {
            $args = array(
                'post_type'      => isset( $data->settings->post_type ) ? $data->settings->post_type : 'post',
                'post_status'    => 'publish',
                'posts_per_page' => 1,
                'orderby'        => 'rand',
            );
            $post = get_posts( $args );

            if ( ! empty( $post ) ) {
                $data->post_id = $post[0]->ID;
            }
        }

        // Add post meta to postmeta.
        if ( isset( $data->post_id ) ) {
            $postmeta['fab_setting_post_id'] = $data->post_id;
        }

        return $postmeta;
    }

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

    /**
     * JIT Method.
     *
     * @return void
     */
    public static function jit() {
        // Filter template title.
        add_filter( 'fab_template_title', array( __CLASS__, 'jit_filter_template_title' ), 10, 3 );

        // Filter template postmeta.
        add_filter( 'fab_template_postmeta', array( __CLASS__, 'jit_filter_template_postmeta' ), 10, 3 );
    }
}
