<?php
$templateCsrf = \PpPhp\Core\Security::CSRF()->Token();
$templateRemoteProjects = array_values(array_filter($projects, static fn(array $p): bool => ($p['db_type'] ?? '') !== 'sqlite' && empty($p['archived_at'])));
?>
<div class="modal fade project-modal template-modal" id="templateLibraryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"><div class="modal-content">
        <div class="modal-header px-4 py-3"><div><div class="template-kicker"><i class="bi bi-layers"></i> Reusable starters</div><h5 class="modal-title mb-0">Project templates</h5></div><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close template library"></button></div>
<?php if (!empty($templateFeedStatus) && ($templateFeedStatus['licensed'] ?? true) === false): ?>
        <div class="template-feed-banner mx-4 mt-3 p-3 rounded" style="background:rgba(245,158,11,.12);border:1px solid rgba(245,158,11,.35);color:#b45309"><i class="bi bi-shield-exclamation me-1"></i> <strong>Connect your licence to load the template gallery.</strong> <span class="small"><?= htmlspecialchars((string)($templateFeedStatus['message'] ?? 'A valid licence is required.')) ?></span></div>
<?php endif; ?>
        <div class="template-library-toolbar"><div class="template-search"><i class="bi bi-search"></i><input class="form-control" id="templateSearch" type="search" placeholder="Search templates, categories, or tags"></div><div class="template-category-list" id="templateCategoryList"><?php foreach ($templateCategories as $index => $category): ?><button type="button" class="<?= $index === 0 ? 'active' : '' ?>" data-template-category="<?= htmlspecialchars($category) ?>"><?= htmlspecialchars($category) ?></button><?php endforeach; ?></div></div>
<?php if (!empty($templateViewerIsOwner)): ?>
        <div class="template-user-access px-4 pt-3"><label class="form-check form-switch d-flex align-items-center gap-2 mb-0" style="cursor:pointer"><input class="form-check-input mt-0" type="checkbox" id="templatesOpenToUsers" role="switch" <?= !empty($templatesOpenToUsers) ? 'checked' : '' ?>><span class="small"><i class="bi bi-people me-1"></i> Allow the <strong>User</strong> group to browse &amp; use templates <span class="text-muted">— each template’s own access still applies (e.g. data-bearing ones stay owner-only)</span></span></label></div>
<?php endif; ?>
        <div class="modal-body p-4"><div class="template-grid" id="templateGrid">
            <?php foreach ($projectTemplates as $template): $content = $template['content']; $codeCount = (int)($content['executable_custom_files'] ?? 0); $isBuiltin = !empty($template['builtin']); ?>
            <article class="template-card<?= $isBuiltin ? ' template-card-builtin' : '' ?>" data-template-card data-template-id="<?= htmlspecialchars((string)$template['id']) ?>" data-template-name="<?= htmlspecialchars($template['name']) ?>" data-template-slug="<?= htmlspecialchars($template['slug']) ?>" data-template-description="<?= htmlspecialchars($template['description']) ?>" data-template-category="<?= htmlspecialchars($template['category']) ?>" data-template-code-count="<?= $codeCount ?>" data-template-content="<?= !empty($template['has_content']) ? '1' : '0' ?>" data-template-roles="<?= htmlspecialchars(implode(',', (array)($template['roles'] ?? []))) ?>" data-template-search="<?= htmlspecialchars(strtolower(implode(' ', [$template['name'], $template['description'], $template['category'], implode(' ', $template['tags'])]))) ?>" style="--template-accent:<?= htmlspecialchars($template['color']) ?>">
                <div class="template-card-top"><span class="template-card-icon"><i class="bi bi-<?= htmlspecialchars($template['icon']) ?>"></i></span><span class="template-category-badge"><?= htmlspecialchars($template['category']) ?></span><?php if ($isBuiltin): ?><span class="template-category-badge" style="background:rgba(79,70,229,.14);color:#4f46e5" title="A built-in platform template — always available, can’t be deleted"><i class="bi bi-shield-check me-1"></i>Built-in</span><span class="template-category-badge template-audience-badge" style="background:rgba(245,158,11,.14);color:#b45309" title="Who can use this template"><i class="bi bi-people me-1"></i><?= htmlspecialchars($template['audience'] ?? '') ?></span><?php endif; ?><?php if (!empty($template['version'])): ?><span class="template-category-badge template-version-badge" style="background:rgba(5,150,105,.14);color:#059669" title="Template version — bumps when you publish an updated build; compare it to spot an outdated upload">v<?= htmlspecialchars((string)$template['version']) ?></span><?php endif; ?><div class="dropdown"><button type="button" class="template-menu" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button><ul class="dropdown-menu dropdown-menu-end"><li><button class="dropdown-item" type="button" data-template-action="export"><i class="bi bi-download me-2"></i>Export template</button></li><?php if ($isBuiltin && !empty($templateViewerIsOwner)): ?><li><button class="dropdown-item" type="button" data-template-action="access"><i class="bi bi-people me-2"></i>Manage access</button></li><?php endif; ?><?php if (!$isBuiltin): ?><li><button class="dropdown-item text-danger" type="button" data-template-action="delete"><i class="bi bi-trash3 me-2"></i>Delete template</button></li><?php endif; ?></ul></div></div>
                <h3><?= htmlspecialchars($template['name']) ?></h3><p><?= htmlspecialchars($template['description'] ?: 'Reusable project configuration and design.') ?></p>
                <div class="template-meta"><span><i class="bi bi-sliders"></i><?= (int)($content['configuration_files'] ?? 0) ?> configs</span><span><i class="bi bi-folder2"></i><?= (int)($content['custom_files'] ?? 0) ?> files</span><?php if ($codeCount): ?><span class="active-code"><i class="bi bi-code-slash"></i><?= $codeCount ?> active</span><?php endif; ?></div>
                <div class="template-tags"><?php foreach (array_slice($template['tags'], 0, 4) as $tag): ?><span><?= htmlspecialchars($tag) ?></span><?php endforeach; ?></div>
                <footer><span><i class="bi bi-clock-history"></i><?= htmlspecialchars(date('M j, Y', strtotime($template['updated_at']))) ?></span><button class="btn btn-sm btn-primary" type="button" data-template-action="use">Use template <i class="bi bi-arrow-right ms-1"></i></button></footer>
            </article><?php endforeach; ?>
        </div><div class="template-empty <?= $projectTemplates ? '' : 'show' ?>" id="templateEmpty"><i class="bi bi-layers"></i><h6>No templates in this view</h6><p>Open a project’s action menu and choose “Save as Template” to build your reusable library.</p></div></div>
    </div></div>
</div>

<div class="modal fade project-modal template-modal" id="saveTemplateModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
    <div class="modal-header px-4 py-3"><div><div class="template-kicker"><i class="bi bi-bookmark-plus"></i> Capture reusable work</div><h5 class="modal-title mb-0">Save as template</h5></div><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close save template"></button></div>
    <form id="saveTemplateForm"><div class="modal-body p-4"><div class="template-security-note"><i class="bi bi-shield-lock"></i><div><strong>Safe by default</strong><span>Database credentials and structured secrets are removed. SQLite data is never stored in a template.</span></div></div>
        <div class="row g-3 mt-1"><div class="col-md-7"><label class="form-label small fw-semibold">Template name</label><input class="form-control" name="name" id="saveTemplateName" maxlength="100" required></div><div class="col-md-5"><label class="form-label small fw-semibold">Template slug</label><input class="form-control" name="slug" id="saveTemplateSlug" pattern="[a-z0-9]+(?:-[a-z0-9]+)*" required></div><div class="col-12"><label class="form-label small fw-semibold">Description</label><textarea class="form-control" name="description" id="saveTemplateDescription" rows="2" maxlength="1000"></textarea></div><div class="col-md-5"><label class="form-label small fw-semibold">Category</label><select class="form-select" name="category"><?php foreach (array_slice($templateCategories,1) as $category): ?><option><?= htmlspecialchars($category) ?></option><?php endforeach; ?></select></div><div class="col-md-7"><label class="form-label small fw-semibold">Tags</label><input class="form-control" name="tags" placeholder="portal, internal, responsive"><div class="form-text">Up to eight comma-separated tags.</div></div></div>
        <label class="form-check transfer-check mt-3"><input class="form-check-input" type="checkbox" name="include_custom" value="1" checked><span><strong>Include Custom Files</strong><small>Active code is recorded in the template manifest and requires confirmation when used.</small></span></label>
    </div><div class="modal-footer px-4 py-3"><button class="btn btn-light border" type="button" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="saveTemplateSubmit" type="submit"><i class="bi bi-bookmark-plus me-1"></i> Save template</button></div></form>
</div></div></div>

<div class="modal fade project-modal template-modal" id="useTemplateModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header px-4 py-3"><div><div class="template-kicker"><i class="bi bi-stars"></i> New from template</div><h5 class="modal-title mb-0">Use <span id="useTemplateTitle"></span></h5></div><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close use template"></button></div>
    <form id="useTemplateForm"><input type="hidden" name="template_id" id="useTemplateId"><div class="modal-body p-4">
        <fieldset class="transfer-fieldset"><legend>Where to apply</legend>
            <label class="transfer-choice"><input type="radio" name="target_mode" value="new" checked><span class="choice-icon violet"><i class="bi bi-plus-square"></i></span><span><strong>Create a new project</strong><small>Sets up a brand-new project from this template.</small></span></label>
            <?php $ownProjects = array_values(array_filter($projects, static fn(array $pp): bool => empty($pp['archived_at']))); if ($ownProjects): ?>
            <label class="transfer-choice"><input type="radio" name="target_mode" value="update"><span class="choice-icon amber"><i class="bi bi-arrow-repeat"></i></span><span class="flex-grow-1"><strong>Update an existing project</strong><small>Restore this template’s design &amp; files onto a project you already have — its database &amp; data are kept.</small><select class="form-select form-select-sm mt-2" name="target_project"><?php foreach ($ownProjects as $pp): ?><option value="<?= htmlspecialchars($pp['slug']) ?>"><?= htmlspecialchars($pp['name'].' · /'.$pp['slug']) ?></option><?php endforeach; ?></select></span></label>
            <?php endif; ?>
        </fieldset>
        <div id="useTemplateNewFields"><div class="row g-3 mt-1"><div class="col-md-7"><label class="form-label small fw-semibold">Project name</label><input class="form-control" name="name" id="useTemplateProjectName" maxlength="100" required></div><div class="col-md-5"><label class="form-label small fw-semibold">Project slug</label><input class="form-control" name="slug" id="useTemplateProjectSlug" pattern="[a-z0-9]+(?:-[a-z0-9]+)*" required></div><div class="col-12"><label class="form-label small fw-semibold">Description</label><textarea class="form-control" name="description" id="useTemplateProjectDescription" rows="2" maxlength="1000"></textarea></div></div>
        <fieldset class="transfer-fieldset mt-3"><legend>Database connection</legend>
            <div class="template-db-hint d-none" id="useTemplateDbHint"><i class="bi bi-info-circle-fill"></i> This template restores content into a <strong>MySQL / MariaDB</strong> database — pick one of the database options below (SQLite starts empty).</div>
            <label class="transfer-choice"><input type="radio" name="connection_mode" value="sqlite" checked><span class="choice-icon violet"><i class="bi bi-device-ssd"></i></span><span><strong>Portable SQLite workspace</strong><small>Creates a clean local database. Best for a starter template (no content).</small></span></label>
            <?php if (!empty($assignedDbs)): ?>
            <label class="transfer-choice"><input type="radio" name="connection_mode" value="managed"><span class="choice-icon teal"><i class="bi bi-hdd-network"></i></span><span class="flex-grow-1"><strong>Use a database assigned to me</strong><small>Restore into one of your provisioned databases. Credentials stay on the server.</small><select class="form-select form-select-sm mt-2" name="managed_db_id"><?php foreach ($assignedDbs as $mdb): ?><option value="<?= (int)($mdb['id'] ?? 0) ?>"><?= htmlspecialchars((string)($mdb['label'] ?? 'Database').' · '.($mdb['db_name'] ?? '')) ?></option><?php endforeach; ?></select></span></label>
            <?php endif; ?>
            <label class="transfer-choice"><input type="radio" name="connection_mode" value="custom"><span class="choice-icon amber"><i class="bi bi-database-gear"></i></span><span class="flex-grow-1"><strong>Connect to a database</strong><small>Enter MySQL / MariaDB connection details.</small><div class="row g-2 mt-1"><input type="hidden" name="db_type" value="mysql"><div class="col-6"><input class="form-control form-control-sm" name="db_host" placeholder="Host (e.g. localhost)" autocomplete="off"></div><div class="col-6"><input class="form-control form-control-sm" name="db_name" placeholder="Database name" autocomplete="off"></div><div class="col-6"><input class="form-control form-control-sm" name="db_user" placeholder="Username" autocomplete="off"></div><div class="col-6"><input class="form-control form-control-sm" type="password" name="db_pass" placeholder="Password" autocomplete="new-password"></div></div></span></label>
            <?php if ($templateRemoteProjects): ?><label class="transfer-choice"><input type="radio" name="connection_mode" value="existing"><span class="choice-icon blue"><i class="bi bi-link-45deg"></i></span><span class="flex-grow-1"><strong>Use an existing project connection</strong><small>Credentials are copied only on the server.</small><select class="form-select form-select-sm mt-2" name="connection_project"><?php foreach ($templateRemoteProjects as $p): ?><option value="<?= htmlspecialchars($p['slug']) ?>"><?= htmlspecialchars($p['name'].' · '.$p['db_label']) ?></option><?php endforeach; ?></select></span></label><?php endif; ?>
        </fieldset>
        <label class="form-check transfer-check mt-3" id="useTemplateSchemaOption"><input class="form-check-input" type="checkbox" name="initialize_schema" value="1" checked><span><strong>Initialize missing SQLite tables</strong><small>Applies the template’s data-free, dialect-neutral schema blueprint. No sample records are added.</small></span></label>
        </div>
        <div id="useTemplateUpdateFields" class="d-none">
            <div class="template-db-hint" style="border-color:rgba(245,158,11,.45)"><i class="bi bi-exclamation-triangle-fill"></i> This <strong>replaces the selected project’s design and custom files</strong> with the template’s. Its database connection and existing data are kept — content is only added if the database is empty.</div>
            <label class="form-check transfer-check mt-2"><input class="form-check-input" type="checkbox" name="confirm_update" value="1"><span><strong>I understand — restore this template onto the selected project</strong></span></label>
        </div>
        <label class="form-check transfer-check mt-3 d-none" id="useTemplateCodeConfirmation"><input class="form-check-input" type="checkbox" name="allow_code" value="1"><span><strong>I reviewed this template’s active code</strong><small>Only use templates you trust; PHP, JavaScript, HTML/SVG, and server rules can execute code.</small></span></label>
    </div><div class="modal-footer px-4 py-3"><button class="btn btn-light border" type="button" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="useTemplateSubmit" type="submit"><i class="bi bi-stars me-1"></i> Create project</button></div></form>
</div></div></div>

<form id="templateExportForm" method="post" class="d-none"><input type="hidden" name="_token" value="<?= htmlspecialchars($templateCsrf) ?>"></form>

<?php if (!empty($templateViewerIsOwner)): ?>
<div class="modal fade project-modal template-modal" id="templateAccessModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
    <div class="modal-header px-4 py-3"><div><div class="template-kicker"><i class="bi bi-people"></i> Who can use this</div><h5 class="modal-title mb-0">Access — <span id="templateAccessTitle"></span></h5></div><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close access"></button></div>
    <form id="templateAccessForm"><input type="hidden" name="template_id" id="templateAccessId"><div class="modal-body p-4">
        <p class="small text-muted mb-3">Choose which permission groups can see and use this template. The <strong>Owner</strong> always has access — data-bearing templates should usually stay owner-only.</p>
        <label class="form-check transfer-check"><input class="form-check-input" type="checkbox" checked disabled><span><strong>Owner</strong><small>Always included — cannot be removed.</small></span></label>
        <label class="form-check transfer-check mt-2"><input class="form-check-input" type="checkbox" name="role_superadmin" value="1"><span><strong>Superadmin</strong><small>Full administrators.</small></span></label>
        <label class="form-check transfer-check mt-2"><input class="form-check-input" type="checkbox" name="role_developer" value="1"><span><strong>Developer</strong><small>Can build projects.</small></span></label>
        <label class="form-check transfer-check mt-2"><input class="form-check-input" type="checkbox" name="role_user" value="1"><span><strong>User</strong><small>Standard members.</small></span></label>

        <hr class="my-3">
        <div class="template-user-picker">
            <label class="small fw-semibold d-block mb-1"><i class="bi bi-person-plus me-1"></i> Specific users <span class="text-muted fw-normal">— grant to individuals regardless of their group</span></label>
            <div class="position-relative">
                <input type="text" class="form-control form-control-sm" id="templateUserSearch" placeholder="Search users by name or email…" autocomplete="off">
                <div id="templateUserResults" class="list-group position-absolute w-100 shadow-sm" style="z-index:1090;max-height:220px;overflow:auto;display:none;border:1px solid var(--pp-border,#e2e8f0);border-radius:8px"></div>
            </div>
            <div id="templateUserChips" class="d-flex flex-wrap gap-1 mt-2"></div>
            <div id="templateUserEmpty" class="small text-muted mt-1">No individual users assigned yet.</div>
        </div>
    </div><div class="modal-footer px-4 py-3"><button class="btn btn-light border" type="button" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="templateAccessSubmit" type="submit"><i class="bi bi-check2 me-1"></i> Save access</button></div></form>
</div></div></div>
<?php endif; ?>
