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

class CGC_Post_Type {

    // Slug => WP_Query args distinguishing the three design categories:
    // Starters (plugin-offered inspiration, ping_status flips to 'open' via
    // the "starter" checkbox in the design editor - see save_template() in
    // class-cgc-rest-api.php), My Templates (site owner's own top-level
    // designs), and Personalized (customer designs created at checkout,
    // linked to their source template via post_parent - see
    // gift-card-view.ts's submit()).
    const DESIGN_CATEGORIES = array(
        'starters' => array(
            'label' => 'Starters',
            'post_parent' => 0,
            'ping_status' => 'open',
        ),
        'my-templates' => array(
            'label' => 'My Templates',
            'post_parent' => 0,
            'ping_status' => 'closed',
        ),
        'personalized' => array(
            'label' => 'Personalized',
            'post_parent__not_in' => array( 0 ),
        ),
    );

    public function __construct() {
        add_action( 'init', array( $this, 'register_custom_post_type' ) );

        //add custom meta box to the design post type
        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );


        //remove the submitdiv from the card design edit
        add_action( 'admin_menu', array( $this, 'remove_submitdiv_metabox' ) );

        add_filter( 'views_edit-cgc-design', array( $this, 'add_design_category_views' ) );
        add_action( 'pre_get_posts', array( $this, 'filter_designs_by_category' ) );

    }

    public function add_design_category_views( $views ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only GET filter link (like core's own list-table view filters), not a state-changing action; value is sanitized below.
        $current = isset( $_GET['design_category'] ) ? sanitize_key( $_GET['design_category'] ) : '';

        foreach ( self::DESIGN_CATEGORIES as $slug => $category ) {
            $count_query = new WP_Query( array_merge(
                array(
                    'post_type' => 'cgc-design',
                    'post_status' => 'any',
                    'fields' => 'ids',
                    'posts_per_page' => 1,
                ),
                wp_array_slice_assoc( $category, array( 'post_parent', 'post_parent__not_in', 'ping_status' ) )
            ) );

            $url = add_query_arg( array(
                'post_type' => 'cgc-design',
                'design_category' => $slug,
            ), admin_url( 'edit.php' ) );

            $views[ $slug ] = sprintf(
                '<a href="%s"%s>%s <span class="count">(%d)</span></a>',
                esc_url( $url ),
                $current === $slug ? ' class="current" aria-current="page"' : '',
                esc_html( $category['label'] ),
                $count_query->found_posts
            );
        }

        return $views;
    }

    public function filter_designs_by_category( $query ) {
        if ( ! is_admin() || ! $query->is_main_query() || 'cgc-design' !== $query->get( 'post_type' ) ) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only GET filter link (like core's own list-table view filters), not a state-changing action; value is sanitized below.
        $slug = isset( $_GET['design_category'] ) ? sanitize_key( $_GET['design_category'] ) : '';

        if ( ! isset( self::DESIGN_CATEGORIES[ $slug ] ) ) {
            return;
        }

        foreach ( wp_array_slice_assoc( self::DESIGN_CATEGORIES[ $slug ], array( 'post_parent', 'post_parent__not_in', 'ping_status' ) ) as $key => $value ) {
            $query->set( $key, $value );
        }
    }

  

    public function remove_submitdiv_metabox() {
        remove_meta_box( 'submitdiv', 'cgc-design', 'side' );

        //commentstatusdiv remove
        //commentsdiv remove
        remove_meta_box( 'commentstatusdiv', 'cgc-design', 'normal' );
        remove_meta_box( 'commentsdiv', 'cgc-design', 'normal' );

    }

    public function add_meta_boxes() {
        add_meta_box(
            'cgc_design_meta_box',
            'Design Details',
            array( $this, 'design_meta_box_callback' ),
            'cgc-design',
            'normal',
            'high'
        );
    }

    public function design_meta_box_callback( $post ) {
         //get deps
         $asset_file = include( CGC_PLUGIN_PATH . 'build/design-edit/index.asset.php');

         if( ! is_array($asset_file) ) {
             return;
         }
 
         // build/index
         wp_enqueue_script('cgc-design-edit', CGC_PLUGIN_URL . 'build/design-edit/index.js', $asset_file['dependencies'], CGC_PLUGIN_VERSION, true);
         wp_set_script_translations( 'cgc-design-edit', 'gift-card-studio', CGC_PLUGIN_PATH . 'languages' );

         wp_enqueue_style('cgc-design-edit', CGC_PLUGIN_URL . 'build/design-edit.css', array(), CGC_PLUGIN_VERSION);
         wp_enqueue_style( 'cgc-fonts', CGC_PLUGIN_URL . 'assets/fonts.css', array(), CGC_PLUGIN_VERSION );
         // This meta box only ever renders on the cgc-design post-edit
         // screen (already gated by WP core's own edit_post capability
         // check to get here at all), so no extra admin check needed - lets
         // the Page tab's Background Image field open the real WP media
         // library instead of just this plugin's own lightweight uploads list.
         wp_enqueue_media();


         $current_user = wp_get_current_user();
 
         $display_name = $current_user->display_name ?? '';
         $is_admin = current_user_can('administrator');
 
         global $cgc_fetch;
         if( ! $cgc_fetch ) return;

         $design = $cgc_fetch->get_design();

        $uploads = $cgc_fetch->get_user_uploads();

        $designs_path = CGC_PLUGIN_PATH . 'assets/designs/';
        $design_files = glob( $designs_path . '*.json' );

        $designs = array();

        foreach ( $design_files as $file ) {
            $designs[] = array(
                'file' => basename( $file ),
                'url'  => CGC_PLUGIN_URL . 'assets/designs/' . basename( $file ),
                'ver'  => '1.0.3'
            );
        }
 
         // "Midnight" is the only built-in wp-admin color scheme with an
         // actually dark background (the rest just vary the menu accent
         // color on a light admin) - closest available proxy for "does
         // this user want a dark UI" that WordPress itself exposes.
         $is_dark_mode = 'midnight' === get_user_option( 'admin_color' );

         wp_localize_script( 'cgc-design-edit', 'appData', array(
             'user_name' => $display_name,
             'rest_url' => rest_url( 'cgc/v2' ),
             'site_url' => site_url(),
             'nonce' => wp_create_nonce( 'wp_rest' ),
             'plugin_url' => CGC_PLUGIN_URL,
             'is_admin' => $is_admin,
             'is_dark_mode' => $is_dark_mode,
             'design' => $design,
             'starters' => $designs,
             'uploads' => $uploads,
             'action' => 'edit',
             'formFields' => CGC_Form_Fields::get_default_fields(),
         ) );


         // Create a div for the React app
         echo '
         <style>
            #cgc_design_meta_box {
                border: 0;
            }
            #cgc_design_meta_box .postbox-header {
                display: none;
            }
         </style>
         ';
         echo '<div class="design-edit"></div>';

    }

   
    public function register_custom_post_type() {
        //Card designs post type
        $labels = array(
            'name'               => _x( 'Designs', 'post type general name', 'gift-card-studio' ),
            'singular_name'      => _x( 'Design', 'post type singular name', 'gift-card-studio' ),
            'menu_name'          => _x( 'Designs', 'admin menu', 'gift-card-studio' ),
            'name_admin_bar'     => _x( 'Design', 'add new on admin bar', 'gift-card-studio' ),
            'add_new'            => _x( 'Add New', 'card design', 'gift-card-studio' ),
            'add_new_item'       => __( 'Add New Design', 'gift-card-studio' ),
            'new_item'           => __( 'New Design', 'gift-card-studio' ),
            'edit_item'          => __( 'Edit Design', 'gift-card-studio' ),
            'view_item'          => __( 'View Design', 'gift-card-studio' ),
            'all_items'          => __( 'All Designs', 'gift-card-studio' ),
            'search_items'       => __( 'Search Designs', 'gift-card-studio' ),
            'parent_item_colon'  => __( 'Parent Designs:', 'gift-card-studio' ),
            'not_found'          => __( 'No card designs found.', 'gift-card-studio' ),
            'not_found_in_trash' => __( 'No card designs found in Trash.', 'gift-card-studio' )
        );

        $args = array(
            'labels'             => $labels,
            'public'             => false,
            'publicly_queryable' => false,
            'show_in_rest'       => true,
            'show_ui'            => true,
            // Submenu under the top-level "GiftCard Studio" menu (see
            // class-cgc-admin-settings.php's register_menu(), same slug)
            // instead of its own separate top-level entry.
            'show_in_menu'       => 'giftcard-studio-settings',
            'query_var'          => true,
            'rewrite'            => array( 'slug' => 'card-design' ),
            'capability_type'    => 'post',
            'has_archive'        => false,
            'hierarchical'       => false,
            'menu_position'      => null,
            'supports'           => false
        );

        register_post_type( 'cgc-design', $args );

    }
}

new CGC_Post_Type();
?>