<?php
/**
 * Admin Components Management
 * Lists available components and allows creating/editing them
 */
require_once __DIR__ . "/../../src/Core/Auth.php";
require_once __DIR__ . "/../../src/Core/Model.php";
require_once __DIR__ . "/../../src/Core/MultiTenancy.php";
require_once __DIR__ . "/../../src/Core/Component.php";

// Auth check
if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

// Database connection
$tenantId = \Core\MultiTenancy::getTenantId();
define('DB_PATH', \Core\MultiTenancy::getDatabasePath($tenantId));
try {
    $pdo = new PDO('sqlite:' . DB_PATH);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    \Core\Model::setPdo($pdo);
} catch (Exception $e) {
    die('DB Error: ' . $e->getMessage());
}

// Get all file-based components
$componentDir = __DIR__ . '/../../themes/default/components/';
$components = [];

if (is_dir($componentDir)) {
    $files = glob($componentDir . '*.php');
    foreach ($files as $file) {
        $name = basename($file, '.php');
        $content = file_get_contents($file);

        // Try to extract component info from comments or content
        $components[] = [
            'name' => $name,
            'display_name' => ucwords(str_replace('_', ' ', $name)),
            'file' => $file,
            'category' => detectCategory($name),
            'is_system' => true,
            'description' => getComponentDescription($name)
        ];
    }
}

function detectCategory($name)
{
    $categories = [
        'hero' => 'Hero',
        'features' => 'Content',
        'team' => 'Team',
        'contact' => 'Forms',
        'showcase' => 'Content',
        'gallery' => 'Media',
        'pricing' => 'Commerce',
        'testimonial' => 'Social',
        'cta' => 'Hero',
        'faq' => 'Content'
    ];

    foreach ($categories as $key => $cat) {
        if (stripos($name, $key) !== false) {
            return $cat;
        }
    }
    return 'Other';
}

function getComponentDescription($name)
{
    $descriptions = [
        'hero' => 'Full-width hero section with title, subtitle, and call-to-action button.',
        'features' => 'Grid of feature cards with icons, titles, and descriptions.',
        'team' => 'Team member cards with photos, names, and roles.',
        'contact_form' => 'Professional contact form with multiple fields and styling.',
        'showcase' => 'Showcase section for highlighting products or services.'
    ];
    return $descriptions[$name] ?? 'Custom component';
}

function getCategoryIcon($category)
{
    $icons = [
        'Hero' => 'fas fa-star',
        'Content' => 'fas fa-align-left',
        'Team' => 'fas fa-users',
        'Forms' => 'fas fa-envelope',
        'Media' => 'fas fa-images',
        'Commerce' => 'fas fa-shopping-cart',
        'Social' => 'fas fa-comments',
        'Other' => 'fas fa-puzzle-piece'
    ];
    return $icons[$category] ?? 'fas fa-cube';
}

// Page settings
$pageTitle = 'Components';
$currentPage = 'components';
$headerActions = '<a href="/admin/component-editor.php" class="button is-primary">
    <span class="icon"><i class="fas fa-plus"></i></span>
    <span>New Component</span>
</a>';

// Start content buffer
ob_start();
?>

<!-- Component Stats -->
<div class="columns mb-5">
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-primary">
                <i class="fas fa-puzzle-piece"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value"><?= count($components) ?></div>
                <div class="stat-label">Total Components</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value"><?= count($components) ?></div>
                <div class="stat-label">System Components</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-info">
                <i class="fas fa-user"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value">0</div>
                <div class="stat-label">Custom Components</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-warning">
                <i class="fas fa-folder"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value"><?= count(array_unique(array_column($components, 'category'))) ?></div>
                <div class="stat-label">Categories</div>
            </div>
        </div>
    </div>
</div>

<!-- Info Box -->
<div class="notification is-info is-light mb-5">
    <div class="columns is-vcentered">
        <div class="column">
            <p>
                <strong><i class="fas fa-info-circle"></i> How to use components:</strong><br>
                Insert components into pages using shortcode syntax: <code>[component:name attribute="value"]</code>
            </p>
        </div>
        <div class="column is-narrow">
            <a href="/admin/prompt-generator.php" class="button is-info is-light">
                <span class="icon"><i class="fas fa-robot"></i></span>
                <span>AI Prompt Generator</span>
            </a>
        </div>
    </div>
</div>

<!-- Components Grid -->
<div class="admin-card">
    <h2 class="card-header-title">
        <span class="icon mr-2"><i class="fas fa-puzzle-piece"></i></span>
        Available Components
    </h2>

    <div class="columns is-multiline">
        <?php foreach ($components as $comp): ?>
            <div class="column is-4">
                <div class="box component-card">
                    <div class="level mb-3">
                        <div class="level-left">
                            <span class="icon is-large has-text-primary">
                                <i class="<?= getCategoryIcon($comp['category']) ?> fa-2x"></i>
                            </span>
                        </div>
                        <div class="level-right">
                            <span class="tag is-light"><?= $comp['category'] ?></span>
                            <?php if ($comp['is_system']): ?>
                                <span class="tag is-info is-light ml-1">System</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <h3 class="title is-5 mb-2"><?= htmlspecialchars($comp['display_name']) ?></h3>
                    <p class="has-text-grey mb-4"><?= htmlspecialchars($comp['description']) ?></p>

                    <div class="field has-addons">
                        <div class="control is-expanded">
                            <input class="input is-small" type="text" value="[component:<?= $comp['name'] ?>]" readonly>
                        </div>
                        <div class="control">
                            <button class="button is-small is-info copy-btn" data-copy="[component:<?= $comp['name'] ?>]"
                                title="Copy shortcode">
                                <span class="icon"><i class="fas fa-copy"></i></span>
                            </button>
                        </div>
                    </div>

                    <hr class="my-3">

                    <div class="buttons are-small">
                        <a href="/admin/component-editor.php?name=<?= $comp['name'] ?>" class="button is-primary is-light">
                            <span class="icon"><i class="fas fa-edit"></i></span>
                            <span>Edit</span>
                        </a>
                        <a href="/admin/component-preview.php?name=<?= $comp['name'] ?>" class="button is-info is-light">
                            <span class="icon"><i class="fas fa-eye"></i></span>
                            <span>Preview</span>
                        </a>
                        <button class="button is-light" onclick="showDocs('<?= $comp['name'] ?>')">
                            <span class="icon"><i class="fas fa-book"></i></span>
                            <span>Docs</span>
                        </button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Component Documentation Modal -->
<div class="modal" id="docsModal">
    <div class="modal-background"></div>
    <div class="modal-card" style="max-width: 700px;">
        <header class="modal-card-head">
            <p class="modal-card-title" id="docsTitle">Component Documentation</p>
            <button class="delete" aria-label="close" onclick="closeModal()"></button>
        </header>
        <section class="modal-card-body" id="docsContent">
            <!-- Content loaded dynamically -->
        </section>
        <footer class="modal-card-foot">
            <button class="button" onclick="closeModal()">Close</button>
        </footer>
    </div>
</div>

<style>
    .component-card {
        transition: all 0.2s;
        height: 100%;
    }

    .component-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
</style>

<script>
    // Copy shortcode
    document.querySelectorAll('.copy-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const text = this.dataset.copy;
            navigator.clipboard.writeText(text).then(() => {
                const icon = this.querySelector('i');
                icon.classList.remove('fa-copy');
                icon.classList.add('fa-check');
                setTimeout(() => {
                    icon.classList.remove('fa-check');
                    icon.classList.add('fa-copy');
                }, 1500);
            });
        });
    });

    // Component documentation
    const componentDocs = {
        hero: {
            title: 'Hero Component',
            params: [
                { name: 'title', type: 'text', required: true, desc: 'Main heading text' },
                { name: 'subtitle', type: 'text', required: false, desc: 'Subtitle text below heading' },
                { name: 'cta_text', type: 'text', required: false, desc: 'Button text' },
                { name: 'cta_link', type: 'url', required: false, desc: 'Button link URL' }
            ],
            example: '[component:hero title="Welcome" subtitle="Your tagline here" cta_text="Learn More" cta_link="/about"]'
        },
        features: {
            title: 'Features Component',
            params: [
                { name: 'title', type: 'text', required: false, desc: 'Section title' },
                { name: 'description', type: 'text', required: false, desc: 'Section description' },
                { name: 'items', type: 'json', required: true, desc: 'Array of feature items' }
            ],
            example: '[component:features title="Our Services" items=\'[{"title":"Service 1","description":"Description"}]\']'
        },
        team: {
            title: 'Team Component',
            params: [
                { name: 'title', type: 'text', required: true, desc: 'Section title' },
                { name: 'description', type: 'text', required: false, desc: 'Section description' },
                { name: 'member1_name', type: 'text', required: true, desc: 'First member name' },
                { name: 'member1_role', type: 'text', required: false, desc: 'First member role' },
                { name: 'member1_image', type: 'url', required: false, desc: 'First member photo URL' }
            ],
            example: '[component:team title="Our Team" member1_name="John Doe" member1_role="CEO"]'
        },
        contact_form: {
            title: 'Contact Form Component',
            params: [
                { name: 'title', type: 'text', required: true, desc: 'Form heading' },
                { name: 'subtitle', type: 'text', required: false, desc: 'Form description' },
                { name: 'email_to', type: 'email', required: true, desc: 'Email address for submissions' }
            ],
            example: '[component:contact_form title="Get in Touch" email_to="info@example.com"]'
        },
        showcase: {
            title: 'Showcase Component',
            params: [
                { name: 'title', type: 'text', required: false, desc: 'Section title' }
            ],
            example: '[component:showcase title="Our Work"]'
        }
    };

    function showDocs(name) {
        const docs = componentDocs[name];
        if (!docs) {
            alert('Documentation not available for this component.');
            return;
        }

        let html = '<div class="content">';
        html += '<h4>Parameters</h4>';
        html += '<table class="table is-fullwidth is-striped">';
        html += '<thead><tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr></thead>';
        html += '<tbody>';
        docs.params.forEach(p => {
            html += '<tr>';
            html += '<td><code>' + p.name + '</code></td>';
            html += '<td>' + p.type + '</td>';
            html += '<td>' + (p.required ? '<span class="tag is-danger is-light">Yes</span>' : '<span class="tag is-light">No</span>') + '</td>';
            html += '<td>' + p.desc + '</td>';
            html += '</tr>';
        });
        html += '</tbody></table>';
        html += '<h4>Example Usage</h4>';
        html += '<pre style="background:#f5f5f5;padding:1rem;border-radius:4px;overflow-x:auto;"><code>' + docs.example + '</code></pre>';
        html += '</div>';

        document.getElementById('docsTitle').textContent = docs.title;
        document.getElementById('docsContent').innerHTML = html;
        document.getElementById('docsModal').classList.add('is-active');
    }

    function closeModal() {
        document.getElementById('docsModal').classList.remove('is-active');
    }
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layouts/admin_layout.php';
