<?php
/**
 * Super Admin Standard Template Creator
 * Location: public_html/admin/create_artifact.php
 * Purpose: Allows Super Admins to build "Standard Templates" that all users across all accounts will have access to see and use.
 */

require_once __DIR__ . '/../connections/connect.php';
if (file_exists(__DIR__ . '/../includes/functions.php')) {
    require_once __DIR__ . '/../includes/functions.php';
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Defensive helper fallback (ensures no fatal error if functions.php was not updated on disk)
if (!function_exists('is_admin_logged_in')) {
    function is_admin_logged_in() {
        return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true && !empty($_SESSION['admin_user_id']);
    }
}
if (!function_exists('require_admin_login')) {
    function require_admin_login() {
        if (!is_admin_logged_in()) {
            header("Location: login_admin.php?error=" . urlencode("Super Administrator authentication required."));
            exit;
        }
    }
}
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        return htmlspecialchars(trim((string)$data), ENT_QUOTES, 'UTF-8');
    }
}

// Enforce Super Admin authentication
require_admin_login();

$msg = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $category = trim($_POST['category'] ?? 'General');
    $type = trim($_POST['type'] ?? 'QC_CHECKLIST');
    $description = trim($_POST['description'] ?? '');
    $fields_raw = $_POST['fields'] ?? [];

    if (empty($title)) {
        $error = "Standard Template title is required.";
    } else {
        try {
            $pdo->beginTransaction();

            $template_id = 'tmpl_std_' . uniqid();

            // Insert into artifact_templates with account_id = NULL and is_standard_template = 1
            $stmt = $pdo->prepare("
                INSERT INTO artifact_templates (id, account_id, type, title, description, category, is_standard_template, created_at)
                VALUES (:id, NULL, :type, :title, :description, :category, 1, NOW())
            ");
            $stmt->execute([
                'id' => $template_id,
                'type' => $type,
                'title' => $title,
                'description' => $description,
                'category' => $category,
            ]);

            // Insert template fields if provided
            if (!empty($fields_raw) && is_array($fields_raw)) {
                $fieldStmt = $pdo->prepare("
                    INSERT INTO artifact_template_fields (id, template_id, field_label, field_type, options_json, is_required, help_text, sort_order)
                    VALUES (:id, :template_id, :field_label, :field_type, :options_json, :is_required, :help_text, :sort_order)
                ");

                $sort = 1;
                foreach ($fields_raw as $f) {
                    if (empty($f['label'])) continue;

                    $field_id = 'fld_' . uniqid();
                    $f_type = $f['type'] ?? 'SINGLE_CHOICE';
                    $options_json = null;
                    
                    // Only store options JSON for choice-based types
                    if (in_array($f_type, ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN']) && !empty($f['options'])) {
                        $opts_array = array_map('trim', explode(',', $f['options']));
                        $clean_opts = array_values(array_filter($opts_array));
                        if (!empty($clean_opts)) {
                            $options_json = json_encode($clean_opts);
                        }
                    }

                    $fieldStmt->execute([
                        'id' => $field_id,
                        'template_id' => $template_id,
                        'field_label' => trim($f['label']),
                        'field_type' => $f_type,
                        'options_json' => $options_json,
                        'is_required' => !empty($f['required']) ? 1 : 0,
                        'help_text' => trim($f['help_text'] ?? ''),
                        'sort_order' => $sort++
                    ]);
                }
            }

                // Commit template creation FIRST
                $pdo->commit();
                $msg = "Standard Template '{$title}' published globally! All application users can now use it.";

                // Record audit log non-blockingly with NULL account_id (system level event)
                try {
                    $logStmt = $pdo->prepare("
                        INSERT INTO audit_logs (id, account_id, user_id, action, details, ip_address)
                        VALUES (:id, NULL, :admin_id, 'STANDARD_TEMPLATE_PUBLISHED', :details, :ip)
                    ");
                    $logStmt->execute([
                        'id' => 'log_' . uniqid(),
                        'admin_id' => $_SESSION['admin_user_id'],
                        'details' => "Published global standard template: '{$title}'",
                        'ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                    ]);
                } catch (Exception $logEx) {
                    // Non-blocking log catch (prevents audit foreign key constraint from blocking template creation)
                }
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = "Failed to create standard template: " . $e->getMessage();
        }
    }
}

// Fetch all existing Standard Templates for overview
$stdTemplates = [];
$stdFieldsMap = [];
try {
    $stmt = $pdo->query("
        SELECT t.*, COUNT(f.id) as field_count 
        FROM artifact_templates t 
        LEFT JOIN artifact_template_fields f ON t.id = f.template_id 
        WHERE t.is_standard_template = 1 OR t.account_id IS NULL 
        GROUP BY t.id 
        ORDER BY t.created_at DESC
    ");
    $stdTemplates = $stmt->fetchAll();

    // Fetch fields mapped by template_id for preview and cloning
    $stmt_flds = $pdo->query("
        SELECT f.* 
        FROM artifact_template_fields f
        INNER JOIN artifact_templates t ON f.template_id = t.id
        WHERE t.is_standard_template = 1 OR t.account_id IS NULL
        ORDER BY f.template_id, f.sort_order ASC
    ");
    $raw_flds = $stmt_flds->fetchAll();
    foreach ($raw_flds as $rf) {
        $stdFieldsMap[$rf['template_id']][] = $rf;
    }
} catch (Exception $e) {}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Standard QC Template - MiBuildqc Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>body { font-family: 'Plus Jakarta Sans', sans-serif; }</style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen">

    <!-- Top Navigation -->
    <header class="bg-slate-950 border-b border-slate-800 sticky top-0 z-30">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3.5 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <a href="dashboard_admin.php" class="p-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                    </svg>
                </a>
                <h1 class="text-sm font-bold text-white">Standard QC Template Designer (create_artifact.php)</h1>
            </div>

            <div class="flex items-center gap-3">
                <a href="dashboard_admin.php" class="px-3.5 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs font-semibold text-slate-300">
                    Back to Admin Dashboard
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-5xl mx-auto px-4 sm:px-6 py-8 space-y-8">

        <?php if (!empty($msg)): ?>
            <div class="p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs flex items-center justify-between">
                <span><?php echo htmlspecialchars($msg); ?></span>
                <button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white">✕</button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="p-4 rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs flex items-center justify-between">
                <span><?php echo htmlspecialchars($error); ?></span>
                <button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white">✕</button>
            </div>
        <?php endif; ?>

        <!-- Builder Form -->
        <div class="bg-slate-800/90 border border-slate-700/80 rounded-3xl p-6 sm:p-8 space-y-6 shadow-2xl">
            <div class="border-b border-slate-700/80 pb-4">
                <h2 class="text-lg font-bold text-white">Build Global Standard QC Template</h2>
                <p class="text-xs text-slate-400 mt-1">
                    Templates built here are stored globally (account_id = NULL, is_standard_template = 1) so every company account and user has instant access.
                </p>
            </div>

            <form action="create_artifact.php" method="POST" class="space-y-6" id="templateForm">
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="md:col-span-2">
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Standard Template Title *</label>
                        <input type="text" name="title" id="form-title" required placeholder="e.g. Waterproofing Membrane Pre-Tile Inspection" class="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Category *</label>
                        <select name="category" id="form-category" class="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white outline-none">
                            <option value="Foundation & Concrete">Foundation & Concrete</option>
                            <option value="Structural & Framing">Structural & Framing</option>
                            <option value="Waterproofing & Roofing">Waterproofing & Roofing</option>
                            <option value="Mechanical & Electrical">Mechanical & Electrical</option>
                            <option value="Finishes & Fitout">Finishes & Fitout</option>
                            <option value="Safety & Compliance">Safety & Compliance</option>
                            <option value="General">General</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Artifact Type *</label>
                        <select name="type" id="form-type" class="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white outline-none">
                            <option value="QC_CHECKLIST">QC Checklist</option>
                            <option value="QUESTIONNAIRE">Questionnaire / Audit Form</option>
                            <option value="BUILD_STAGE_REVIEW">Build Stage Review</option>
                            <option value="DOCUMENT_UPLOAD">Compliance Document Upload</option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label class="block text-xs font-semibold text-slate-300 mb-1">Description</label>
                        <input type="text" name="description" id="form-description" placeholder="Short description of QC requirements and objectives..." class="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                    </div>
                </div>

                <!-- Dynamic Question / Field Builder -->
                <div class="space-y-4 pt-4 border-t border-slate-700/80">
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                        <div>
                            <h3 class="text-xs font-bold uppercase tracking-wider text-slate-300">Checklist Questions & Inspection Criteria</h3>
                            <p class="text-[11px] text-slate-400">Configure questions, single/multi choices, photo evidence uploads, and signatures.</p>
                        </div>
                    </div>

                    <!-- Field Types Control Palette (Exact Parity with Primary Owner) -->
                    <div class="p-4 rounded-2xl bg-slate-900/90 border border-slate-700 space-y-3">
                        <span class="text-xs font-bold text-slate-300 uppercase tracking-wider block">
                            Add Questions / Fields to Form
                        </span>
                        <div class="flex flex-wrap gap-2">
                            <button type="button" onclick="addField('TEXT')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-indigo-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"></path></svg>
                                Short Text
                            </button>
                            <button type="button" onclick="addField('TEXTAREA')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-indigo-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h10"></path></svg>
                                Long Textarea
                            </button>
                            <button type="button" onclick="addField('SINGLE_CHOICE')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-emerald-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                Single Choice (Radio)
                            </button>
                            <button type="button" onclick="addField('MULTI_CHOICE')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-amber-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
                                Multiple Choice
                            </button>
                            <button type="button" onclick="addField('DROPDOWN')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-cyan-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path></svg>
                                Dropdown List
                            </button>
                            <button type="button" onclick="addField('PHOTO_UPLOAD')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-purple-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                Photo Upload
                            </button>
                            <button type="button" onclick="addField('SIGNATURE')" class="px-3 py-1.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 text-xs font-medium hover:border-indigo-500 hover:text-rose-400 transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5 text-rose-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                Digital Signature
                            </button>
                        </div>
                    </div>

                    <div id="fieldsContainer" class="space-y-3">
                        <!-- Populated by JavaScript -->
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-700/80">
                    <a href="dashboard_admin.php" class="px-4 py-2.5 rounded-xl border border-slate-700 text-slate-300 text-xs font-semibold hover:bg-slate-800">
                        Cancel
                    </a>
                    <button type="submit" class="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs rounded-xl shadow-lg transition-all">
                        Publish Global Standard Template
                    </button>
                </div>
            </form>
        </div>

        <!-- Existing Standard Templates List with Preview & Clone (Full Parity with Primary Owner) -->
        <div class="bg-slate-800/90 border border-slate-700/80 rounded-3xl p-6 sm:p-8 space-y-6 shadow-xl">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-700/80 pb-4">
                <div>
                    <h3 class="text-base font-bold text-white flex items-center gap-2">
                        <svg class="w-5 h-5 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
                        <span>Existing Standard QC Templates (<?php echo count($stdTemplates); ?>)</span>
                    </h3>
                    <p class="text-xs text-slate-400 mt-0.5">
                        Preview full question checklists or clone questions directly into the designer above to create new templates.
                    </p>
                </div>

                <div class="w-full sm:w-64">
                    <input type="text" id="std-search-input" onkeyup="filterStdList()" placeholder="Search templates, categories..." class="w-full px-3.5 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                </div>
            </div>

            <!-- Category Filter Chips -->
            <div class="flex items-center gap-2 overflow-x-auto pb-1 text-xs" id="std-category-chips">
                <button type="button" onclick="setStdCategory('ALL')" class="std-cat-btn px-3 py-1 rounded-xl bg-indigo-600 text-white font-bold transition-all" data-cat="ALL">All</button>
                <button type="button" onclick="setStdCategory('Foundation & Concrete')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="Foundation & Concrete">Foundation & Concrete</button>
                <button type="button" onclick="setStdCategory('Structural & Framing')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="Structural & Framing">Structural & Framing</button>
                <button type="button" onclick="setStdCategory('Waterproofing & Roofing')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="Waterproofing & Roofing">Waterproofing & Roofing</button>
                <button type="button" onclick="setStdCategory('Finishes & Fitout')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="Finishes & Fitout">Finishes & Fitout</button>
                <button type="button" onclick="setStdCategory('Safety & Compliance')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="Safety & Compliance">Safety & Compliance</button>
                <button type="button" onclick="setStdCategory('General')" class="std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all" data-cat="General">General</button>
            </div>

            <!-- Standard Templates Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="std-templates-grid">
                <?php foreach ($stdTemplates as $st): 
                    $t_id = $st['id'];
                    $t_fields = $stdFieldsMap[$t_id] ?? [];
                ?>
                    <div class="std-card p-5 bg-slate-900 border border-slate-700/80 hover:border-slate-600 rounded-2xl space-y-3 transition-all flex flex-col justify-between" data-category="<?php echo htmlspecialchars($st['category']); ?>" data-title="<?php echo strtolower(htmlspecialchars($st['title'])); ?>">
                        <div class="space-y-2">
                            <div class="flex items-center justify-between gap-2">
                                <span class="text-[10px] font-bold px-2.5 py-0.5 rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                                    <?php echo htmlspecialchars($st['category']); ?>
                                </span>
                                <span class="text-[11px] font-mono text-slate-400 bg-slate-800 px-2 py-0.5 rounded border border-slate-700">
                                    <?php echo count($t_fields); ?> Configured Fields
                                </span>
                            </div>
                            <div class="font-bold text-white text-sm"><?php echo htmlspecialchars($st['title']); ?></div>
                            <p class="text-xs text-slate-400 line-clamp-2"><?php echo htmlspecialchars($st['description'] ?? 'Standard QC checklist.'); ?></p>
                        </div>

                        <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-800">
                            <!-- Preview Button -->
                            <button type="button" onclick="openStdPreviewModal('<?php echo $t_id; ?>')" class="px-3.5 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-semibold transition-all flex items-center gap-1.5 border border-slate-700">
                                <svg class="w-3.5 h-3.5 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                                <span>Preview (<?php echo count($t_fields); ?>)</span>
                            </button>

                            <!-- Clone to Designer Button -->
                            <button type="button" onclick="cloneStdTemplate('<?php echo $t_id; ?>')" class="px-3.5 py-1.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                <span>Clone to Designer</span>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

    </main>

    <!-- Standard Template Preview Modal (Scrollable, supports 40+ fields) -->
    <div id="std-preview-modal" class="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4 hidden">
        <div class="bg-slate-900 border border-slate-700 rounded-3xl max-w-2xl w-full max-h-[90vh] flex flex-col shadow-2xl overflow-hidden">
            <!-- Modal Header -->
            <div class="p-6 border-b border-slate-800 flex items-start justify-between gap-4 bg-slate-950/60 shrink-0">
                <div class="space-y-1">
                    <div class="flex items-center gap-2">
                        <span id="preview-category" class="text-[10px] font-bold px-2 py-0.5 rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">Category</span>
                        <span id="preview-type" class="text-[10px] font-bold px-2 py-0.5 rounded bg-slate-800 text-slate-300 border border-slate-700">QC_CHECKLIST</span>
                    </div>
                    <h3 id="preview-title" class="text-lg font-bold text-white">Template Preview</h3>
                    <p id="preview-description" class="text-xs text-slate-400 line-clamp-2">Description</p>
                </div>
                <button type="button" onclick="closeStdPreviewModal()" class="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-slate-800 transition-colors">✕</button>
            </div>

            <!-- Modal Search Filter & Stats Strip -->
            <div class="px-6 py-3 bg-slate-800/60 border-b border-slate-800 flex items-center justify-between gap-3 shrink-0">
                <span id="preview-count" class="text-xs text-slate-400 font-semibold">0 Questions</span>
                <input type="text" id="modal-search-input" onkeyup="filterModalQuestions()" placeholder="Search questions in this template..." class="px-3 py-1.5 bg-slate-900 border border-slate-700 rounded-lg text-xs text-white outline-none focus:border-indigo-500 w-56">
            </div>

            <!-- Modal Body: Scrollable Question Items -->
            <div id="preview-fields-list" class="p-6 space-y-3 overflow-y-auto flex-1 divide-y divide-slate-800/60">
                <!-- Injected via JavaScript -->
            </div>

            <!-- Modal Footer -->
            <div class="p-4 bg-slate-950/80 border-t border-slate-800 flex items-center justify-between gap-3 shrink-0">
                <button type="button" onclick="closeStdPreviewModal()" class="px-4 py-2 rounded-xl border border-slate-700 text-slate-300 text-xs font-semibold hover:bg-slate-800">
                    Close Preview
                </button>
                <button type="button" id="preview-modal-clone-btn" onclick="" class="px-5 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold transition-all shadow-md flex items-center gap-1.5">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                    <span>Clone Template into Builder</span>
                </button>
            </div>
        </div>
    </div>

    <script>
        const stdTemplatesData = <?php echo json_encode($stdTemplates); ?>;
        const stdFieldsData = <?php echo json_encode($stdFieldsMap); ?>;
        let fieldIndex = 0;
        let activeCategory = 'ALL';

        function handleAdminTypeChange(selectEl) {
            const row = selectEl.closest('.field-row');
            const optionsContainer = row.querySelector('.options-container');
            const optionsInput = row.querySelector('.options-input');
            const typeBadge = row.querySelector('.field-type-badge');
            const isChoice = ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN'].includes(selectEl.value);

            if (typeBadge) {
                typeBadge.innerText = selectEl.value.replace('_', ' ');
            }

            if (optionsContainer) {
                if (isChoice) {
                    optionsContainer.style.opacity = '1';
                    optionsContainer.style.pointerEvents = 'auto';
                    if (!optionsInput.value.trim()) {
                        optionsInput.value = selectEl.value === 'DROPDOWN' ? 'Satisfactory, Minor Defect, Major Defect' : 'Pass, Fail, N/A';
                    }
                } else {
                    optionsContainer.style.opacity = '0.3';
                    optionsContainer.style.pointerEvents = 'none';
                    optionsInput.value = '';
                }
            }
        }

        function addField(type = 'SINGLE_CHOICE', label = '', options = '', helpText = '') {
            const container = document.getElementById('fieldsContainer');
            const row = document.createElement('div');
            row.className = 'p-4 bg-slate-900/80 border border-slate-700 rounded-2xl space-y-3 field-row transition-all';
            
            if (type === 'SINGLE_CHOICE' && !options) {
                options = 'Pass, Fail, N/A';
            } else if (type === 'MULTI_CHOICE' && !options) {
                options = 'Option 1, Option 2, Option 3';
            } else if (type === 'DROPDOWN' && !options) {
                options = 'Satisfactory, Minor Defect, Major Defect';
            }

            const isChoice = ['SINGLE_CHOICE', 'MULTI_CHOICE', 'DROPDOWN'].includes(type);

            row.innerHTML = `
                <div class="flex items-center justify-between gap-3">
                    <div class="flex items-center gap-2">
                        <span class="w-6 h-6 rounded-full bg-indigo-600 text-white flex items-center justify-center text-xs font-bold shrink-0 field-badge">
                            ${container.children.length + 1}
                        </span>
                        <span class="field-type-badge text-[10px] font-bold px-2 py-0.5 rounded bg-slate-800 text-slate-300 border border-slate-700 uppercase tracking-wider">
                            ${type.replace('_', ' ')}
                        </span>
                        <div class="flex items-center gap-1">
                            <button type="button" onclick="moveFieldUp(this)" title="Move question up" class="btn-move-up p-1 rounded-md text-slate-400 hover:text-indigo-300 hover:bg-slate-800 border border-slate-700 bg-slate-900 text-xs font-semibold flex items-center gap-0.5 transition-all">
                                ▲ <span class="text-[10px] hidden sm:inline">Up</span>
                            </button>
                            <button type="button" onclick="moveFieldDown(this)" title="Move question down" class="btn-move-down p-1 rounded-md text-slate-400 hover:text-indigo-300 hover:bg-slate-800 border border-slate-700 bg-slate-900 text-xs font-semibold flex items-center gap-0.5 transition-all">
                                ▼ <span class="text-[10px] hidden sm:inline">Down</span>
                            </button>
                        </div>
                    </div>
                    <button type="button" onclick="removeField(this)" class="text-rose-400 hover:text-rose-300 text-xs font-semibold flex items-center gap-1">
                        ✕ Remove
                    </button>
                </div>

                <div>
                    <input type="text" name="fields[${fieldIndex}][label]" value="${label.replace(/"/g, '&quot;')}" placeholder="Question / Inspection check item..." required class="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-xl text-xs text-white outline-none focus:border-indigo-500 field-label-input">
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                    <div>
                        <label class="block text-[10px] text-slate-400 mb-1">Field Type</label>
                        <select name="fields[${fieldIndex}][type]" onchange="handleAdminTypeChange(this)" class="w-full px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-xs text-white outline-none field-type-select">
                            <option value="SINGLE_CHOICE" ${type === 'SINGLE_CHOICE' ? 'selected' : ''}>Single Choice (Radio)</option>
                            <option value="MULTI_CHOICE" ${type === 'MULTI_CHOICE' ? 'selected' : ''}>Multi Choice (Checkboxes)</option>
                            <option value="DROPDOWN" ${type === 'DROPDOWN' ? 'selected' : ''}>Dropdown List</option>
                            <option value="TEXT" ${type === 'TEXT' ? 'selected' : ''}>Short Text</option>
                            <option value="TEXTAREA" ${type === 'TEXTAREA' ? 'selected' : ''}>Detailed Textarea</option>
                            <option value="PHOTO_UPLOAD" ${type === 'PHOTO_UPLOAD' ? 'selected' : ''}>Photo Evidence Upload</option>
                            <option value="SIGNATURE" ${type === 'SIGNATURE' ? 'selected' : ''}>Digital Signature</option>
                        </select>
                    </div>
                    <div class="options-container" style="opacity: ${isChoice ? '1' : '0.3'}; pointer-events: ${isChoice ? 'auto' : 'none'};">
                        <label class="block text-[10px] text-slate-400 mb-1">Options (comma-separated)</label>
                        <input type="text" name="fields[${fieldIndex}][options]" value="${options.replace(/"/g, '&quot;')}" placeholder="Pass, Fail, N/A" class="w-full px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-xs text-white options-input outline-none">
                    </div>
                    <div>
                        <label class="block text-[10px] text-slate-400 mb-1">Help / Subtext</label>
                        <input type="text" name="fields[${fieldIndex}][help_text]" value="${helpText.replace(/"/g, '&quot;')}" placeholder="Guidance for inspector..." class="w-full px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-xs text-white outline-none field-help-input">
                    </div>
                </div>
            `;
            container.appendChild(row);
            fieldIndex++;
            renumberFields();
        }

        function moveFieldUp(btn) {
            const row = btn.closest('.field-row');
            if (row && row.previousElementSibling) {
                row.parentNode.insertBefore(row, row.previousElementSibling);
                renumberFields();
            }
        }

        function moveFieldDown(btn) {
            const row = btn.closest('.field-row');
            if (row && row.nextElementSibling) {
                row.parentNode.insertBefore(row.nextElementSibling, row);
                renumberFields();
            }
        }

        function removeField(btn) {
            const row = btn.closest('.field-row');
            if (row) {
                row.remove();
                renumberFields();
            }
        }

        function renumberFields() {
            const container = document.getElementById('fieldsContainer');
            if (!container) return;
            const rows = container.querySelectorAll('.field-row');
            rows.forEach((row, idx) => {
                const badge = row.querySelector('.field-badge');
                if (badge) badge.innerText = idx + 1;

                const labelInput = row.querySelector('.field-label-input');
                if (labelInput) labelInput.name = `fields[${idx}][label]`;

                const typeSelect = row.querySelector('.field-type-select');
                if (typeSelect) typeSelect.name = `fields[${idx}][type]`;

                const optionsInput = row.querySelector('.options-input');
                if (optionsInput) optionsInput.name = `fields[${idx}][options]`;

                const helpInput = row.querySelector('.field-help-input');
                if (helpInput) helpInput.name = `fields[${idx}][help_text]`;

                const upBtn = row.querySelector('.btn-move-up');
                const downBtn = row.querySelector('.btn-move-down');
                if (upBtn) {
                    upBtn.disabled = idx === 0;
                    upBtn.classList.toggle('opacity-30', idx === 0);
                    upBtn.classList.toggle('cursor-not-allowed', idx === 0);
                }
                if (downBtn) {
                    downBtn.disabled = idx === rows.length - 1;
                    downBtn.classList.toggle('opacity-30', idx === rows.length - 1);
                    downBtn.classList.toggle('cursor-not-allowed', idx === rows.length - 1);
                }
            });
        }

        // ==========================================
        // PREVIEW & CLONING HELPERS
        // ==========================================
        function openStdPreviewModal(templateId) {
            const tmpl = stdTemplatesData.find(t => t.id === templateId);
            if (!tmpl) return;
            const fields = stdFieldsData[templateId] || [];

            document.getElementById('preview-category').innerText = tmpl.category || 'General';
            document.getElementById('preview-type').innerText = (tmpl.type || 'QC_CHECKLIST').replace('_', ' ');
            document.getElementById('preview-title').innerText = tmpl.title;
            document.getElementById('preview-description').innerText = tmpl.description || 'Standard quality control template.';
            document.getElementById('preview-count').innerText = fields.length + ' Configured Questions & Fields';
            document.getElementById('modal-search-input').value = '';

            const cloneBtn = document.getElementById('preview-modal-clone-btn');
            cloneBtn.onclick = function() {
                closeStdPreviewModal();
                cloneStdTemplate(templateId);
            };

            const container = document.getElementById('preview-fields-list');
            container.innerHTML = '';

            if (fields.length === 0) {
                container.innerHTML = '<div class="text-center py-8 text-slate-400 text-xs">No questions configured for this template.</div>';
            } else {
                fields.forEach((f, idx) => {
                    const fieldEl = document.createElement('div');
                    fieldEl.className = 'modal-field-item pt-3 first:pt-0 space-y-1.5';
                    
                    let optsText = '';
                    if (f.options_json) {
                        try {
                            const parsed = JSON.parse(f.options_json);
                            if (Array.isArray(parsed)) optsText = parsed.join(', ');
                        } catch(e) {
                            optsText = f.options_json;
                        }
                    }

                    fieldEl.innerHTML = `
                        <div class="flex items-center justify-between gap-2">
                            <span class="text-xs font-bold text-white">${idx + 1}. ${f.field_label}</span>
                            <span class="text-[10px] font-mono px-2 py-0.5 rounded bg-slate-800 text-indigo-300 border border-slate-700">${(f.field_type || 'TEXT').replace('_', ' ')}</span>
                        </div>
                        ${optsText ? `<div class="text-[11px] text-emerald-400 font-mono bg-slate-950/60 p-2 rounded-lg border border-slate-800/80">Options: ${optsText}</div>` : ''}
                        ${f.help_text ? `<div class="text-[11px] text-slate-400 italic">${f.help_text}</div>` : ''}
                    `;
                    container.appendChild(fieldEl);
                });
            }

            document.getElementById('std-preview-modal').classList.remove('hidden');
        }

        function closeStdPreviewModal() {
            document.getElementById('std-preview-modal').classList.add('hidden');
        }

        function filterModalQuestions() {
            const query = (document.getElementById('modal-search-input').value || '').toLowerCase();
            const items = document.querySelectorAll('.modal-field-item');
            items.forEach(item => {
                const match = item.innerText.toLowerCase().includes(query);
                item.style.display = match ? 'block' : 'none';
            });
        }

        function cloneStdTemplate(templateId) {
            const tmpl = stdTemplatesData.find(t => t.id === templateId);
            if (!tmpl) return;
            const fields = stdFieldsData[templateId] || [];

            // Populate form metadata
            document.getElementById('form-title').value = tmpl.title + ' (Copy)';
            document.getElementById('form-category').value = tmpl.category || 'General';
            document.getElementById('form-type').value = tmpl.type || 'QC_CHECKLIST';
            document.getElementById('form-description').value = tmpl.description || '';

            // Clear existing fields
            const container = document.getElementById('fieldsContainer');
            container.innerHTML = '';
            fieldIndex = 0;

            // Add each field into the builder
            fields.forEach(f => {
                let options = '';
                if (f.options_json) {
                    try {
                        const parsed = JSON.parse(f.options_json);
                        if (Array.isArray(parsed)) options = parsed.join(', ');
                        else options = String(f.options_json);
                    } catch(e) {
                        options = String(f.options_json);
                    }
                }
                addField(f.field_type || 'SINGLE_CHOICE', f.field_label || '', options, f.help_text || '');
            });

            // Scroll up to the designer smoothly
            document.getElementById('templateForm').scrollIntoView({ behavior: 'smooth' });
        }

        function setStdCategory(cat) {
            activeCategory = cat;
            document.querySelectorAll('.std-cat-btn').forEach(btn => {
                if (btn.getAttribute('data-cat') === cat) {
                    btn.className = 'std-cat-btn px-3 py-1 rounded-xl bg-indigo-600 text-white font-bold transition-all';
                } else {
                    btn.className = 'std-cat-btn px-3 py-1 rounded-xl bg-slate-800 text-slate-300 font-medium hover:bg-slate-700 transition-all';
                }
            });
            filterStdList();
        }

        function filterStdList() {
            const query = (document.getElementById('std-search-input').value || '').toLowerCase();
            const cards = document.querySelectorAll('.std-card');
            cards.forEach(card => {
                const cardCat = card.getAttribute('data-category');
                const cardTitle = card.getAttribute('data-title');
                const matchesCat = activeCategory === 'ALL' || cardCat === activeCategory;
                const matchesQuery = cardTitle.includes(query) || cardCat.toLowerCase().includes(query);
                card.style.display = (matchesCat && matchesQuery) ? 'flex' : 'none';
            });
        }

        // Initialize with default standard QC items if starting blank
        window.addEventListener('DOMContentLoaded', () => {
            addField('SINGLE_CHOICE', 'Site preparation & substrate cleanliness verified', 'Pass, Fail, N/A', 'Check substrate for dust, grease, or standing water.');
            addField('PHOTO_UPLOAD', 'Pre-Installation Substrate Verification Photo', '', 'Upload clear photo of prepped area.');
            addField('SIGNATURE', 'Quality Assurance Inspector Sign-Off', '', 'Digital sign-off acknowledging QA check.');
        });
    </script>

</body>
</html>