<?php
/**
 * WooCommerce Dashboard Widgets for PrimeLink.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Core\Admin;

use PrimeLink\Modules\Imports\Service\StatisticsService;
use PrimeLink\Modules\Exports\Service\ExportStatisticsService;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class DashboardWidgets {

    /**
     * Register dashboard widgets.
     */
    public static function register() {
        add_action( 'wp_dashboard_setup', array( __CLASS__, 'add_widgets' ) );
    }

    /**
     * Add widgets to WooCommerce dashboard.
     */
    public static function add_widgets() {
        // Only show to users who can manage options
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        wp_add_dashboard_widget(
            'mt-primelink-recent-imports',
            __( 'PrimeLink: Recent Imports', 'primelink' ),
            array( __CLASS__, 'render_recent_imports' )
        );

        wp_add_dashboard_widget(
            'mt-primelink-import-stats',
            __( 'PrimeLink: Import Statistics (Last 7 Days)', 'primelink' ),
            array( __CLASS__, 'render_import_stats' )
        );

        wp_add_dashboard_widget(
            'mt-primelink-top-imports',
            __( 'PrimeLink: Top Performing Imports', 'primelink' ),
            array( __CLASS__, 'render_top_imports' )
        );

        wp_add_dashboard_widget(
            'mt-primelink-common-errors',
            __( 'PrimeLink: Common Errors', 'primelink' ),
            array( __CLASS__, 'render_common_errors' )
        );
    }

    /**
     * Render recent imports widget.
     */
    public static function render_recent_imports() {
        $drafts = get_option( 'mt_primelink_import_drafts', array() );
        $drafts = is_array( $drafts ) ? $drafts : array();

        // Get recent imports (last 5)
        $recent = array();
        foreach ( $drafts as $id => $draft ) {
            $state = get_option( 'mt_primelink_import_state_' . absint( $id ), array() );
            $recent[] = array(
                'id'        => $id,
                'type'      => $draft['type'] ?? ( $draft['step_data'][1]['type'] ?? 'product' ),
                'status'    => $state['status'] ?? 'idle',
                'created'   => $draft['created_at'] ?? '',
                'current'   => absint( $state['current'] ?? 0 ),
                'total'     => absint( $state['total'] ?? 0 ),
                'progress'  => absint( $state['progress'] ?? 0 ),
            );
        }

        // Sort by created date
        usort( $recent, function( $a, $b ) {
            $at = strtotime( $a['created'] ?? '' );
            $bt = strtotime( $b['created'] ?? '' );
            return $bt <=> $at;
        } );

        $recent = array_slice( $recent, 0, 5 );

        ?>
        <div class="mt-primelink-dashboard-widget">
            <?php if ( empty( $recent ) ) : ?>
                <p class="description"><?php esc_html_e( 'No imports yet. Start your first import to see activity here.', 'primelink' ); ?></p>
            <?php else : ?>
                <table class="widefat">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'ID', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Type', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Progress', 'primelink' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $recent as $import ) : ?>
                            <tr>
                                <td>
                                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-new-import&import_id=' . absint( $import['id'] ) ) ); ?>">
                                        #<?php echo absint( $import['id'] ); ?>
                                    </a>
                                </td>
                                <td><?php echo esc_html( ucfirst( $import['type'] ) ); ?></td>
                                <td>
                                    <span class="mt-primelink-status-badge status-<?php echo esc_attr( $import['status'] ); ?>">
                                        <?php echo esc_html( ucfirst( $import['status'] ) ); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ( $import['total'] > 0 ) : ?>
                                        <?php echo absint( $import['current'] ); ?> / <?php echo absint( $import['total'] ); ?>
                                        (<?php echo absint( $import['progress'] ); ?>%)
                                    <?php else : ?>
                                        &mdash;
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <p style="margin-top: 12px;">
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-manage-import' ) ); ?>" class="button">
                        <?php esc_html_e( 'View All Imports', 'primelink' ); ?>
                    </a>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render import statistics widget (last 7 days).
     */
    public static function render_import_stats() {
        $date_from = date( 'Y-m-d', strtotime( '-7 days' ) );
        $date_to   = date( 'Y-m-d' );

        $stats = StatisticsService::get_statistics( array(
            'date_from' => $date_from,
            'date_to'   => $date_to,
        ) );

        $overview = $stats['overview'] ?? array();
        $by_status = $stats['by_status'] ?? array();
        ?>
        <div class="mt-primelink-dashboard-widget">
            <div class="mt-primelink-stats-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 16px;">
                <div class="mt-primelink-stat-box" style="padding: 12px; background: #f0f6fc; border-radius: 4px;">
                    <div style="font-size: 24px; font-weight: 600; color: #2271b1;">
                        <?php echo absint( $overview['total_imports'] ?? 0 ); ?>
                    </div>
                    <div style="font-size: 12px; color: #646970; margin-top: 4px;">
                        <?php esc_html_e( 'Total Imports', 'primelink' ); ?>
                    </div>
                </div>
                <div class="mt-primelink-stat-box" style="padding: 12px; background: #f0f6fc; border-radius: 4px;">
                    <div style="font-size: 24px; font-weight: 600; color: #00a32a;">
                        <?php echo absint( ( $overview['total_created'] ?? 0 ) + ( $overview['total_updated'] ?? 0 ) ); ?>
                    </div>
                    <div style="font-size: 12px; color: #646970; margin-top: 4px;">
                        <?php esc_html_e( 'Items Processed', 'primelink' ); ?>
                    </div>
                </div>
                <div class="mt-primelink-stat-box" style="padding: 12px; background: #f0f6fc; border-radius: 4px;">
                    <div style="font-size: 24px; font-weight: 600; color: #d63638;">
                        <?php echo absint( $overview['total_errors'] ?? 0 ); ?>
                    </div>
                    <div style="font-size: 12px; color: #646970; margin-top: 4px;">
                        <?php esc_html_e( 'Errors', 'primelink' ); ?>
                    </div>
                </div>
                <div class="mt-primelink-stat-box" style="padding: 12px; background: #f0f6fc; border-radius: 4px;">
                    <div style="font-size: 24px; font-weight: 600; color: #2271b1;">
                        <?php echo esc_html( number_format( $overview['success_rate'] ?? 0, 1 ) ); ?>%
                    </div>
                    <div style="font-size: 12px; color: #646970; margin-top: 4px;">
                        <?php esc_html_e( 'Success Rate', 'primelink' ); ?>
                    </div>
                </div>
            </div>

            <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #ddd;">
                <strong><?php esc_html_e( 'By Status:', 'primelink' ); ?></strong>
                <ul style="margin: 8px 0 0 0; padding-left: 20px;">
                    <?php foreach ( $by_status as $status => $count ) : ?>
                        <li>
                            <?php echo esc_html( ucfirst( $status ) ); ?>: <strong><?php echo absint( $count ); ?></strong>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <p style="margin-top: 16px;">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-statistics' ) ); ?>" class="button">
                    <?php esc_html_e( 'View Full Statistics', 'primelink' ); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * Render top performing imports widget.
     */
    public static function render_top_imports() {
        $stats = StatisticsService::get_statistics();
        $top_imports = $stats['top_imports'] ?? array();
        $top_imports = array_slice( $top_imports, 0, 5 );

        ?>
        <div class="mt-primelink-dashboard-widget">
            <?php if ( empty( $top_imports ) ) : ?>
                <p class="description"><?php esc_html_e( 'No imports to display yet.', 'primelink' ); ?></p>
            <?php else : ?>
                <table class="widefat">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'ID', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Type', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Items', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'primelink' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $top_imports as $import ) : ?>
                            <tr>
                                <td>
                                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-new-import&import_id=' . absint( $import['id'] ) ) ); ?>">
                                        #<?php echo absint( $import['id'] ); ?>
                                    </a>
                                </td>
                                <td><?php echo esc_html( ucfirst( $import['type'] ) ); ?></td>
                                <td>
                                    <strong><?php echo absint( $import['created'] + $import['updated'] ); ?></strong>
                                    <?php if ( $import['created'] > 0 ) : ?>
                                        <span style="color: #00a32a;">(+<?php echo absint( $import['created'] ); ?>)</span>
                                    <?php endif; ?>
                                    <?php if ( $import['updated'] > 0 ) : ?>
                                        <span style="color: #2271b1;">(~<?php echo absint( $import['updated'] ); ?>)</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="mt-primelink-status-badge status-<?php echo esc_attr( $import['status'] ); ?>">
                                        <?php echo esc_html( ucfirst( $import['status'] ) ); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render common errors widget.
     */
    public static function render_common_errors() {
        $drafts = get_option( 'mt_primelink_import_drafts', array() );
        $drafts = is_array( $drafts ) ? $drafts : array();

        $errors = array();
        foreach ( $drafts as $id => $draft ) {
            $state = get_option( 'mt_primelink_import_state_' . absint( $id ), array() );
            $log = $state['log'] ?? array();

            if ( ! empty( $log ) && is_array( $log ) ) {
                foreach ( $log as $log_line ) {
                    $log_line = strtolower( $log_line );
                    if ( strpos( $log_line, 'error' ) !== false || strpos( $log_line, 'failed' ) !== false ) {
                        // Extract error message (simplified)
                        $error_key = $log_line;
                        if ( ! isset( $errors[ $error_key ] ) ) {
                            $errors[ $error_key ] = 0;
                        }
                        $errors[ $error_key ]++;
                    }
                }
            }
        }

        // Sort by frequency
        arsort( $errors );
        $errors = array_slice( $errors, 0, 5, true );

        ?>
        <div class="mt-primelink-dashboard-widget">
            <?php if ( empty( $errors ) ) : ?>
                <p class="description" style="color: #00a32a;">
                    <span class="dashicons dashicons-yes-alt" style="color: #00a32a;"></span>
                    <?php esc_html_e( 'No errors found in recent imports.', 'primelink' ); ?>
                </p>
            <?php else : ?>
                <ul style="margin: 0; padding-left: 20px;">
                    <?php foreach ( $errors as $error => $count ) : ?>
                        <li style="margin-bottom: 8px;">
                            <strong><?php echo absint( $count ); ?>x</strong>
                            <span style="color: #d63638;"><?php echo esc_html( substr( $error, 0, 100 ) ); ?><?php echo strlen( $error ) > 100 ? '...' : ''; ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <p style="margin-top: 12px;">
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-statistics' ) ); ?>" class="button">
                        <?php esc_html_e( 'View All Statistics', 'primelink' ); ?>
                    </a>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }
}

