<?php

declare(strict_types=1);
/* Variables: $baseUrl, $assetsUrl, $project, $user, $navItems, $tables, $savedQueries, $pageTitle */
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title><?= htmlspecialchars($project['name'] ?? 'Project') ?> - Query</title>

    <?php include constant('BASE_PATH') . '/core/views/project-head.php'; ?>
    <link rel="stylesheet" href="<?= htmlspecialchars($assetsUrl) ?>/css/module-guide.css?v=<?= (int) @filemtime(constant('BASE_PATH') . '/public/assets/css/module-guide.css') ?>">

    <?= \PpPhp\Core\ModuleAssets::style('Query', 'Views/styles.css') ?>

    <?php
    // Bundled CodeMirror for the SQL editor (schema-aware autocomplete). Cache-bust
    // off both bundle files' mtime+size so editing either forces a fresh download.
    $cmVer = '';
    foreach (['js', 'css'] as $__ext) {
        foreach ([constant('BASE_PATH') . "/public/assets/codemirror/codemirror.bundle.$__ext", constant('BASE_PATH') . "/assets/codemirror/codemirror.bundle.$__ext"] as $__cm) {
            if (is_file($__cm)) { $cmVer .= filemtime($__cm) . '-' . filesize($__cm) . '.'; break; }
        }
    }
    $cmVer = $cmVer !== '' ? rtrim($cmVer, '.') : '1';
    ?>
    <link href="<?= htmlspecialchars($assetsUrl) ?>/codemirror/codemirror.bundle.css?v=<?= htmlspecialchars($cmVer) ?>" rel="stylesheet">
    <script src="<?= htmlspecialchars($assetsUrl) ?>/codemirror/codemirror.bundle.js?v=<?= htmlspecialchars($cmVer) ?>"></script>
</head>

<body class="query-module">
    <?php include __DIR__ . '/partials/shell.php'; ?>

    <div id="mainArea" class="main-area">
        <!-- Left panel: tables + saved queries -->
        <div class="left-panel">
            <div class="panel-header">Tables</div>
            <div class="query-table-tools">
                <label class="visually-hidden" for="queryTableSearch">Search tables</label>
                <i class="bi bi-search" aria-hidden="true"></i>
                <input type="search" id="queryTableSearch" placeholder="Search tables…" autocomplete="off">
                <span id="queryTableCount" class="query-table-count"><?= count($tables) ?></span>
            </div>
            <ul class="table-list" id="queryTableList">
                <?php foreach ($tables as $t): ?>
                    <li data-table="<?= htmlspecialchars($t['name']) ?>" draggable="true">
                        <i class="bi bi-<?= $t['type'] === 'VIEW' ? 'eye' : 'table' ?> me-1"></i>
                        <span><?= htmlspecialchars($t['name']) ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
            <div id="queryTableSearchEmpty" class="query-table-empty" hidden>No matching tables</div>
            <section class="saved-queries-dock" aria-labelledby="savedQueriesToggle">
                <button type="button" class="saved-queries-toggle" id="savedQueriesToggle" aria-expanded="false" aria-controls="savedQueriesPanel">
                    <span><i class="bi bi-bookmark-star me-2" aria-hidden="true"></i>Saved Queries</span>
                    <span class="saved-queries-meta"><span class="saved-query-count"><?= count($savedQueries) ?></span><i class="bi bi-chevron-up saved-queries-chevron" aria-hidden="true"></i></span>
                </button>
                <div class="saved-queries-panel" id="savedQueriesPanel" hidden>
                    <ul class="saved-queries-list" id="savedQueriesList">
                        <?php foreach ($savedQueries as $q): ?>
                            <li data-query="<?= htmlspecialchars($q['name']) ?>" style="display:flex; align-items:center; justify-content:space-between;">
                                <span style="flex:1; cursor:pointer;"><?= htmlspecialchars($q['name']) ?></span>
                                <span class="delete-query-btn text-danger" data-query="<?= htmlspecialchars($q['name']) ?>" style="cursor:pointer; margin-left:0.5rem;" title="Delete query"><i class="bi bi-trash"></i></span>
                            </li>
                        <?php endforeach; ?>
                        <?php if ($savedQueries === []): ?>
                            <li class="saved-query-empty"><span>No saved queries yet</span></li>
                        <?php endif; ?>
                    </ul>
                </div>
            </section>
        </div>

        <!-- Right workspace: tabs -->
        <div class="right-workspace">
            <div class="workspace-content" id="queryWorkspace">
                <!-- Tab navigation and query actions share one compact row. -->
                <div class="query-tabbar">
                    <ul class="nav nav-tabs small" id="queryTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="designer-tab" data-bs-toggle="tab" data-bs-target="#designerPane" data-bs-custom-class="query-tooltip" type="button" role="tab" title="Build the query visually by selecting fields, joins, sorting, grouping, and criteria.">Designer</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="sql-tab" data-bs-toggle="tab" data-bs-target="#sqlPane" data-bs-custom-class="query-tooltip" type="button" role="tab" title="Review or edit the SQL generated by the visual query designer.">SQL</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="results-tab" data-bs-toggle="tab" data-bs-target="#resultsPane" data-bs-custom-class="query-tooltip" type="button" role="tab" title="Preview the rows returned by the current query.">Results</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="where-tab" data-bs-toggle="tab" data-bs-target="#wherePane" data-bs-custom-class="query-tooltip" type="button" role="tab" title="Create reusable, named WHERE-condition variants for this query.">Additional WHERE</button>
                        </li>
                    </ul>
                    <div class="query-tab-actions">
                        <button type="button" class="pp-guide-trigger" data-bs-toggle="modal" data-bs-target="#queryGuideModal" title="Open the complete Query module guide" aria-label="Open the Query module guide">
                            <i class="bi bi-question-circle"></i><span class="d-none d-sm-inline">Guide</span>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary d-md-none" id="btnToggleQueryList" data-bs-custom-class="query-tooltip" title="Show or hide the Tables sidebar.">
                            <i class="bi bi-list"></i><span class="d-none d-sm-inline"> Tables</span>
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" id="btnSaveAsView" data-bs-custom-class="query-tooltip" title="Create a database VIEW from the current SQL (usable as a table in other modules)."><i class="bi bi-eye me-1"></i> Save as View</button>
                        <button class="btn btn-sm btn-outline-primary" id="btnSaveQuery" data-bs-custom-class="query-tooltip" title="Save the current query under a reusable name."><i class="bi bi-save me-1"></i> Save As…</button>
                    </div>
                </div>

                <!-- Tab panes -->
                <div class="tab-content mt-2" id="queryTabContent">
                    <div class="tab-pane fade show active" id="designerPane" role="tabpanel">
                        <?php include __DIR__ . '/partials/designer_tab.php'; ?>
                    </div>
                    <div class="tab-pane fade" id="sqlPane" role="tabpanel">
                        <?php include __DIR__ . '/partials/sql_tab.php'; ?>
                    </div>
                    <div class="tab-pane fade" id="resultsPane" role="tabpanel">
                        <?php include __DIR__ . '/partials/results_tab.php'; ?>
                    </div>
                    <div class="tab-pane fade" id="wherePane" role="tabpanel">
                        <?php include __DIR__ . '/partials/where_tabs.php'; ?>
                    </div>
                </div>

                <?php include __DIR__ . '/partials/join_modal.php'; ?>
                <?php include __DIR__ . '/partials/save_query_modal.php'; ?>
            </div>
        </div>
    </div>
    <?php include __DIR__ . '/partials/guide.php'; ?>


    <!-- PHP data passed to JavaScript -->
    <script>
        const projectSlug = <?= json_encode($project['slug'] ?? '') ?>;
        const baseUrl = <?= json_encode($baseUrl) ?>;
        const dbTables = <?= json_encode($tables) ?>;
        const tablePresets = <?= json_encode($tablePresets ?: new stdClass()) ?>;
        // Only assign – do NOT use 'let' or 'const' again
        currentTableName = <?= json_encode($currentTableName) ?>;
    </script>

    <?php include constant('BASE_PATH') . '/core/views/project-scripts.php'; ?>
    <script src="<?= htmlspecialchars($assetsUrl) ?>/js/module-guide.js"></script>


    <!-- Modular Query scripts (order matters) -->
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/core.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/diagram.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/designer.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/results.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/where.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/loadSave.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/sqlEnhance.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Query', 'Views/scripts/init.js') ?>



</body>

</html>
