<?php

/**
 * Dashboard View
 *
 * @package SlideMind
 * @since 2.0.0
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// ─── Data queries ────────────────────────────────────────────────────────────
global $wpdb;
$table_logs = $wpdb->prefix . 'slidemind_logs';
$table_memory = $wpdb->prefix . 'slidemind_learner_memory';
$config_repo = \SlideMind\Plugin::instance()->get_config_repository();
// Config counts by type (published only)
$courses = $config_repo->get_courses( 'publish' );
$modules = $config_repo->get_all_modules( 'publish' );
$slides = $config_repo->get_all_slides( 'publish' );
$count_courses = count( $courses );
$count_modules = count( $modules );
$count_slides = count( $slides );
// 30-day stats with success rate
// phpcs:disable WordPress.DB.DirectDatabaseQuery
$stats = $wpdb->get_row( $wpdb->prepare( "SELECT\n            COUNT(*) as total_calls,\n            SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_calls,\n            SUM(total_tokens) as total_tokens,\n            SUM(estimated_cost) as total_cost\n        FROM %i\n        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)", $table_logs ) );
$total_calls = (int) ($stats->total_calls ?? 0);
$success_calls = (int) ($stats->success_calls ?? 0);
$total_tokens = (int) ($stats->total_tokens ?? 0);
$total_cost = (float) ($stats->total_cost ?? 0);
$success_rate = ( $total_calls > 0 ? round( $success_calls / $total_calls * 100 ) : 100 );
// 24h errors
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Dashboard stats, no user input.
$recent_errors = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i\n        WHERE status = 'error' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)", $table_logs ) );
// Monthly cost projection (7-day average × 30)
$projection = get_transient( 'slidemind_dashboard_projection' );
if ( $projection === false ) {
    $projection_data = $wpdb->get_row( $wpdb->prepare( "SELECT\n                SUM(estimated_cost) as total_7d_cost,\n                COUNT(DISTINCT DATE(created_at)) as active_days\n            FROM %i\n            WHERE status = 'success' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)", $table_logs ) );
    $total_7d_cost = (float) ($projection_data->total_7d_cost ?? 0);
    $active_days = (int) ($projection_data->active_days ?? 0);
    if ( $active_days > 0 && $total_7d_cost > 0 ) {
        $avg_daily_cost = $total_7d_cost / $active_days;
        $monthly_projection = round( $avg_daily_cost * 30, 2 );
    } else {
        $monthly_projection = 0;
    }
    $projection = [
        'monthly'     => $monthly_projection,
        'daily_avg'   => ( $active_days > 0 ? round( $total_7d_cost / $active_days, 4 ) : 0 ),
        'active_days' => $active_days,
    ];
    set_transient( 'slidemind_dashboard_projection', $projection, 15 * MINUTE_IN_SECONDS );
}
$monthly_projection = (float) ($projection['monthly'] ?? 0);
// Recently modified slides (5)
$recent_slides_posts = get_posts( [
    'post_type'      => 'slidemind_config',
    'post_status'    => 'publish',
    'posts_per_page' => 5,
    'orderby'        => 'modified',
    'order'          => 'DESC',
    'meta_query'     => [[
        'key'   => '_slidemind_config_type',
        'value' => 'slide',
    ]],
] );
$recent_slides = [];
foreach ( $recent_slides_posts as $post ) {
    $slide = $config_repo->get_slide( $post->ID );
    if ( $slide ) {
        $recent_slides[] = $slide;
    }
}
// Top 5 slides by calls (30 days)
$top_slides = $wpdb->get_results( $wpdb->prepare( "SELECT\n            l.config_id,\n            p.post_title as title,\n            COUNT(*) as calls\n        FROM %i l\n        LEFT JOIN {$wpdb->posts} p ON l.config_id = p.ID\n        WHERE l.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)\n            AND p.ID IS NOT NULL\n        GROUP BY l.config_id\n        ORDER BY calls DESC\n        LIMIT 5", $table_logs ) );
// phpcs:enable WordPress.DB.DirectDatabaseQuery
$max_calls = ( !empty( $top_slides ) ? (int) $top_slides[0]->calls : 1 );
// Active learners count
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Dashboard stats, no user input.
$active_learners = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT wp_user_id) FROM %i", $table_memory ) );
// Success rate color
$rate_variant = 'success';
if ( $success_rate < 90 ) {
    $rate_variant = 'warning';
}
if ( $success_rate < 70 ) {
    $rate_variant = 'error';
}
$current_user = wp_get_current_user();
?>

<div class="sm-wrap">

    <?php 
// ─── Error Alert ───────────────────────────────────────────────────
?>
    <?php 
if ( $recent_errors > 0 ) {
    ?>
    <div class="sm-dashboard-alert sm-notice sm-notice-warning" id="sm-dashboard-alert">
        <span class="dashicons dashicons-warning"></span>
        <div>
            <?php 
    /* translators: %d: number of errors */
    printf( '<strong>' . esc_html( _n(
        '%d error',
        '%d errors',
        $recent_errors,
        'slidemind'
    ) ) . '</strong> ', intval( $recent_errors ) );
    ?>
            <?php 
    esc_html_e( 'in the last 24 hours.', 'slidemind' );
    ?>
            <a href="<?php 
    echo esc_url( admin_url( 'admin.php?page=slidemind-analytics' ) );
    ?>"><?php 
    esc_html_e( 'View details', 'slidemind' );
    ?></a>
        </div>
        <button type="button" class="sm-dashboard-alert-dismiss" id="sm-dismiss-alert" aria-label="<?php 
    esc_attr_e( 'Close', 'slidemind' );
    ?>">
            <span class="dashicons dashicons-no-alt"></span>
        </button>
    </div>
    <?php 
}
?>

    <?php 
// ─── Hero Header ───────────────────────────────────────────────────
?>
    <div class="sm-dashboard-hero">
        <div class="sm-dashboard-hero-top">
            <div class="sm-dashboard-hero-left">
                <img src="<?php 
echo esc_url( SLIDEMIND_PLUGIN_URL . 'images/slidemind-logo.png' );
?>"
                     alt="SlideMind"
                     class="sm-dashboard-logo-img">
                <div>
                    <h1 class="sm-dashboard-welcome-title">
                        <?php 
/* translators: %s: user display name */
printf( esc_html__( 'Welcome, %s', 'slidemind' ), esc_html( $current_user->display_name ) );
?>
                    </h1>
                    <p class="sm-dashboard-welcome-sub">
                        <?php 
esc_html_e( 'AI bridge for e-learning and persistent learner memory manager', 'slidemind' );
?>
                    </p>
                </div>
            </div>
            <div class="sm-dashboard-hero-right">
                <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-new' ) );
?>" class="sm-btn sm-btn-primary">
                    <span class="dashicons dashicons-plus-alt2"></span>
                    <?php 
esc_html_e( 'New slide', 'slidemind' );
?>
                </a>
            </div>
        </div>

        <div class="sm-dashboard-steps">
            <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-settings' ) );
?>" class="sm-dashboard-step">
                <span class="sm-dashboard-step-number">1</span>
                <div class="sm-dashboard-step-content">
                    <strong><?php 
esc_html_e( 'Configure API key', 'slidemind' );
?></strong>
                    <span><?php 
esc_html_e( 'Add your API key in the settings.', 'slidemind' );
?></span>
                </div>
            </a>
            <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-new' ) );
?>" class="sm-dashboard-step">
                <span class="sm-dashboard-step-number">2</span>
                <div class="sm-dashboard-step-content">
                    <strong><?php 
esc_html_e( 'Create a slide', 'slidemind' );
?></strong>
                    <span><?php 
esc_html_e( 'Create an AI slide for your course.', 'slidemind' );
?></span>
                </div>
            </a>
            <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-sandbox' ) );
?>" class="sm-dashboard-step">
                <span class="sm-dashboard-step-number">3</span>
                <div class="sm-dashboard-step-content">
                    <strong><?php 
esc_html_e( 'Test in Sandbox', 'slidemind' );
?></strong>
                    <span><?php 
esc_html_e( 'Test your slide before using it.', 'slidemind' );
?></span>
                </div>
            </a>
            <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-slides' ) );
?>" class="sm-dashboard-step">
                <span class="sm-dashboard-step-number">4</span>
                <div class="sm-dashboard-step-content">
                    <strong><?php 
esc_html_e( 'Integrate in your authoring tool', 'slidemind' );
?></strong>
                    <span><?php 
esc_html_e( 'Generate the integration code.', 'slidemind' );
?></span>
                </div>
            </a>
        </div>
    </div>

    <?php 
if ( \SlideMind\Core\FeatureGate::get_plan() === 'free' ) {
    ?>
        <div class="sm-upsell-card" style="margin-bottom: 24px;">
            <div class="sm-upsell-card-content" style="max-width: 700px;">
                <span class="sm-badge sm-badge-pro"><?php 
    esc_html_e( 'Unlock more with Pro', 'slidemind' );
    ?></span>
                <ul style="margin: 10px 0 14px; padding-left: 20px; line-height: 1.6;">
                    <li><?php 
    esc_html_e( 'Courses & Modules — organize slides with shared context and inherited prompts', 'slidemind' );
    ?></li>
                    <li><?php 
    esc_html_e( 'LMS Profile Sync — pull fields from BuddyBoss, LearnDash, WooCommerce and more', 'slidemind' );
    ?></li>
                    <li><?php 
    esc_html_e( 'External LMS Integration — Moodle, Docebo, Cornerstone, SCORM Cloud', 'slidemind' );
    ?></li>
                </ul>
                <?php 
    $upgrade_url = \SlideMind\Core\FeatureGate::get_upgrade_url();
    ?>
                <?php 
    if ( $upgrade_url ) {
        ?>
                    <a href="<?php 
        echo esc_url( $upgrade_url );
        ?>" class="sm-btn sm-btn-primary" target="_blank" rel="noopener noreferrer">
                        <?php 
        esc_html_e( 'See plans', 'slidemind' );
        ?>
                    </a>
                <?php 
    }
    ?>
            </div>
        </div>
    <?php 
}
?>

    <?php 
// ─── KPI Stats Row ─────────────────────────────────────────────────
?>
    <div class="sm-dashboard-stats">
        <div class="sm-dashboard-stat-card">
            <div class="sm-dashboard-stat-icon sm-dashboard-stat-icon--primary">
                <span class="dashicons dashicons-slides"></span>
            </div>
            <div class="sm-dashboard-stat-body">
                <div class="sm-dashboard-stat-value"><?php 
echo esc_html( $count_slides );
?></div>
                <div class="sm-dashboard-stat-label"><?php 
esc_html_e( 'Active slides', 'slidemind' );
?></div>
                <div class="sm-dashboard-stat-sub">
                    <?php 
if ( \SlideMind\Core\FeatureGate::has_dialogue() || intval( $count_courses ) > 0 ) {
    ?>
                        <?php 
    /* translators: %1$d: course count, %2$d: module count */
    printf( esc_html__( '%1$d courses, %2$d modules', 'slidemind' ), intval( $count_courses ), intval( $count_modules ) );
    ?>
                    <?php 
} else {
    ?>
                        <?php 
    esc_html_e( 'Standalone mode', 'slidemind' );
    ?>
                    <?php 
}
?>
                </div>
            </div>
        </div>

        <div class="sm-dashboard-stat-card">
            <div class="sm-dashboard-stat-icon sm-dashboard-stat-icon--info">
                <span class="dashicons dashicons-rest-api"></span>
            </div>
            <div class="sm-dashboard-stat-body">
                <div class="sm-dashboard-stat-value"><?php 
echo esc_html( number_format( $total_calls ) );
?></div>
                <div class="sm-dashboard-stat-label"><?php 
esc_html_e( 'API calls', 'slidemind' );
?></div>
                <div class="sm-dashboard-stat-sub"><?php 
esc_html_e( 'Last 30 days', 'slidemind' );
?></div>
            </div>
        </div>

        <div class="sm-dashboard-stat-card">
            <div class="sm-dashboard-stat-icon sm-dashboard-stat-icon--warning">
                <span class="dashicons dashicons-database"></span>
            </div>
            <div class="sm-dashboard-stat-body">
                <div class="sm-dashboard-stat-value"><?php 
echo esc_html( number_format( $total_tokens ) );
?></div>
                <div class="sm-dashboard-stat-label"><?php 
esc_html_e( 'Tokens used', 'slidemind' );
?></div>
                <div class="sm-dashboard-stat-sub"><?php 
esc_html_e( 'Last 30 days', 'slidemind' );
?></div>
            </div>
        </div>

        <div class="sm-dashboard-stat-card">
            <div class="sm-dashboard-stat-icon sm-dashboard-stat-icon--success">
                <span class="dashicons dashicons-chart-area"></span>
            </div>
            <div class="sm-dashboard-stat-body">
                <div class="sm-dashboard-stat-value">$<?php 
echo esc_html( number_format( $total_cost, 2 ) );
?></div>
                <div class="sm-dashboard-stat-label"><?php 
esc_html_e( 'Estimated cost', 'slidemind' );
?></div>
                <div class="sm-dashboard-stat-sub"><?php 
esc_html_e( 'Last 30 days', 'slidemind' );
?></div>
                <?php 
if ( $monthly_projection > 0 ) {
    ?>
                    <div class="sm-dashboard-stat-projection">
                        <span class="dashicons dashicons-arrow-right-alt" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span>
                        <?php 
    /* translators: %s: projected monthly cost */
    printf( esc_html__( '~$%s/month at this rate', 'slidemind' ), esc_html( number_format( $monthly_projection, 2 ) ) );
    ?>
                    </div>
                <?php 
}
?>
            </div>
        </div>

        <div class="sm-dashboard-stat-card">
            <div class="sm-dashboard-stat-icon sm-dashboard-stat-icon--<?php 
echo esc_attr( $rate_variant );
?>">
                <span class="dashicons dashicons-yes-alt"></span>
            </div>
            <div class="sm-dashboard-stat-body">
                <div class="sm-dashboard-stat-value"><?php 
echo esc_html( $success_rate );
?>%</div>
                <div class="sm-dashboard-stat-label"><?php 
esc_html_e( 'Success rate', 'slidemind' );
?></div>
                <div class="sm-dashboard-stat-sub">
                    <?php 
/* translators: %d: number of active learners */
printf( esc_html( _n(
    '%d active learner',
    '%d active learners',
    $active_learners,
    'slidemind'
) ), intval( $active_learners ) );
?>
                </div>
            </div>
        </div>
    </div>

    <?php 
// ─── Two-Column Layout ─────────────────────────────────────────────
?>
    <div class="sm-dashboard-columns">

        <?php 
// ── Left column: Recent slides ──────────────────────────────────
?>
        <div class="sm-dashboard-col-main">
            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Recently modified slides', 'slidemind' );
?></h2>
                    <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-slides' ) );
?>" class="sm-btn sm-btn-sm sm-btn-secondary">
                        <?php 
esc_html_e( 'View all', 'slidemind' );
?>
                    </a>
                </div>

                <?php 
if ( empty( $recent_slides ) ) {
    ?>
                    <div class="sm-empty-state" style="padding: 40px 20px;">
                        <div class="sm-empty-state-icon">
                            <span class="dashicons dashicons-slides" style="font-size: 48px; width: 48px; height: 48px;"></span>
                        </div>
                        <div class="sm-empty-state-title"><?php 
    esc_html_e( 'No slides yet', 'slidemind' );
    ?></div>
                        <div class="sm-empty-state-description"><?php 
    esc_html_e( 'Create your first AI slide to get started.', 'slidemind' );
    ?></div>
                        <a href="<?php 
    echo esc_url( admin_url( 'admin.php?page=slidemind-new' ) );
    ?>" class="sm-btn sm-btn-primary">
                            <span class="dashicons dashicons-plus-alt2"></span>
                            <?php 
    esc_html_e( 'New slide', 'slidemind' );
    ?>
                        </a>
                    </div>
                <?php 
} else {
    ?>
                    <table class="sm-table">
                        <thead>
                            <tr>
                                <th><?php 
    esc_html_e( 'Title', 'slidemind' );
    ?></th>
                                <th><?php 
    esc_html_e( 'Location', 'slidemind' );
    ?></th>
                                <th><?php 
    esc_html_e( 'Modified', 'slidemind' );
    ?></th>
                                <th><?php 
    esc_html_e( 'Actions', 'slidemind' );
    ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
    foreach ( $recent_slides as $slide ) {
        ?>
                            <tr>
                                <td>
                                    <span class="sm-dashboard-slide-title"><?php 
        echo esc_html( $slide['title'] );
        ?></span>
                                </td>
                                <td>
                                    <span class="sm-dashboard-slide-path">
                                        <?php 
        if ( !empty( $slide['parent_course_title'] ) ) {
            ?>
                                            <?php 
            echo esc_html( $slide['parent_course_title'] );
            ?>
                                            <span class="sm-dashboard-path-sep">/</span>
                                        <?php 
        }
        ?>
                                        <?php 
        if ( !empty( $slide['parent_module_title'] ) ) {
            ?>
                                            <?php 
            echo esc_html( $slide['parent_module_title'] );
            ?>
                                        <?php 
        }
        ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="sm-text-muted">
                                        <?php 
        $post_obj = get_post( $slide['id'] );
        if ( $post_obj ) {
            /* translators: %s: human-readable time difference */
            printf( esc_html__( '%s ago', 'slidemind' ), esc_html( human_time_diff( strtotime( $post_obj->post_modified ) ) ) );
        }
        ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="sm-table-actions">
                                        <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=slidemind-slide-edit&id=' . $slide['id'] ) );
        ?>"
                                           class="sm-btn sm-btn-sm sm-btn-secondary"
                                           title="<?php 
        esc_attr_e( 'Edit', 'slidemind' );
        ?>">
                                            <span class="dashicons dashicons-edit"></span>
                                        </a>
                                        <a href="<?php 
        echo esc_url( admin_url( 'admin.php?page=slidemind-sandbox&slide_id=' . $slide['id'] ) );
        ?>"
                                           class="sm-btn sm-btn-sm sm-btn-secondary"
                                           title="<?php 
        esc_attr_e( 'Sandbox', 'slidemind' );
        ?>">
                                            <span class="dashicons dashicons-visibility"></span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php 
    }
    ?>
                        </tbody>
                    </table>
                <?php 
}
?>
            </div>
        </div>

        <?php 
// ── Right column: Leaderboard + Quick access ─────────────────────
?>
        <div class="sm-dashboard-col-side">

            <?php 
// ── Leaderboard ──────────────────────────────────────────────
?>
            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Leaderboard', 'slidemind' );
?></h2>
                    <span class="sm-text-muted" style="font-size: 12px;"><?php 
esc_html_e( 'Last 30 days', 'slidemind' );
?></span>
                </div>

                <?php 
if ( empty( $top_slides ) ) {
    ?>
                    <p class="sm-text-muted" style="text-align: center; padding: 20px 0;">
                        <?php 
    esc_html_e( 'No data available.', 'slidemind' );
    ?>
                    </p>
                <?php 
} else {
    ?>
                    <div class="sm-dashboard-top-list">
                        <?php 
    foreach ( $top_slides as $rank => $item ) {
        ?>
                        <div class="sm-dashboard-top-item<?php 
        echo ( $rank === 0 ? ' sm-dashboard-top-item--gold' : '' );
        ?>">
                            <span class="sm-dashboard-top-rank"><?php 
        echo esc_html( $rank + 1 );
        ?></span>
                            <div class="sm-dashboard-top-info">
                                <span class="sm-dashboard-top-name"><?php 
        echo esc_html( ( $item->title ?: __( '(untitled)', 'slidemind' ) ) );
        ?></span>
                                <div class="sm-dashboard-top-bar-wrap">
                                    <div class="sm-dashboard-top-bar" style="width: <?php 
        echo esc_attr( round( $item->calls / $max_calls * 100 ) );
        ?>%;"></div>
                                </div>
                            </div>
                            <span class="sm-dashboard-top-count"><?php 
        echo esc_html( number_format( (int) $item->calls ) );
        ?></span>
                        </div>
                        <?php 
    }
    ?>
                    </div>
                <?php 
}
?>
            </div>

            <?php 
// ── Quick access ─────────────────────────────────────────────
?>
            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Quick access', 'slidemind' );
?></h2>
                </div>
                <div class="sm-dashboard-quick-links">
                    <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-sandbox' ) );
?>" class="sm-dashboard-quick-link">
                        <span class="dashicons dashicons-visibility"></span>
                        <?php 
esc_html_e( 'Sandbox', 'slidemind' );
?>
                    </a>
                    <?php 
?>
                    <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-settings' ) );
?>" class="sm-dashboard-quick-link">
                        <span class="dashicons dashicons-admin-generic"></span>
                        <?php 
esc_html_e( 'Settings', 'slidemind' );
?>
                    </a>
                    <a href="<?php 
echo esc_url( admin_url( 'admin.php?page=slidemind-memory' ) );
?>" class="sm-dashboard-quick-link">
                        <span class="dashicons dashicons-groups"></span>
                        <?php 
esc_html_e( 'Memory', 'slidemind' );
?>
                    </a>
                    <?php 
?>
                </div>
            </div>

        </div>
    </div>
</div>

<?php 
wp_add_inline_script( 'slidemind-admin-app', "jQuery(function(\$){ \$('#sm-dismiss-alert').on('click', function(){ \$('#sm-dashboard-alert').slideUp(200); }); });" );