<?php

namespace Reach\App\Fields\Options;

use Reach\App\Fields\RegisterFieldGroups;

/**
 * Class SiteOptionsTemplates
 *
 * registerFields()
 *
 * @package Reach\App\Fields\Options
 */
class SiteOptionsTemplates {

    /**
     * Register Template Tab fields into our Site Options parent group
     *
     * @return array
     *
     * @since 1.0.0
     */
    public function registerFields() {
        // get a list of our current pages
        $pages = get_pages( [
            'post_status' => [ 'publish', 'draft' ]
        ] );

        $fields = [
            [
                'key'       => 'field_591b74531375a',
                'label'     => __( 'Page Modules', 'reach' ),
                'type'      => 'tab',
                'placement' => 'left'
            ],
            [
                'key'     => 'field_591b74531375c',
                'type'    => 'message',
                'message' => __( 'Enable/Disable which modules will be available to the user on a per page basis.', 'reach' ),
            ]
        ];

        // Initial loop to pull Homepage to the front of the array
        $is_front_page    = get_option( 'page_on_front' );
        $front_page_array = [];
        foreach ( $pages as $index => $page ) {
            if ( (int) $is_front_page === $page->ID ) {
                $front_page_array = [ $pages[ $index ] ];
                unset( $pages[ $index ] );
            }
        }
        $results = array_merge( $front_page_array, $pages );

        // loop through existing pages and generate a module selection for each
        foreach ( $results as $index => $page ) {
            $fields[] = [
                'key'     => 'field_591b745d1375b' . $page->ID,
                'label'   => $page->post_title,
                'name'    => 'page_modules_' . $page->ID,
                'page_id' => $page->ID,
                'type'    => 'modules_select',
                'choices' => ( new RegisterFieldGroups() )->getFieldGroupOptions( $page->ID ),
                'wrapper' => [
                    'class' => 'page-modules',
                    'width' => '100'
                ]
            ];
        }

        return $fields;
    }
}