<?php
/**
 * Component Editor
 * View and edit component templates
 */
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/Cache.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);
    \Core\Model::setPdo($pdo);
} catch (Exception $e) {
    die('DB Error: ' . $e->getMessage());
}

$componentName = $_GET['name'] ?? null;
$componentDir = __DIR__ . '/../../themes/default/components/';
$successMessage = null;
$errorMessage = null;

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $name = $_POST['component_name'];
    $content = $_POST['component_content'];
    $filePath = $componentDir . $name . '.php';

    // Backup existing file
    if (file_exists($filePath)) {
        $backupDir = $componentDir . 'backups/';
        if (!is_dir($backupDir))
            mkdir($backupDir, 0777, true);
        copy($filePath, $backupDir . $name . '_' . date('Y-m-d_H-i-s') . '.php');
    }

    // Save new content
    if (file_put_contents($filePath, $content)) {
        \Core\Cache::clear();
        $successMessage = 'Component saved successfully!';
    } else {
        $errorMessage = 'Failed to save component. Check file permissions.';
    }
}

// Load component content
$componentContent = '';
$isNew = true;
if ($componentName) {
    $filePath = $componentDir . $componentName . '.php';
    if (file_exists($filePath)) {
        $componentContent = file_get_contents($filePath);
        $isNew = false;
    }
}

// Page settings
$pageTitle = $isNew ? 'Create Component' : 'Edit: ' . ucwords(str_replace('_', ' ', $componentName));
$currentPage = 'components';

// Start content buffer
ob_start();
?>

<div class="columns">
    <div class="column is-8">
        <form method="POST" class="admin-form">
            <div class="admin-card">
                <h2 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-code"></i></span>
                    Component Template
                </h2>

                <?php if ($isNew): ?>
                    <div class="field">
                        <label class="label">Component Name</label>
                        <div class="control has-icons-left">
                            <input class="input" type="text" name="component_name" placeholder="my_component"
                                pattern="[a-z0-9_]+" required>
                            <span class="icon is-small is-left">
                                <i class="fas fa-puzzle-piece"></i>
                            </span>
                        </div>
                        <p class="help">Lowercase letters, numbers, and underscores only.</p>
                    </div>
                <?php else: ?>
                    <input type="hidden" name="component_name" value="<?= htmlspecialchars($componentName) ?>">
                <?php endif; ?>

                <div class="field">
                    <label class="label">PHP/HTML Template</label>
                    <div class="control">
                        <textarea class="textarea code-editor" name="component_content" rows="25"
                            style="font-family: monospace; font-size: 13px;"><?= htmlspecialchars($componentContent) ?></textarea>
                    </div>
                </div>

                <div class="buttons">
                    <button type="submit" name="save" class="button is-primary">
                        <span class="icon"><i class="fas fa-save"></i></span>
                        <span>Save Component</span>
                    </button>
                    <a href="/admin/components.php" class="button is-light">
                        <span class="icon"><i class="fas fa-arrow-left"></i></span>
                        <span>Back to Components</span>
                    </a>
                </div>
            </div>
        </form>
    </div>

    <div class="column is-4">
        <!-- Component Info -->
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-info-circle"></i></span>
                Component Info
            </h2>

            <?php if (!$isNew): ?>
                <table class="table is-fullwidth is-size-7">
                    <tr>
                        <td><strong>Name</strong></td>
                        <td><code><?= htmlspecialchars($componentName) ?></code></td>
                    </tr>
                    <tr>
                        <td><strong>Shortcode</strong></td>
                        <td><code>[component:<?= htmlspecialchars($componentName) ?>]</code></td>
                    </tr>
                    <tr>
                        <td><strong>File</strong></td>
                        <td><code>/themes/default/components/<?= htmlspecialchars($componentName) ?>.php</code></td>
                    </tr>
                </table>
            <?php else: ?>
                <p class="has-text-grey">Create a new component to see its info here.</p>
            <?php endif; ?>
        </div>

        <!-- Variable Reference -->
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-book"></i></span>
                Variable Reference
            </h2>
            <div class="content is-small">
                <p>Components receive shortcode attributes as PHP variables:</p>
                <pre style="background:#f5f5f5;padding:0.5rem;border-radius:4px;"><code>[component:name title="Hello"]

// In template:
&lt;?= $title ?&gt;</code></pre>

                <p class="mt-4"><strong>Common patterns:</strong></p>
                <ul>
                    <li><code>$title ?? 'Default'</code> - With default</li>
                    <li><code>isset($var) ? ... : ...</code> - Conditional</li>
                    <li><code>htmlspecialchars($var)</code> - Escape output</li>
                </ul>
            </div>
        </div>

        <!-- Template -->
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-file-code"></i></span>
                Starter Template
            </h2>
            <div class="content is-small">
                <button class="button is-small is-info is-fullwidth mb-3" onclick="insertTemplate()">
                    <span class="icon"><i class="fas fa-magic"></i></span>
                    <span>Insert Starter Template</span>
                </button>
                <p class="has-text-grey">Click to insert a basic component template structure.</p>
            </div>
        </div>

        <?php if (!$isNew): ?>
            <!-- Preview -->
            <div class="admin-card">
                <h2 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-eye"></i></span>
                    Preview
                </h2>
                <a href="/admin/component-preview.php?name=<?= htmlspecialchars($componentName) ?>" target="_blank"
                    class="button is-info is-light is-fullwidth">
                    <span class="icon"><i class="fas fa-external-link-alt"></i></span>
                    <span>Open Preview</span>
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    function insertTemplate() {
        const template = `<?php
        /**
         * My Custom Component
         * 
         * Attributes:
         * - title (required): Main heading
         * - subtitle (optional): Subheading text
         * - content (optional): Body content
         */

        // Get attributes with defaults
        $title = $title ?? 'Default Title';
        $subtitle = $subtitle ?? '';
        $content = $content ?? '';
        ?>
<section class="section">
    <div class="container">
        <div class="has-text-centered mb-6">
            <h2 class="title is-2"><?= htmlspecialchars($title) ?></h2>
            <?php if ($subtitle): ?>
            <p class="subtitle is-4"><?= htmlspecialchars($subtitle) ?></p>
            <?php endif; ?>
        </div>
        
        <?php if ($content): ?>
        <div class="content">
            <?= $content ?>
        </div>
        <?php endif; ?>
        
        <!-- Add your component HTML here -->
        
    </div>
</section>`;

        document.querySelector('.code-editor').value = template;
    }
</script>

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