<?php
/**
 * Component Configurator
 * Visual form for configuring components
 */
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/Models/ComponentSchema.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);
    \Models\ComponentSchema::setPdo($pdo);

    // Create table if not exists
    \Models\ComponentSchema::createTable();
} catch (PDOException $e) {
    die('Database error: ' . $e->getMessage());
}

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $action = $_POST['action'] ?? '';

    if ($action === 'get_schema') {
        $componentName = $_POST['component_name'] ?? '';
        $schema = \Models\ComponentSchema::get($componentName);
        echo json_encode(['success' => true, 'schema' => $schema]);
        exit;
    }

    if ($action === 'seed_schemas') {
        \Models\ComponentSchema::seedDefaultSchemas();
        echo json_encode(['success' => true, 'message' => 'Schemas seeded']);
        exit;
    }

    if ($action === 'generate_shortcode') {
        $componentName = $_POST['component_name'] ?? '';
        $formData = $_POST['form_data'] ?? [];

        // Build shortcode
        $attrs = [];
        foreach ($formData as $key => $value) {
            if (!empty($value) && $value !== '') {
                // Handle arrays (repeaters)
                if (is_array($value)) {
                    $value = json_encode($value);
                }
                // Escape quotes
                $value = str_replace('"', '&quot;', $value);
                $attrs[] = $key . '="' . $value . '"';
            }
        }

        $shortcode = '[component:' . $componentName;
        if (!empty($attrs)) {
            $shortcode .= ' ' . implode(' ', $attrs);
        }
        $shortcode .= ']';

        echo json_encode(['success' => true, 'shortcode' => $shortcode]);
        exit;
    }

    echo json_encode(['success' => false, 'error' => 'Unknown action']);
    exit;
}

// Seed schemas if table is empty
$schemas = \Models\ComponentSchema::all();
if (empty($schemas)) {
    \Models\ComponentSchema::seedDefaultSchemas();
    $schemas = \Models\ComponentSchema::all();
}

// Group by category
$categories = [];
foreach ($schemas as $schema) {
    $cat = $schema['category'] ?? 'general';
    if (!isset($categories[$cat])) {
        $categories[$cat] = [];
    }
    $categories[$cat][] = $schema;
}

$pageTitle = 'Component Configurator';
$currentPage = 'component-config';

ob_start();
?>

<div class="columns">
    <!-- Component Picker -->
    <div class="column is-4">
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-puzzle-piece"></i></span>
                Select Component
            </h2>

            <div class="field">
                <div class="control has-icons-left">
                    <input type="text" class="input" id="componentSearch" placeholder="Search components...">
                    <span class="icon is-left"><i class="fas fa-search"></i></span>
                </div>
            </div>

            <div id="componentList" style="max-height: 600px; overflow-y: auto;">
                <?php foreach ($categories as $catName => $catComponents): ?>
                    <div class="component-category mb-4">
                        <p class="has-text-weight-bold has-text-grey-dark mb-2">
                            <?= ucfirst(str_replace('-', ' ', htmlspecialchars($catName))) ?>
                        </p>
                        <?php foreach ($catComponents as $comp):
                            $schemaData = is_string($comp['schema']) ? json_decode($comp['schema'], true) : $comp['schema'];
                            ?>
                            <a class="box component-item mb-2 p-3"
                                data-component="<?= htmlspecialchars($comp['component_name']) ?>"
                                data-schema='<?= htmlspecialchars(json_encode($schemaData)) ?>'>
                                <div class="is-flex is-align-items-center">
                                    <span class="icon has-text-primary mr-3">
                                        <i class="<?= htmlspecialchars($comp['icon'] ?? 'fas fa-puzzle-piece') ?>"></i>
                                    </span>
                                    <div>
                                        <p class="has-text-weight-semibold"><?= htmlspecialchars($comp['display_name']) ?></p>
                                        <p class="is-size-7 has-text-grey"><?= htmlspecialchars($comp['description'] ?? '') ?>
                                        </p>
                                    </div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Configuration Form -->
    <div class="column is-8">
        <div class="admin-card" id="configPanel" style="display: none;">
            <div class="level">
                <div class="level-left">
                    <h2 class="card-header-title" id="configTitle" style="border: none; padding: 0;">
                        <span class="icon mr-2"><i class="fas fa-cog"></i></span>
                        Configure Component
                    </h2>
                </div>
                <div class="level-right">
                    <button type="button" class="button is-small is-light" onclick="resetForm()">
                        <span class="icon"><i class="fas fa-undo"></i></span>
                    </button>
                </div>
            </div>

            <form id="configForm">
                <input type="hidden" id="componentName" name="component_name">
                <div id="formFields">
                    <!-- Dynamic fields will be rendered here -->
                </div>

                <hr>

                <div class="buttons">
                    <button type="submit" class="button is-primary">
                        <span class="icon"><i class="fas fa-code"></i></span>
                        <span>Generate Shortcode</span>
                    </button>
                    <button type="button" class="button is-info is-light" id="previewBtn">
                        <span class="icon"><i class="fas fa-eye"></i></span>
                        <span>Preview</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- No component selected -->
        <div class="admin-card has-text-centered" id="noComponentPanel">
            <div class="py-6">
                <span class="icon is-large has-text-grey-light">
                    <i class="fas fa-hand-pointer fa-3x"></i>
                </span>
                <p class="has-text-grey mt-4">Select a component from the left panel to configure it.</p>
            </div>
        </div>

        <!-- Generated Shortcode -->
        <div class="admin-card mt-4" id="shortcodePanel" style="display: none;">
            <h3 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-code"></i></span>
                Generated Shortcode
            </h3>
            <div class="field">
                <div class="control">
                    <textarea class="textarea is-family-monospace" id="generatedShortcode" rows="3" readonly></textarea>
                </div>
            </div>
            <div class="buttons">
                <button type="button" class="button is-success" onclick="copyShortcode()">
                    <span class="icon"><i class="fas fa-copy"></i></span>
                    <span>Copy</span>
                </button>
                <button type="button" class="button is-info" onclick="insertToEditor()">
                    <span class="icon"><i class="fas fa-plus"></i></span>
                    <span>Insert to Page</span>
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    .component-item {
        cursor: pointer;
        transition: all 0.2s;
        border: 2px solid transparent;
    }

    .component-item:hover {
        border-color: #3273dc;
        background: #f5f5f5;
    }

    .component-item.is-selected {
        border-color: #3273dc;
        background: #ebf5ff;
    }

    .repeater-item {
        background: #f9f9f9;
        border-radius: 4px;
        padding: 1rem;
        margin-bottom: 0.5rem;
        position: relative;
    }

    .repeater-remove {
        position: absolute;
        top: 0.5rem;
        right: 0.5rem;
    }
</style>

<script>
    let currentComponent = null;
    let currentSchema = null;

    // Component selection
    document.querySelectorAll('.component-item').forEach(item => {
        item.addEventListener('click', function () {
            // Update selection UI
            document.querySelectorAll('.component-item').forEach(i => i.classList.remove('is-selected'));
            this.classList.add('is-selected');

            // Load component schema
            currentComponent = this.dataset.component;
            currentSchema = JSON.parse(this.dataset.schema);

            // Show config panel
            document.getElementById('noComponentPanel').style.display = 'none';
            document.getElementById('configPanel').style.display = 'block';
            document.getElementById('shortcodePanel').style.display = 'none';

            // Update title
            document.getElementById('configTitle').innerHTML =
                '<span class="icon mr-2"><i class="fas fa-cog"></i></span>' +
                this.querySelector('.has-text-weight-semibold').textContent;

            document.getElementById('componentName').value = currentComponent;

            // Render form
            renderForm(currentSchema);
        });
    });

    // Search filter
    document.getElementById('componentSearch').addEventListener('input', function () {
        const query = this.value.toLowerCase();
        document.querySelectorAll('.component-item').forEach(item => {
            const text = item.textContent.toLowerCase();
            item.style.display = text.includes(query) ? 'block' : 'none';
        });
    });

    // Render form based on schema
    function renderForm(schema) {
        const container = document.getElementById('formFields');
        container.innerHTML = '';

        if (!schema || !schema.fields) return;

        schema.fields.forEach(field => {
            container.appendChild(createField(field));
        });
    }

    // Create form field
    function createField(field, prefix = '') {
        const fieldName = prefix ? `${prefix}[${field.name}]` : field.name;
        const fieldId = fieldName.replace(/[\[\]]/g, '_');

        const div = document.createElement('div');
        div.className = 'field mb-4';

        // Label
        const label = document.createElement('label');
        label.className = 'label';
        label.textContent = field.label || field.name;
        if (field.required) {
            label.innerHTML += ' <span class="has-text-danger">*</span>';
        }
        div.appendChild(label);

        const control = document.createElement('div');
        control.className = 'control';

        switch (field.type) {
            case 'text':
            case 'url':
            case 'email':
            case 'number':
                const input = document.createElement('input');
                input.type = field.type === 'url' ? 'url' : (field.type === 'email' ? 'email' : (field.type === 'number' ? 'number' : 'text'));
                input.className = 'input';
                input.name = fieldName;
                input.id = fieldId;
                input.placeholder = field.placeholder || '';
                if (field.required) input.required = true;
                control.appendChild(input);
                break;

            case 'textarea':
            case 'richtext':
                const textarea = document.createElement('textarea');
                textarea.className = 'textarea';
                textarea.name = fieldName;
                textarea.id = fieldId;
                textarea.rows = field.rows || 4;
                textarea.placeholder = field.placeholder || '';
                control.appendChild(textarea);
                break;

            case 'select':
                const selectDiv = document.createElement('div');
                selectDiv.className = 'select is-fullwidth';
                const select = document.createElement('select');
                select.name = fieldName;
                select.id = fieldId;

                // Empty option
                const emptyOpt = document.createElement('option');
                emptyOpt.value = '';
                emptyOpt.textContent = '-- Select --';
                select.appendChild(emptyOpt);

                (field.options || []).forEach(opt => {
                    const option = document.createElement('option');
                    if (typeof opt === 'object') {
                        option.value = opt.value;
                        option.textContent = opt.label;
                    } else {
                        option.value = opt;
                        option.textContent = opt;
                    }
                    select.appendChild(option);
                });
                selectDiv.appendChild(select);
                control.appendChild(selectDiv);
                break;

            case 'checkbox':
                const checkLabel = document.createElement('label');
                checkLabel.className = 'checkbox';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.name = fieldName;
                checkbox.id = fieldId;
                checkbox.value = '1';
                checkLabel.appendChild(checkbox);
                checkLabel.appendChild(document.createTextNode(' ' + (field.label || field.name)));
                control.appendChild(checkLabel);
                // Remove duplicate label
                div.removeChild(label);
                break;

            case 'color':
                const colorInput = document.createElement('input');
                colorInput.type = 'color';
                colorInput.className = 'input';
                colorInput.name = fieldName;
                colorInput.id = fieldId;
                colorInput.style.height = '40px';
                control.appendChild(colorInput);
                break;

            case 'media':
                const mediaDiv = document.createElement('div');
                mediaDiv.className = 'is-flex is-align-items-center';
                const mediaInput = document.createElement('input');
                mediaInput.type = 'text';
                mediaInput.className = 'input mr-2';
                mediaInput.name = fieldName;
                mediaInput.id = fieldId;
                mediaInput.placeholder = 'Image URL or select from media library';
                const mediaBtn = document.createElement('button');
                mediaBtn.type = 'button';
                mediaBtn.className = 'button is-info is-light';
                mediaBtn.innerHTML = '<span class="icon"><i class="fas fa-image"></i></span>';
                mediaBtn.onclick = () => openMediaPicker(fieldId);
                mediaDiv.appendChild(mediaInput);
                mediaDiv.appendChild(mediaBtn);
                control.appendChild(mediaDiv);
                break;

            case 'icon':
                const iconDiv = document.createElement('div');
                iconDiv.className = 'is-flex is-align-items-center';
                const iconInput = document.createElement('input');
                iconInput.type = 'text';
                iconInput.className = 'input mr-2';
                iconInput.name = fieldName;
                iconInput.id = fieldId;
                iconInput.placeholder = 'fas fa-star';
                const iconPreview = document.createElement('span');
                iconPreview.className = 'icon is-large';
                iconPreview.id = fieldId + '_preview';
                iconPreview.innerHTML = '<i class="fas fa-star"></i>';
                iconInput.addEventListener('input', function () {
                    iconPreview.innerHTML = '<i class="' + this.value + '"></i>';
                });
                iconDiv.appendChild(iconInput);
                iconDiv.appendChild(iconPreview);
                control.appendChild(iconDiv);
                break;

            case 'repeater':
                const repeaterDiv = document.createElement('div');
                repeaterDiv.className = 'repeater-container';
                repeaterDiv.dataset.field = field.name;
                repeaterDiv.dataset.fields = JSON.stringify(field.fields);

                const repeaterItems = document.createElement('div');
                repeaterItems.className = 'repeater-items';
                repeaterItems.id = fieldId + '_items';
                repeaterDiv.appendChild(repeaterItems);

                const addBtn = document.createElement('button');
                addBtn.type = 'button';
                addBtn.className = 'button is-small is-info is-light mt-2';
                addBtn.innerHTML = '<span class="icon"><i class="fas fa-plus"></i></span><span>Add Item</span>';
                addBtn.onclick = () => addRepeaterItem(fieldName, field.fields, repeaterItems);
                repeaterDiv.appendChild(addBtn);

                control.appendChild(repeaterDiv);
                break;
        }

        div.appendChild(control);

        // Help text
        if (field.help) {
            const help = document.createElement('p');
            help.className = 'help';
            help.textContent = field.help;
            div.appendChild(help);
        }

        return div;
    }

    // Add repeater item
    let repeaterIndex = {};
    function addRepeaterItem(parentName, fields, container) {
        if (!repeaterIndex[parentName]) repeaterIndex[parentName] = 0;
        const index = repeaterIndex[parentName]++;

        const item = document.createElement('div');
        item.className = 'repeater-item';

        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'delete repeater-remove';
        removeBtn.onclick = () => item.remove();
        item.appendChild(removeBtn);

        fields.forEach(field => {
            const fieldEl = createField(field, `${parentName}[${index}]`);
            item.appendChild(fieldEl);
        });

        container.appendChild(item);
    }

    // Form submission
    document.getElementById('configForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('action', 'generate_shortcode');

        // Convert to form_data object
        const data = {};
        for (let [key, value] of formData.entries()) {
            if (key === 'action' || key === 'component_name') continue;

            // Handle nested keys like items[0][title]
            const keys = key.match(/[^\[\]]+/g);
            if (keys.length === 1) {
                data[key] = value;
            } else {
                let current = data;
                for (let i = 0; i < keys.length - 1; i++) {
                    if (!current[keys[i]]) {
                        current[keys[i]] = isNaN(keys[i + 1]) ? {} : [];
                    }
                    current = current[keys[i]];
                }
                current[keys[keys.length - 1]] = value;
            }
        }

        // Build shortcode manually
        let shortcode = '[component:' + currentComponent;
        Object.entries(data).forEach(([key, value]) => {
            if (value && value !== '' && value !== null) {
                if (typeof value === 'object') {
                    // Array/object - JSON encode
                    shortcode += ' ' + key + '="' + JSON.stringify(value).replace(/"/g, '&quot;') + '"';
                } else {
                    shortcode += ' ' + key + '="' + value.replace(/"/g, '&quot;') + '"';
                }
            }
        });
        shortcode += ']';

        document.getElementById('generatedShortcode').value = shortcode;
        document.getElementById('shortcodePanel').style.display = 'block';
    });

    // Copy shortcode
    function copyShortcode() {
        const textarea = document.getElementById('generatedShortcode');
        textarea.select();
        document.execCommand('copy');

        // Show feedback
        const btn = event.target.closest('button');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="icon"><i class="fas fa-check"></i></span><span>Copied!</span>';
        btn.classList.add('is-success');
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    }

    // Insert to editor (for modal usage)
    function insertToEditor() {
        const shortcode = document.getElementById('generatedShortcode').value;
        if (window.opener && window.opener.insertShortcode) {
            window.opener.insertShortcode(shortcode);
            window.close();
        } else {
            alert('Copy the shortcode and paste it into your page content.');
        }
    }

    // Reset form
    function resetForm() {
        document.getElementById('configForm').reset();
        document.getElementById('shortcodePanel').style.display = 'none';
    }

    // Media picker placeholder
    function openMediaPicker(targetId) {
        const url = prompt('Enter image URL:', 'https://');
        if (url) {
            document.getElementById(targetId).value = url;
        }
    }

    // Preview button
    document.getElementById('previewBtn').addEventListener('click', function () {
        // Trigger form submit first to generate shortcode
        document.getElementById('configForm').dispatchEvent(new Event('submit'));

        // Open preview in playground
        setTimeout(() => {
            const shortcode = document.getElementById('generatedShortcode').value;
            window.open('/admin/playground.php?code=' + encodeURIComponent(shortcode), '_blank');
        }, 100);
    });
</script>

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