<?php
    /**
     * Add archive meta
     *
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE\Admin;
    require_once get_template_directory() . '/inc/meta/base-meta.php';

    use BBE\Admin\Base_Meta as Base_Meta;
    use WP_Term;

    if( ! class_exists( __NAMESPACE__ . '\\Archive_Meta' ) ) {
        /**
         * Archive_Meta class
         */
        class Archive_Meta extends Base_Meta {
            /**
             * Nonce key
             * 
             * @since 1.0.0
             */
            private $nonce_key = 'bbe_taxonomy_nonce';

            /**
             * Nonce value
             * 
             * @since 1.0.0
             */
            private $nonce_value = 'bbe_taxonomy_nonce_value';

            /**
             * Taxonomy layout meta key
             * 
             * @since 1.0.0
             */
            private $taxonomy_layout_meta = 'bbe_taxonomy_layout_meta';

            /**
             * Taxonomy sidebar meta key
             * 
             * @since 1.0.0
             */
            private $taxonomy_sidebar_meta = 'bbe_taxonomy_sidebar_meta';

            /**
             * Taxonomy grid desktop number of columns
             * 
             * @since 1.0.0
             */
            private $taxonomy_grid_noc_desktop = 'bbe_taxonomy_grid_noc_desktop';

            /**
             * Taxonomy grid tablet number of columns
             * 
             * @since 1.0.0
             */
            private $taxonomy_grid_noc_tablet = 'bbe_taxonomy_grid_noc_tablet';

            /**
             * Taxonomy grid mobile number of columns
             * 
             * @since 1.0.0
             */
            private $taxonomy_grid_noc_mobile = 'bbe_taxonomy_grid_noc_mobile';

            /**
             * Taxonomy list number of columns
             * 
             * @since 1.0.0
             */
            private $taxonomy_list_noc = 'bbe_taxonomy_list_noc';

            /**
             * Instance
             *
             * @since 1.0.0
             */
            private static $instance = null;

            /**
             * Instance getter
             *
             * @since 1.0.0
             */
            public static function get_instance() {
                if( self::$instance === null ) {
                    self::$instance = new self();
                }
                return self::$instance;
            }

            /**
             * Constructor
             *
             * @see https://developer.wordpress.org/reference/hooks/taxonomy_edit_form_fields/
             * @see https://developer.wordpress.org/reference/hooks/created_taxonomy/
             * @see https://developer.wordpress.org/reference/hooks/edited_taxonomy/
             * @see https://developer.wordpress.org/reference/hooks/taxonomy_add_form_fields/
             * @since 1.0.0
             */
            private function __construct() {
                add_action( 'category_edit_form_fields', [ $this, 'update_meta_html' ] );
                add_action( 'post_tag_edit_form_fields', [ $this, 'update_meta_html' ] );
                add_action( 'category_add_form_fields', [ $this, 'render_meta_html' ] );
                add_action( 'post_tag_add_form_fields', [ $this, 'render_meta_html' ] );
                add_action( 'edited_category', [ $this, 'save_taxonomy_meta' ] );
                add_action( 'edited_post_tag', [ $this, 'save_taxonomy_meta' ] );
                add_action( 'create_category', [ $this, 'save_taxonomy_meta' ] );
                add_action( 'create_post_tag', [ $this, 'save_taxonomy_meta' ] );
            }

            /**
             * Update meta html
             * 
             * @see https://developer.wordpress.org/reference/hooks/taxonomy_edit_form_fields/
             * @param WP_Term $term Current taxonomy term object
             * @since 1.0.0
             */
            public function update_meta_html( $term ) {
                wp_nonce_field( $this->nonce_value, $this->nonce_key );
                $this->get_archive_layouts_html( $term, true );
                $this->get_sidebar_layouts_html( $term, $this->taxonomy_sidebar_meta, true );
                $this->get_number_of_columns_html( $term, true );
            }

            /**
             * Render meta html
             * 
             * @see https://developer.wordpress.org/reference/hooks/taxonomy_edit_form_fields/
             * @param WP_Term $term Current taxonomy term object
             * @since 1.0.0
             */
            public function render_meta_html( $term ) {
                wp_nonce_field( $this->nonce_value, $this->nonce_key );
                $this->get_archive_layouts_html( $term, false );
                $this->get_sidebar_layouts_html( $term, $this->taxonomy_sidebar_meta, false );
                $this->get_number_of_columns_html( $term, false );
            }

            /**
             * Render post layout html
             * 
             * @see https://developer.wordpress.org/reference/functions/get_post_meta/
             * @param WP_Term $post The current post
             * @param bool $update Whether the meta field is to update term or not
             * @since 1.0.0
             */
            private function get_archive_layouts_html( $term, $update ) {
                $layout = 'customizer-layout';
                if( $term instanceof WP_Term ) {
                    $layout = get_term_meta( $term->term_id, $this->taxonomy_layout_meta, true ) ?: 'customizer-layout';
                }

                $layouts = [
                    'customizer-layout'    =>  [
                        'label' =>  __( 'Customizer', 'blog-bee' ),
                        'url' =>    get_template_directory_uri() . '/inc/customizer/assets/images/customizer.webp',
                    ],
                    'list'  =>  [
                        'label' =>  esc_html__( 'List', 'blog-bee' ),
                        'url'   =>  get_template_directory_uri() . '/inc/customizer/assets/images/archive-list.webp'
                    ],
                    'grid'  =>  [
                        'label' =>  esc_html__( 'Grid', 'blog-bee' ),
                        'url'   =>  get_template_directory_uri() . '/inc/customizer/assets/images/archive-grid.webp'
                    ],
                    'list-alter'  =>  [
                        'label' =>  esc_html__( 'List Alter', 'blog-bee' ),
                        'url'   =>  get_template_directory_uri() . '/inc/customizer/assets/images/archive-list-alter.webp'
                    ],
                    'grid-alter'  =>  [
                        'label' =>  esc_html__( 'Grid Alter', 'blog-bee' ),
                        'url'   =>  get_template_directory_uri() . '/inc/customizer/assets/images/archive-grid-alter.webp'
                    ],
                ];
                if( $update ) :
                    ?>
                        <tr class="bbe-meta-field post-layout form-field">

                            <th class="heading"><?php esc_html_e( 'Archive Layouts', 'blog-bee' ); ?></th>

                            <?php $this->get_html( $layouts, $layout, $this->taxonomy_layout_meta, true ); ?>

                        </tr>
                        
                    <?php
                else:
                    ?>
                        <div class="bbe-meta-field post-layout">

                            <h2 class="heading"><?php esc_html_e( 'Archive Layouts', 'blog-bee' ); ?></h2>

                            <?php $this->get_html( $layouts, $layout, $this->taxonomy_layout_meta, false ); ?>

                        </div>
                        
                    <?php
                endif;
            }

            /**
             * Save to database
             * 
             * @param int $id Id of the taxonomy being saved
             * @since 1.0.0
             */
            public function save_taxonomy_meta( $term_id ) {
                /**
                 * Nonce verification to prevent CSRF attacks
                 */
                if( ! isset( $_POST[ $this->nonce_key ] ) || ! wp_verify_nonce( $_POST[ $this->nonce_key ], $this->nonce_value ) ) {
                    return;
                }

                /**
                 * Permission check
                 */
                if( ! current_user_can( 'edit_term', $term_id ) ) return;

                // Save
                if ( isset( $_POST[ $this->taxonomy_layout_meta ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_layout_meta,
                        sanitize_text_field( $_POST[ $this->taxonomy_layout_meta ] )
                    );
                }
                if ( isset( $_POST[ $this->taxonomy_sidebar_meta ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_sidebar_meta,
                        sanitize_text_field( $_POST[ $this->taxonomy_sidebar_meta ] )
                    );
                }
                if ( isset( $_POST[ $this->taxonomy_grid_noc_desktop ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_grid_noc_desktop,
                        absint( $_POST[ $this->taxonomy_grid_noc_desktop ] )
                    );
                }
                if ( isset( $_POST[ $this->taxonomy_grid_noc_tablet ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_grid_noc_tablet,
                        absint( $_POST[ $this->taxonomy_grid_noc_tablet ] )
                    );
                }
                if ( isset( $_POST[ $this->taxonomy_grid_noc_mobile ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_grid_noc_mobile,
                        absint( $_POST[ $this->taxonomy_grid_noc_mobile ] )
                    );
                }
                if ( isset( $_POST[ $this->taxonomy_list_noc ] ) ) {
                    update_term_meta(
                        $term_id,
                        $this->taxonomy_list_noc,
                        absint( $_POST[ $this->taxonomy_list_noc ] )
                    );
                }
            }

            /**
             * Number of columns
             * 
             * @param WP_Term $post The current post
             * @param bool $update Whether the meta field is to update term or not
             * @since 1.0.0
             */
            private function get_number_of_columns_html( $term, $update = false ) {
                $grid_noc_desktop = $grid_noc_tablet = $grid_noc_mobile = $list_noc = 1;
                if( $term instanceof WP_Term ) {
                    $grid_noc_desktop = get_term_meta( $term->term_id, $this->taxonomy_grid_noc_desktop, true ) ?: 1;
                    $grid_noc_tablet = get_term_meta( $term->term_id, $this->taxonomy_grid_noc_tablet, true ) ?: 1;
                    $grid_noc_mobile = get_term_meta( $term->term_id, $this->taxonomy_grid_noc_mobile, true ) ?: 1;
                    $list_noc = get_term_meta( $term->term_id, $this->taxonomy_list_noc, true ) ?: 1;
                }
                $grid_input_attrs = [
                    'min'   =>  1,
                    'max'   =>  5,
                    'step'  =>  1
                ];

                $grid_noc_args = [ 
                    'desktop'  =>  [
                        'label' =>  __( 'Desktop', 'blog-bee' ),
                        'meta_key'  =>  $this->taxonomy_grid_noc_desktop,
                        'meta_value'    =>  $grid_noc_desktop,
                        'input_attrs'   =>  $grid_input_attrs
                    ],
                    'tablet'  =>  [
                        'label' =>  __( 'Tablet', 'blog-bee' ),
                        'meta_key'  =>  $this->taxonomy_grid_noc_tablet,
                        'meta_value'    =>  $grid_noc_tablet,
                        'input_attrs'   =>  $grid_input_attrs
                    ],
                    'mobile'  =>  [
                        'label' =>  __( 'Mobile', 'blog-bee' ),
                        'meta_key'  =>  $this->taxonomy_grid_noc_mobile,
                        'meta_value'    =>  $grid_noc_mobile,
                        'input_attrs'   =>  $grid_input_attrs
                    ],
                ];

                $list_noc_args = [ 
                    'label' =>  '',
                    'meta_key'  =>  $this->taxonomy_list_noc,
                    'meta_value'    =>  $list_noc,
                    'input_attrs'   =>  [
                        'min'   =>  1,
                        'max'   =>  2,
                        'step'  =>  1
                    ]
                ];

                if( $update ) :
                    ?>
                        <tr class="bbe-meta-field no-of-columns form-field">

                            <th class="heading"><?php esc_html_e( 'Grid Number of Columns', 'blog-bee' ); ?></th>

                            <td class="form-field">

                                <?php
                                    if( ! empty( $grid_noc_args ) && is_array( $grid_noc_args ) ) :
                                        foreach( $grid_noc_args as $device => $noc_args ) :

                                            $this->render_number_of_columns( $noc_args );

                                        endforeach;
                                    endif;
                                ?>

                                <p class="description"><?php printf( esc_html__( 'Archive layouts other than %s should be selected.', 'blog-bee' ), '<strong>"Customizer Settings and List Layouts"</strong>' ); ?></p>
                            </td>

                        </tr>

                        <tr class="bbe-meta-field no-of-columns form-field">

                            <th class="heading"><?php esc_html_e( 'List Number of Columns', 'blog-bee' ); ?></th>

                            <td class="form-field">

                                <?php $this->render_number_of_columns( $list_noc_args ); ?>

                                <p class="description"><?php printf( esc_html__( 'Archive layouts other than %s should be selected.', 'blog-bee' ), '<strong>"Customizer Settings and Grid Layouts"</strong>' ); ?></p>
                                
                            </td>

                        </tr>

                    <?php
                else:
                    ?>
                        <div class="bbe-meta-field no-of-columns">

                            <h2 class="heading"><?php esc_html_e( 'Grid Number of Columns', 'blog-bee' ); ?></h2>

                            <div class="form-field">

                                <?php
                                    if( ! empty( $grid_noc_args ) && is_array( $grid_noc_args ) ) :
                                        foreach( $grid_noc_args as $device => $noc_args ) :

                                            $this->render_number_of_columns( $noc_args );

                                        endforeach;
                                    endif;
                                ?>

                                <p class="description"><?php printf( esc_html__( 'Archive layouts other than %s should be selected.', 'blog-bee' ), '<strong>"Customizer Settings and List Layouts"</strong>' ); ?></p>

                            </div>

                        </div>

                        <div class="bbe-meta-field no-of-columns">

                            <h2 class="heading"><?php esc_html_e( 'List Number of Columns', 'blog-bee' ); ?></h2>

                            <div class="form-field">

                                <?php

                                    $this->render_number_of_columns( $list_noc_args );

                                ?>

                                <p class="description"><?php printf( esc_html__( 'Archive layouts other than %s should be selected.', 'blog-bee' ), '<strong>"Customizer Settings and Grid Layouts"</strong>' ); ?></p>

                            </div>


                        </div>
                        
                    <?php
                endif;
            }

            /**
             * Render html
             * 
             * @param array $layouts    An array of layouts
             * @param string $layout    Currently selected layout
             * @param string $field_key    Field key
             * @since 1.0.0
             */
            protected function render_number_of_columns( $noc_args ) {
                $label = $noc_args[ 'label' ];
                $meta_key = $noc_args[ 'meta_key' ];
                $meta_value = $noc_args[ 'meta_value' ];
                $input_attrs = $noc_args[ 'input_attrs' ];

                echo '<div class="form-field-inner">';

                    if( $label ) echo '<label for="' . esc_attr( $meta_key ) .'" class="tag-name">' . esc_html( $label ) . '</label>';

                    echo '<input
                        name = "' . esc_attr( $meta_key ) . '"
                        id = "' . esc_attr( $meta_key ) . '"
                        type = "number"
                        value = "' . esc_attr( $meta_value ) . '"
                        min = "' . esc_attr( $input_attrs[ 'min' ] ) . '"
                        max = "' . esc_attr( $input_attrs[ 'max' ] ) . '"
                        step = "' . esc_attr( $input_attrs[ 'step' ] ) . '"
                    >';

                echo '</div>';
            }
        }
        Archive_Meta::get_instance();
    }
