<?php
/**
 * Code Snippets Manager - Admin Page
 * Dashboard view with grid of snippets and edit/add functionality
 *
 * @package Switchboard
 * @since 1.0.0
 */

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

// Get all snippets
$snippets = get_option('switchboard_code_snippets', []);

// Determine current action
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
$snippet_id = isset($_GET['snippet_id']) ? sanitize_key($_GET['snippet_id']) : '';

// Get snippet data if editing
$snippet_data = null;
if ($action === 'edit' && !empty($snippet_id)) {
    foreach ($snippets as $id => $snippet) {
        if ($id === $snippet_id) {
            $snippet_data = $snippet;
            $snippet_data['id'] = $id;
            break;
        }
    }
} elseif ($action === 'add') {
    $snippet_data = [
        'id' => '',
        'title' => '',
        'description' => '',
        'code' => '',
        'type' => 'js',
        'location' => 'header',
        'priority' => 10,
        'active' => false,
        'created' => current_time('mysql'),
    ];
}

// Enqueue snippet data for JavaScript
if ($snippet_data) {
    wp_localize_script('switchboard-csm-admin', 'switchboard_csm_snippet_data', $snippet_data);
}
?>

<div class="wrap sb-module-wrap">
    <!-- Header -->
    <div class="sb-module-header">
        <div class="sb-module-header-left">
            <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
            </svg>
            <div>
                <h1 class="sb-module-title">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Creating Code Snippet', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Editing Code Snippet', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Code Snippets Manager', 'wpswitchboard'); ?>
                    <?php endif; ?>
                    <span class="switchboard-badge">SWITCHBOARD PRO</span>
                </h1>
                <p class="sb-module-subtitle">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Add custom JavaScript, CSS, or HTML code to your site', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Edit your code snippet settings and code', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Add and manage custom code snippets without editing theme files', 'wpswitchboard'); ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="sb-module-header-right">
            <a href="https://docs.wpswitchboard.com/modules/utilities/code-snippets-manager" target="_blank" class="sb-module-help-link">
                <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                Help
            </a>
            <?php if ($action === 'add' || $action === 'edit'): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-code-snippets-manager')); ?>" class="sb-module-button sb-module-button-secondary">
                    <?php esc_html_e('Go Back', 'wpswitchboard'); ?>
                </a>
            <?php else: ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-code-snippets-manager&action=add')); ?>" class="sb-module-button sb-module-button-primary">
                    <?php esc_html_e('Add New Snippet', 'wpswitchboard'); ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Main Content -->
    <div class="sb-module-container">
        <?php if ($action === ''): ?>
            <!-- Default Dashboard View -->
            <?php if (!empty($snippets)): ?>
                <!-- Stats Cards -->
                <div class="sb-module-stats">
                    <div class="sb-module-stat-card">
                        <div class="sb-module-stat-label"><?php esc_html_e('Total Snippets', 'wpswitchboard'); ?></div>
                        <div class="sb-module-stat-content">
                            <div class="sb-module-stat-value"><?php echo count($snippets); ?></div>
                        </div>
                    </div>

                    <div class="sb-module-stat-card">
                        <div class="sb-module-stat-label"><?php esc_html_e('Active Snippets', 'wpswitchboard'); ?></div>
                        <div class="sb-module-stat-content">
                            <div class="sb-module-stat-value">
                                <?php
                                $active_count = 0;
                                foreach ($snippets as $snippet) {
                                    if (!empty($snippet['active'])) {
                                        $active_count++;
                                    }
                                }
                                echo $active_count;
                                ?>
                            </div>
                        </div>
                    </div>

                    <div class="sb-module-stat-card">
                        <div class="sb-module-stat-label"><?php esc_html_e('Inactive Snippets', 'wpswitchboard'); ?></div>
                        <div class="sb-module-stat-content">
                            <div class="sb-module-stat-value"><?php echo count($snippets) - $active_count; ?></div>
                        </div>
                    </div>

                    <div class="sb-module-stat-card">
                        <div class="sb-module-stat-label"><?php esc_html_e('Code Types', 'wpswitchboard'); ?></div>
                        <div class="sb-module-stat-content">
                            <div class="sb-module-stat-value">
                                <?php
                                $types = array_unique(array_column($snippets, 'type'));
                                echo count($types);
                                ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- List View with Sidebar -->
                <div class="csm-dashboard-layout">
                    <!-- Main List Column -->
                    <div class="csm-list-column">
                        <!-- Search Bar -->
                        <div class="switchboard-search-wrapper">
                            <span class="dashicons dashicons-search search-icon"></span>
                            <input type="text" id="csm-search" class="switchboard-search" placeholder="<?php esc_attr_e('Search snippets...', 'wpswitchboard'); ?>">
                        </div>

                        <!-- Snippets List -->
                        <div class="csm-snippets-list">
                            <?php foreach ($snippets as $id => $snippet): ?>
                                <div class="csm-snippet-row"
                                     data-type="<?php echo esc_attr(isset($snippet['type']) ? $snippet['type'] : ''); ?>"
                                     data-location="<?php echo esc_attr(isset($snippet['location']) ? $snippet['location'] : ''); ?>"
                                     data-status="<?php echo !empty($snippet['active']) ? 'active' : 'inactive'; ?>">
                                    <div class="csm-snippet-row-main">
                                        <div class="csm-snippet-row-header">
                                            <div class="csm-snippet-row-title-wrapper">
                                                <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-code-snippets-manager&action=edit&snippet_id=' . urlencode($id))); ?>" class="csm-snippet-row-title">
                                                    <?php echo esc_html(isset($snippet['title']) ? $snippet['title'] : __('Untitled Snippet', 'wpswitchboard')); ?>
                                                </a>
                                                <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-code-snippets-manager&action=edit&snippet_id=' . urlencode($id))); ?>" class="csm-snippet-row-edit">
                                                    <span class="dashicons dashicons-edit"></span>
                                                </a>
                                            </div>
                                            <div class="csm-snippet-row-meta">
                                                <span class="csm-snippet-row-priority">
                                                    <span class="dashicons dashicons-sort"></span>
                                                    <?php echo sprintf(esc_html__('Priority: %d', 'wpswitchboard'), isset($snippet['priority']) ? $snippet['priority'] : 10); ?>
                                                </span>
                                                <?php if (!empty($snippet['created'])): ?>
                                                    <span class="csm-snippet-row-date">
                                                        <?php echo sprintf(esc_html__('Created %s', 'wpswitchboard'), human_time_diff(strtotime($snippet['created']), current_time('timestamp')) . ' ago'); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php if (!empty($snippet['description'])): ?>
                                            <p class="csm-snippet-row-desc"><?php echo esc_html(wp_trim_words($snippet['description'], 20)); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="csm-snippet-row-right">
                                        <div class="csm-snippet-row-badges">
                                            <span class="csm-badge csm-badge-<?php echo esc_attr(isset($snippet['type']) ? $snippet['type'] : 'js'); ?>">
                                                <?php echo esc_html(strtoupper(isset($snippet['type']) ? $snippet['type'] : 'js')); ?>
                                            </span>
                                            <span class="csm-badge csm-badge-location">
                                                <?php
                                                $location_labels = [
                                                    'header' => 'Header',
                                                    'footer' => 'Footer',
                                                ];
                                                $snippet_location = isset($snippet['location']) ? $snippet['location'] : 'header';
                                                echo esc_html($location_labels[$snippet_location] ?? ucfirst($snippet_location));
                                                ?>
                                            </span>
                                        </div>
                                        <label class="sb-module-toggle csm-snippet-toggle" data-snippet-id="<?php echo esc_attr($id); ?>" onclick="event.stopPropagation();">
                                            <input type="checkbox" class="csm-toggle-input" <?php checked(!empty($snippet['active'])); ?>>
                                            <span class="sb-module-toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- No Results Message -->
                        <div class="csm-no-results" style="display: none;">
                            <p><?php esc_html_e('No snippets found matching your filters.', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <!-- Filters Sidebar -->
                    <div class="csm-filters-column">
                        <!-- Status Filter -->
                        <div class="csm-filter-card">
                            <h3 class="csm-filter-card-title"><?php esc_html_e('Status', 'wpswitchboard'); ?></h3>
                            <div class="csm-filter-options">
                                <label class="csm-filter-option active" data-filter="status" data-value="all">
                                    <input type="radio" name="filter_status" value="all" checked>
                                    <span><?php esc_html_e('All Snippets', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="status" data-value="active">
                                    <input type="radio" name="filter_status" value="active">
                                    <span><?php esc_html_e('Active Only', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="status" data-value="inactive">
                                    <input type="radio" name="filter_status" value="inactive">
                                    <span><?php esc_html_e('Inactive Only', 'wpswitchboard'); ?></span>
                                </label>
                            </div>
                        </div>

                        <!-- Code Type Filter -->
                        <div class="csm-filter-card">
                            <h3 class="csm-filter-card-title"><?php esc_html_e('Code Type', 'wpswitchboard'); ?></h3>
                            <div class="csm-filter-options">
                                <label class="csm-filter-option active" data-filter="type" data-value="all">
                                    <input type="radio" name="filter_type" value="all" checked>
                                    <span><?php esc_html_e('All Types', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="type" data-value="js">
                                    <input type="radio" name="filter_type" value="js">
                                    <span><?php esc_html_e('JavaScript', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="type" data-value="css">
                                    <input type="radio" name="filter_type" value="css">
                                    <span><?php esc_html_e('CSS', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="type" data-value="html">
                                    <input type="radio" name="filter_type" value="html">
                                    <span><?php esc_html_e('HTML', 'wpswitchboard'); ?></span>
                                </label>
                            </div>
                        </div>

                        <!-- Location Filter -->
                        <div class="csm-filter-card">
                            <h3 class="csm-filter-card-title"><?php esc_html_e('Location', 'wpswitchboard'); ?></h3>
                            <div class="csm-filter-options">
                                <label class="csm-filter-option active" data-filter="location" data-value="all">
                                    <input type="radio" name="filter_location" value="all" checked>
                                    <span><?php esc_html_e('All Locations', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="location" data-value="header">
                                    <input type="radio" name="filter_location" value="header">
                                    <span><?php esc_html_e('Header', 'wpswitchboard'); ?></span>
                                </label>
                                <label class="csm-filter-option" data-filter="location" data-value="footer">
                                    <input type="radio" name="filter_location" value="footer">
                                    <span><?php esc_html_e('Footer', 'wpswitchboard'); ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <!-- Empty State -->
                <div class="csm-empty-state">
                    <div class="csm-empty-state-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
                        </svg>
                    </div>
                    <h3 class="csm-empty-state-title"><?php esc_html_e('No code snippets yet', 'wpswitchboard'); ?></h3>
                    <p class="csm-empty-state-desc"><?php esc_html_e('Here are some ideas to get you started', 'wpswitchboard'); ?></p>

                    <!-- Use Cases Grid -->
                    <div class="csm-use-cases-grid">
                        <div class="csm-use-case-card">
                            <h4 class="csm-use-case-title">Analytics & Tracking</h4>
                            <p class="csm-use-case-desc">Insert Google Analytics, Facebook Pixel, or custom tracking scripts in header or footer without touching theme files.</p>
                        </div>
                        <div class="csm-use-case-card">
                            <h4 class="csm-use-case-title">Custom Styles</h4>
                            <p class="csm-use-case-desc">Add CSS tweaks and overrides to customize your site's appearance without creating a child theme or plugin.</p>
                        </div>
                        <div class="csm-use-case-card">
                            <h4 class="csm-use-case-title">Embed Widgets</h4>
                            <p class="csm-use-case-desc">Add chat widgets, social feeds, or other HTML embeds to your site's header or footer easily.</p>
                        </div>
                    </div>

                    <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-code-snippets-manager&action=add')); ?>" class="csm-empty-state-btn">
                        <span class="dashicons dashicons-plus-alt"></span>
                        <?php esc_html_e('Create Code Snippet', 'wpswitchboard'); ?>
                    </a>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <!-- Add/Edit View -->
            <?php include dirname(__FILE__) . '/edit.php'; ?>
        <?php endif; ?>
    </div>
</div>
