<?php
/**
 * Dashboard page class
 *
 * @package ReplicateWP_Virtual_TryOn
 */

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

/**
 * Dashboard page class
 */
class RWPVTO_Dashboard {
    
    /**
     * Single instance
     *
     * @var RWPVTO_Dashboard
     */
    private static $instance = null;
    
    /**
     * Get instance
     *
     * @return RWPVTO_Dashboard
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_menu_page' ), 55 );
    }
    
    /**
     * Add menu page
     */
    public function add_menu_page() {
        add_menu_page(
            __( 'AI Virtual Try-On', 'ai-virtual-try-on-for-woocommerce' ),
            __( 'AI Virtual Try-On', 'ai-virtual-try-on-for-woocommerce' ),
            'edit_products',
            'rwpvto-dashboard',
            array( $this, 'render_page' ),
            'dashicons-camera',
            56
        );
        
        // Add dashboard as first submenu item
        add_submenu_page(
            'rwpvto-dashboard',
            __( 'Dashboard', 'ai-virtual-try-on-for-woocommerce' ),
            __( 'Dashboard', 'ai-virtual-try-on-for-woocommerce' ),
            'edit_products',
            'rwpvto-dashboard',
            array( $this, 'render_page' )
        );
    }
    
    /**
     * Render dashboard page
     */
    public function render_page() {
        if ( ! current_user_can( 'edit_products' ) ) {
            return;
        }
        
        // Get images
        $db = RWPVTO_Database::instance();
        $per_page = 40; // 5 rows of 8 columns in grid view
        
        // Verify nonce for filter parameters
        $nonce_verified = false;
        if ( isset( $_GET['rwpvto_filter_nonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_GET['rwpvto_filter_nonce'] ) );
            $nonce_verified = wp_verify_nonce( $nonce, 'rwpvto_dashboard_filters' );
        }
        
        // Only process GET parameters if nonce is verified, or if no filters are set (first page load)
        if ( $nonce_verified || ( ! isset( $_GET['s'] ) && ! isset( $_GET['gender'] ) && ! isset( $_GET['category'] ) && ! isset( $_GET['paged'] ) ) ) {
            $paged = isset( $_GET['paged'] ) ? max( 1, absint( $_GET['paged'] ) ) : 1;
            $search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
            $gender_filter = isset( $_GET['gender'] ) ? sanitize_text_field( wp_unslash( $_GET['gender'] ) ) : '';
            $category_filter = isset( $_GET['category'] ) ? sanitize_text_field( wp_unslash( $_GET['category'] ) ) : '';
        } else {
            // Invalid nonce or no nonce - use defaults
            $paged = 1;
            $search = '';
            $gender_filter = '';
            $category_filter = '';
        }
        
        $offset = ( $paged - 1 ) * $per_page;
        
        $images = $db->get_all_images( array(
            'limit' => $per_page,
            'offset' => $offset,
            'orderby' => 'created_at',
            'order' => 'DESC',
            'search' => $search,
            'gender' => $gender_filter,
            'category' => $category_filter,
        ) );
        
        $total_images = $db->get_total_count( $search, $gender_filter, $category_filter );
        $total_pages = ceil( $total_images / $per_page );
        
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'AI Virtual Try-On Dashboard', 'ai-virtual-try-on-for-woocommerce' ); ?></h1>
            
            <hr class="wp-header-end">
            
            <?php $this->render_stats(); ?>
            
            <div class="rwpvto-dashboard-content">
                <div class="rwpvto-dashboard-header">
                <h2><?php esc_html_e( 'Generated Images', 'ai-virtual-try-on-for-woocommerce' ); ?></h2>
                    <div class="rwpvto-view-toggle">
                        <button type="button" class="rwpvto-view-btn active" data-view="grid" title="<?php esc_attr_e( 'Grid View', 'ai-virtual-try-on-for-woocommerce' ); ?>">
                            <span class="dashicons dashicons-grid-view"></span>
                        </button>
                        <button type="button" class="rwpvto-view-btn" data-view="list" title="<?php esc_attr_e( 'List View', 'ai-virtual-try-on-for-woocommerce' ); ?>">
                            <span class="dashicons dashicons-list-view"></span>
                        </button>
                    </div>
                </div>
                
                <!-- Search and Filters -->
                <div class="rwpvto-filters">
                    <form method="get" action="" class="rwpvto-filter-form">
                        <input type="hidden" name="page" value="rwpvto-dashboard">
                        <?php wp_nonce_field( 'rwpvto_dashboard_filters', 'rwpvto_filter_nonce' ); ?>
                        
                        <div class="rwpvto-search-box">
                            <input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search by product name...', 'ai-virtual-try-on-for-woocommerce' ); ?>" class="rwpvto-search-input">
                        </div>
                        
                        <select name="gender" class="rwpvto-filter-select">
                            <option value=""><?php esc_html_e( 'All Genders', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                            <option value="male" <?php selected( $gender_filter, 'male' ); ?>><?php esc_html_e( 'Male', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                            <option value="female" <?php selected( $gender_filter, 'female' ); ?>><?php esc_html_e( 'Female', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                        </select>
                        
                        <select name="category" class="rwpvto-filter-select">
                            <option value=""><?php esc_html_e( 'All Categories', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                            <option value="upper_body" <?php selected( $category_filter, 'upper_body' ); ?>><?php esc_html_e( 'Upper Body', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                            <option value="lower_body" <?php selected( $category_filter, 'lower_body' ); ?>><?php esc_html_e( 'Lower Body', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                            <option value="dresses" <?php selected( $category_filter, 'dresses' ); ?>><?php esc_html_e( 'Dresses', 'ai-virtual-try-on-for-woocommerce' ); ?></option>
                        </select>
                        
                        <button type="submit" class="button">
                            <span class="dashicons dashicons-search"></span>
                            <?php esc_html_e( 'Filter', 'ai-virtual-try-on-for-woocommerce' ); ?>
                        </button>
                        
                        <?php if ( $search || $gender_filter || $category_filter ) : ?>
                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=rwpvto-dashboard' ) ); ?>" class="button">
                                <?php esc_html_e( 'Clear', 'ai-virtual-try-on-for-woocommerce' ); ?>
                            </a>
                        <?php endif; ?>
                    </form>
                    
                    <?php if ( $total_images > 0 ) : ?>
                        <div class="rwpvto-results-count">
                            <?php
                            $start = ( $paged - 1 ) * $per_page + 1;
                            $end = min( $paged * $per_page, $total_images );
                            printf(
                                /* translators: 1: start number, 2: end number, 3: total number */
                                esc_html__( 'Showing %1$d-%2$d of %3$d images', 'ai-virtual-try-on-for-woocommerce' ),
                                esc_html( $start ),
                                esc_html( $end ),
                                esc_html( $total_images )
                            );
                            ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <?php if ( empty( $images ) ) : ?>
                    <div class="rwpvto-no-images">
                        <p><?php esc_html_e( 'No generated images yet. Go to a WooCommerce product and generate your first virtual try-on!', 'ai-virtual-try-on-for-woocommerce' ); ?></p>
                    </div>
                <?php else : ?>
                    <div class="rwpvto-images-grid">
                        <?php foreach ( $images as $image ) : ?>
                            <?php $this->render_image_card( $image ); ?>
                        <?php endforeach; ?>
                    </div>
                    
                    <?php if ( $total_pages > 1 ) : ?>
                        <div class="tablenav">
                            <div class="tablenav-pages">
                                <?php
                                echo wp_kses_post(
                                    paginate_links( array(
                                        'base' => add_query_arg( 'paged', '%#%' ),
                                        'format' => '',
                                        'prev_text' => __( '&laquo;', 'ai-virtual-try-on-for-woocommerce' ),
                                        'next_text' => __( '&raquo;', 'ai-virtual-try-on-for-woocommerce' ),
                                        'total' => $total_pages,
                                        'current' => $paged,
                                    ) )
                                );
                                ?>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render stats section
     */
    private function render_stats() {
        $db = RWPVTO_Database::instance();
        
        // Total images
        $total_images = $db->get_total_count();
        
        // This month
        $month_start = gmdate('Y-m-01 00:00:00');
        $month_images = $db->get_count_since_date( $month_start );
        
        // This week
        $week_start = gmdate('Y-m-d 00:00:00', strtotime('monday this week'));
        $week_images = $db->get_count_since_date( $week_start );
        
        // Unique products
        $unique_products = $db->get_unique_products_count();
        
        ?>
        <div class="rwpvto-stats">
            <div class="rwpvto-stat-card rwpvto-stat-primary">
                <div class="rwpvto-stat-icon">
                    <span class="dashicons dashicons-images-alt2"></span>
                </div>
                <div class="rwpvto-stat-content">
                    <div class="rwpvto-stat-value"><?php echo esc_html( number_format_i18n( $total_images ) ); ?></div>
                    <div class="rwpvto-stat-label"><?php esc_html_e( 'Total Generated', 'ai-virtual-try-on-for-woocommerce' ); ?></div>
                </div>
            </div>
            
            <div class="rwpvto-stat-card rwpvto-stat-success">
                <div class="rwpvto-stat-icon">
                    <span class="dashicons dashicons-calendar-alt"></span>
                </div>
                <div class="rwpvto-stat-content">
                    <div class="rwpvto-stat-value"><?php echo esc_html( number_format_i18n( $month_images ) ); ?></div>
                    <div class="rwpvto-stat-label"><?php esc_html_e( 'This Month', 'ai-virtual-try-on-for-woocommerce' ); ?></div>
                </div>
            </div>
            
            <div class="rwpvto-stat-card rwpvto-stat-info">
                <div class="rwpvto-stat-icon">
                    <span class="dashicons dashicons-chart-line"></span>
                </div>
                <div class="rwpvto-stat-content">
                    <div class="rwpvto-stat-value"><?php echo esc_html( number_format_i18n( $week_images ) ); ?></div>
                    <div class="rwpvto-stat-label"><?php esc_html_e( 'This Week', 'ai-virtual-try-on-for-woocommerce' ); ?></div>
                </div>
            </div>
            
            <div class="rwpvto-stat-card rwpvto-stat-warning">
                <div class="rwpvto-stat-icon">
                    <span class="dashicons dashicons-products"></span>
                </div>
                <div class="rwpvto-stat-content">
                    <div class="rwpvto-stat-value"><?php echo esc_html( number_format_i18n( $unique_products ) ); ?></div>
                    <div class="rwpvto-stat-label"><?php esc_html_e( 'Products', 'ai-virtual-try-on-for-woocommerce' ); ?></div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Get the best available image URL (local first, then replicate)
     *
     * @param object $image Image object
     * @return string Image URL
     */
    private function get_image_url( $image ) {
        // Use local WordPress URL if available, otherwise fall back to replicate URL
        if ( ! empty( $image->local_image_url ) ) {
            return $image->local_image_url;
        }
        return $image->generated_image_url;
    }
    
    /**
     * Render image card
     *
     * @param object $image Image object
     */
    private function render_image_card( $image ) {
        $product = wc_get_product( $image->product_id );
        $product_name = $product ? $product->get_name() : __( 'Product Deleted', 'ai-virtual-try-on-for-woocommerce' );
        $product_url = $product ? get_edit_post_link( $image->product_id ) : '#';
        $image_url = $this->get_image_url( $image );
        
        ?>
        <div class="rwpvto-image-card" data-image-id="<?php echo esc_attr( $image->id ); ?>">
            <div class="rwpvto-image-preview">
                <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php esc_attr_e( 'Generated Try-On', 'ai-virtual-try-on-for-woocommerce' ); ?>">
            </div>
            <div class="rwpvto-image-info">
                <div class="rwpvto-image-title">
                    <a href="<?php echo esc_url( $product_url ); ?>" target="_blank">
                        <?php echo esc_html( $product_name ); ?>
                    </a>
                </div>
                <div class="rwpvto-image-meta">
                    <?php if ( ! empty( $image->model_gender ) ) : ?>
                        <span class="rwpvto-meta-item">
                            <strong><?php esc_html_e( 'Gender:', 'ai-virtual-try-on-for-woocommerce' ); ?></strong> 
                            <?php echo esc_html( ucfirst( $image->model_gender ) ); ?>
                        </span>
                    <?php endif; ?>
                    <?php if ( ! empty( $image->category ) ) : ?>
                        <span class="rwpvto-meta-item">
                            <strong><?php esc_html_e( 'Category:', 'ai-virtual-try-on-for-woocommerce' ); ?></strong> 
                            <?php echo esc_html( str_replace( '_', ' ', ucfirst( $image->category ) ) ); ?>
                        </span>
                    <?php endif; ?>
                    <span class="rwpvto-meta-item">
                        <strong><?php esc_html_e( 'Created:', 'ai-virtual-try-on-for-woocommerce' ); ?></strong> 
                        <?php echo esc_html( human_time_diff( strtotime( $image->created_at ), current_time( 'timestamp' ) ) ); ?> <?php esc_html_e( 'ago', 'ai-virtual-try-on-for-woocommerce' ); ?>
                    </span>
                </div>
                <div class="rwpvto-image-actions">
                    <button type="button" class="rwpvto-action-btn rwpvto-view-image-btn" data-image-url="<?php echo esc_url( $image_url ); ?>">
                        <span class="dashicons dashicons-visibility"></span>
                        <span><?php esc_html_e( 'View', 'ai-virtual-try-on-for-woocommerce' ); ?></span>
                    </button>
                    <button type="button" class="rwpvto-action-btn rwpvto-add-to-gallery-btn" data-image-id="<?php echo esc_attr( $image->id ); ?>" data-product-id="<?php echo esc_attr( $image->product_id ); ?>">
                        <span class="dashicons dashicons-plus-alt"></span>
                        <span><?php esc_html_e( 'Add to Gallery', 'ai-virtual-try-on-for-woocommerce' ); ?></span>
                    </button>
                    <button type="button" class="rwpvto-action-btn rwpvto-action-btn-danger rwpvto-delete-image-btn" data-image-id="<?php echo esc_attr( $image->id ); ?>">
                        <span class="dashicons dashicons-trash"></span>
                        <span><?php esc_html_e( 'Delete', 'ai-virtual-try-on-for-woocommerce' ); ?></span>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }
}

