<?php
/**
 * Slides List View
 *
 * @package SlideMind
 * @since 2.0.0
 */

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

// Fetch data
$plugin = \SlideMind\Plugin::instance();
$config_repo = $plugin->get_config_repository();

// Filters
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Nonce verified in controller.
$course_id = isset($_GET['course_id']) ? (int) $_GET['course_id'] : 0;
$module_id = isset($_GET['module_id']) ? (int) $_GET['module_id'] : 0;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$module = null;
$course = null;

if ($module_id) {
    $module = $config_repo->get_module($module_id);
    if ($module) {
        $course = $config_repo->get_course($module['parent_course_id']);
        $course_id = (int) $module['parent_course_id'];
    }
    $slides = $config_repo->get_slides_by_module($module_id);
} elseif ($course_id) {
    $course = $config_repo->get_course($course_id);
    // Fetch all slides and filter by course
    $all_slides = $config_repo->get_all_slides();
    $slides = array_values(array_filter($all_slides, function ($s) use ($course_id) {
        return (int) $s['parent_course_id'] === $course_id;
    }));
} else {
    $slides = $config_repo->get_all_slides();
}

// Quick stats
function slidemind_get_slide_stats($slide_id) {
    global $wpdb;
    $table_logs = $wpdb->prefix . 'slidemind_logs';
    // phpcs:disable WordPress.DB.DirectDatabaseQuery
    return $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(*) as calls, SUM(estimated_cost) as cost
        FROM %i WHERE config_id = %d",
        $table_logs,
        $slide_id
    ));
    // phpcs:enable WordPress.DB.DirectDatabaseQuery
}

// Lists for filters
$courses = $config_repo->get_courses();
$modules = $course_id
    ? $config_repo->get_modules_by_course($course_id)
    : $config_repo->get_all_modules();

$has_api_key = \SlideMind\Plugin::instance()->get_api_key_manager()->has_any_api_key();
$no_create   = ! $has_api_key;
?>

<div class="sm-wrap">
    <div class="sm-header">
        <h1>
            <?php esc_html_e('Slides', 'slidemind'); ?>
            <?php if ($module): ?>
                <small style="font-weight: normal; color: #6b7280;">
                    — <?php echo esc_html($module['title']); ?>
                    <?php if ($course): ?>
                        (<?php echo esc_html($course['title']); ?>)
                    <?php endif; ?>
                </small>
            <?php elseif ($course): ?>
                <small style="font-weight: normal; color: #6b7280;">
                    — <?php echo esc_html($course['title']); ?>
                </small>
            <?php endif; ?>
        </h1>
        <div class="sm-header-actions">
            <?php if ($module_id || $course_id): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-slides')); ?>" class="sm-btn sm-btn-secondary">
                    <?php esc_html_e('View all slides', 'slidemind'); ?>
                </a>
            <?php endif; ?>
            <?php if (!empty($slides)) : ?>
                <button type="button" class="sm-btn sm-btn-secondary sm-export-type-btn" data-export-type="slides">
                    <span class="dashicons dashicons-download"></span>
                    <?php esc_html_e('Export all', 'slidemind'); ?>
                </button>
            <?php endif; ?>
            <button type="button" class="sm-btn sm-btn-secondary" data-sm-modal="sm-import-modal">
                <span class="dashicons dashicons-upload"></span>
                <?php esc_html_e('Import slide(s)', 'slidemind'); ?>
            </button>
            <?php if ($no_create) : ?>
                <button type="button" class="sm-btn sm-btn-primary" disabled>
                    <span class="dashicons dashicons-plus-alt2"></span>
                    <?php esc_html_e('New slide', 'slidemind'); ?>
                </button>
            <?php else : ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-new' . ($module_id ? '&module_id=' . $module_id : ''))); ?>" class="sm-btn sm-btn-primary">
                    <span class="dashicons dashicons-plus-alt2"></span>
                    <?php esc_html_e('New slide', 'slidemind'); ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if ( ! $has_api_key ) : ?>
        <div class="sm-notice sm-notice-warning" style="margin-bottom: 20px;">
            <strong><?php esc_html_e( 'API key missing', 'slidemind' ); ?></strong> —
            <?php esc_html_e( 'Configure an API key in Settings to create and import slides.', 'slidemind' ); ?>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=slidemind-settings' ) ); ?>">
                <?php esc_html_e( 'Go to Settings', 'slidemind' ); ?>
            </a>
        </div>
    <?php endif; ?>

    <?php if (!empty($courses) || !empty($modules)): ?>
    <!-- Filters by course / module -->
    <div class="sm-card" style="margin-bottom: 20px; padding: 16px;">
        <form method="get" style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
            <input type="hidden" name="page" value="slidemind-slides">
            <?php if (!empty($courses)): ?>
                <label for="filter-course" style="font-weight: 500;"><?php esc_html_e('Course:', 'slidemind'); ?></label>
                <select id="filter-course" name="course_id" class="sm-form-select" style="width: auto; min-width: 250px;" onchange="var m=this.form.querySelector('#filter-module'); if(m) m.value=''; this.form.submit()">
                    <option value=""><?php esc_html_e('All courses', 'slidemind'); ?></option>
                    <?php foreach ($courses as $f): ?>
                        <option value="<?php echo esc_attr($f['id']); ?>" <?php selected($course_id, $f['id']); ?>>
                            <?php echo esc_html($f['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            <?php endif; ?>
            <?php if (!empty($modules)): ?>
                <label for="filter-module" style="font-weight: 500;"><?php esc_html_e('Module:', 'slidemind'); ?></label>
                <select id="filter-module" name="module_id" class="sm-form-select" style="width: auto; min-width: 300px;" onchange="this.form.submit()">
                    <option value=""><?php echo $course_id ? esc_html__('All modules in this course', 'slidemind') : esc_html__('All modules', 'slidemind'); ?></option>
                    <?php foreach ($modules as $m): ?>
                        <option value="<?php echo esc_attr($m['id']); ?>" <?php selected($module_id, $m['id']); ?>>
                            <?php echo $course_id ? esc_html($m['title']) : esc_html($m['parent_course_title'] . ' / ' . $m['title']); ?> (<?php echo esc_html($m['slides_count']); ?> slides)
                        </option>
                    <?php endforeach; ?>
                </select>
            <?php endif; ?>
        </form>
    </div>
    <?php endif; ?>

    <div class="sm-card">
        <?php if (empty($slides)): ?>
            <div class="sm-empty-state">
                <svg class="sm-empty-state-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
                <h3 class="sm-empty-state-title"><?php esc_html_e('No slides', 'slidemind'); ?></h3>
                <p class="sm-empty-state-description">
                    <?php if ($module): ?>
                        <?php
                        /* translators: %s: module title */
                        printf(esc_html__('Create your first slide (AI interaction) for "%s".', 'slidemind'), esc_html($module['title']));
                        ?>
                    <?php elseif (empty($modules) && !\SlideMind\Core\FeatureGate::has_dialogue()): ?>
                        <?php esc_html_e('Create your first AI slide.', 'slidemind'); ?>
                    <?php elseif (empty($modules)): ?>
                        <?php esc_html_e('You must first create a course and a module.', 'slidemind'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Create your first slide to enable AI in your e-learning courses.', 'slidemind'); ?>
                    <?php endif; ?>
                </p>
                <?php if ($no_create) : ?>
                    <button type="button" class="sm-btn sm-btn-primary" disabled>
                        <?php esc_html_e('Create a slide', 'slidemind'); ?>
                    </button>
                <?php else: ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-new' . ($module_id ? '&module_id=' . $module_id : ''))); ?>" class="sm-btn sm-btn-primary">
                        <?php esc_html_e('Create a slide', 'slidemind'); ?>
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <table class="sm-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e('#', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Slide', 'slidemind'); ?></th>
                        <?php if (!$module_id && !$course_id): ?>
                            <th><?php esc_html_e('Course / Module', 'slidemind'); ?></th>
                        <?php elseif (!$module_id && $course_id): ?>
                            <th><?php esc_html_e('Module', 'slidemind'); ?></th>
                        <?php endif; ?>
                        <th><?php esc_html_e('Mode', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Model', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Integration code', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Calls', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Status', 'slidemind'); ?></th>
                        <th><?php esc_html_e('Actions', 'slidemind'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    foreach ($slides as $slide):
                        $stats = slidemind_get_slide_stats($slide['id']);
                    ?>
                        <tr>
                            <td>
                                <?php echo $slide['slide_number'] ? esc_html($slide['slide_number']) : '—'; ?>
                            </td>
                            <td>
                                <strong><?php echo esc_html($slide['title']); ?></strong>
                            </td>
                            <?php if (!$module_id && !$course_id): ?>
                                <td>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-slides&module_id=' . $slide['parent_module_id'])); ?>">
                                        <?php echo esc_html($slide['parent_course_title'] . ' / ' . $slide['parent_module_title']); ?>
                                    </a>
                                </td>
                            <?php elseif (!$module_id && $course_id): ?>
                                <td>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-slides&module_id=' . $slide['parent_module_id'])); ?>">
                                        <?php echo esc_html($slide['parent_module_title']); ?>
                                    </a>
                                </td>
                            <?php endif; ?>
                            <td>
                                <?php
                                $mode_labels = [
                                    'qa'      => __('Q&A', 'slidemind'),
                                    'chat'    => __('Chat', 'slidemind'),
                                    'capture' => __('Capture', 'slidemind'),
                                ];
                                $mode = $slide['widget_mode'] ?? '';
                                echo esc_html($mode_labels[$mode] ?? $mode);
                                ?>
                            </td>
                            <td>
                                <?php if (($slide['widget_mode'] ?? 'qa') === 'capture'): ?>
                                    <span class="sm-badge sm-badge-info">Capture</span>
                                <?php else: ?>
                                    <code style="font-size: 11px;"><?php echo esc_html($slide['model_id']); ?></code>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="sm-copyable">
                                    <code style="font-size: 11px;"><?php echo esc_html($slide['config_uid']); ?></code>
                                    <button type="button" class="sm-copyable-btn sm-copy-integration"
                                        data-config-uid="<?php echo esc_attr($slide['config_uid']); ?>"
                                        data-widget-mode="<?php echo esc_attr($slide['widget_mode'] ?? 'qa'); ?>"
                                        data-editor-input-var="<?php echo esc_attr($slide['editor_input_var'] ?? 'userMessage'); ?>"
                                        data-editor-output-var="<?php echo esc_attr($slide['editor_output_var'] ?? 'aiResponse'); ?>"
                                        data-has-memory="<?php echo strpos($slide['system_prompt'] ?? '', '{{memory.') !== false ? '1' : '0'; ?>"
                                        data-memory-variables="<?php echo esc_attr(wp_json_encode($slide['memory_variables'] ?? [])); ?>"
                                        title="<?php esc_attr_e('Copy integration code', 'slidemind'); ?>">
                                        <span class="dashicons dashicons-clipboard"></span>
                                    </button>
                                </div>
                            </td>
                            <td><?php echo esc_html(number_format($stats->calls ?: 0)); ?></td>
                            <td>
                                <?php if ($slide['status'] === 'publish'): ?>
                                    <span class="sm-badge sm-badge-success"><?php esc_html_e('Active', 'slidemind'); ?></span>
                                <?php elseif ($slide['status'] === 'draft'): ?>
                                    <span class="sm-badge sm-badge-warning"><?php esc_html_e('Draft', 'slidemind'); ?></span>
                                <?php else: ?>
                                    <span class="sm-badge"><?php echo esc_html($slide['status']); ?></span>
                                <?php endif; ?>

                                <?php if ($slide['has_custom_key']): ?>
                                    <span class="sm-badge sm-badge-info" title="<?php esc_attr_e('Uses a specific API key', 'slidemind'); ?>"><?php esc_html_e('Custom key', 'slidemind'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="sm-table-actions">
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=slidemind-slide-edit&slide_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>
                                    <?php if (($slide['widget_mode'] ?? 'qa') !== 'capture'): ?>
                                    <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('Test', 'slidemind'); ?>">
                                        <span class="dashicons dashicons-visibility"></span>
                                    </a>
                                    <?php endif; ?>
                                    <button type="button"
                                            class="sm-btn sm-btn-sm sm-btn-secondary sm-export-slide"
                                            data-slide-id="<?php echo esc_attr($slide['id']); ?>"
                                            title="<?php esc_attr_e('Export slide', 'slidemind'); ?>">
                                        <span class="dashicons dashicons-download"></span>
                                    </button>
                                    <button type="button"
                                            class="sm-btn sm-btn-sm sm-btn-secondary sm-delete-slide"
                                            data-slide-id="<?php echo esc_attr($slide['id']); ?>"
                                            title="<?php esc_attr_e('Delete', 'slidemind'); ?>">
                                        <span class="dashicons dashicons-trash"></span>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<!-- Import slide modal -->
<div class="sm-modal-overlay" id="sm-import-modal">
    <div class="sm-modal">
        <div class="sm-modal-header">
            <h3><?php esc_html_e('Import slide(s)', 'slidemind'); ?></h3>
            <button type="button" class="sm-modal-close">&times;</button>
        </div>
        <div class="sm-modal-body">
            <?php if (!empty($courses)): ?>
            <div class="sm-form-group">
                <label class="sm-form-label" for="sm-import-target-course">
                    <?php esc_html_e('Target course (optional)', 'slidemind'); ?>
                </label>
                <select id="sm-import-target-course" class="sm-form-select">
                    <option value=""><?php esc_html_e('— No course —', 'slidemind'); ?></option>
                    <?php foreach ($courses as $f): ?>
                        <option value="<?php echo esc_attr($f['id']); ?>"
                            <?php selected($course_id, $f['id']); ?>>
                            <?php echo esc_html($f['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <?php if (!empty($modules)): ?>
            <div class="sm-form-group">
                <label class="sm-form-label" for="sm-import-target-module">
                    <?php esc_html_e('Target module (optional)', 'slidemind'); ?>
                </label>
                <select id="sm-import-target-module" class="sm-form-select">
                    <option value=""><?php esc_html_e('— No module —', 'slidemind'); ?></option>
                    <?php foreach ($modules as $m): ?>
                        <option value="<?php echo esc_attr($m['id']); ?>"
                            <?php selected($module_id, $m['id']); ?>>
                            <?php echo esc_html($m['parent_course_title'] . ' / ' . $m['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div class="sm-form-group">
                <label class="sm-form-label" for="sm-import-file">
                    <?php esc_html_e('JSON file', 'slidemind'); ?>
                </label>
                <input type="file" id="sm-import-file" accept=".json" class="sm-form-input">
            </div>
            <div class="sm-form-group">
                <label class="sm-form-label" for="sm-import-json">
                    <?php esc_html_e('or paste the JSON content', 'slidemind'); ?>
                </label>
                <textarea id="sm-import-json" class="sm-form-input" rows="6"
                          placeholder="{ &quot;slidemind_export_version&quot;: &quot;1.0&quot;, &quot;export_type&quot;: &quot;slide&quot;, ... }"></textarea>
            </div>
            <div class="sm-form-group">
                <label class="sm-form-label" for="sm-import-action">
                    <?php esc_html_e('On collision', 'slidemind'); ?>
                </label>
                <select id="sm-import-action" class="sm-form-select">
                    <option value="duplicate" selected><?php esc_html_e('Duplicate (create a new copy)', 'slidemind'); ?></option>
                    <option value="overwrite"><?php esc_html_e('Overwrite (replace existing)', 'slidemind'); ?></option>
                    <option value="skip"><?php esc_html_e('Skip (ignore)', 'slidemind'); ?></option>
                </select>
            </div>
        </div>
        <div class="sm-modal-footer">
            <button type="button" class="sm-btn sm-btn-secondary sm-modal-close">
                <?php esc_html_e('Cancel', 'slidemind'); ?>
            </button>
            <button type="button" id="sm-do-import" class="sm-btn sm-btn-primary" data-type="slide">
                <span class="dashicons dashicons-upload"></span>
                <?php esc_html_e('Import', 'slidemind'); ?>
            </button>
        </div>
    </div>
</div>
