<?php

declare(strict_types=1);
/* Variables: $baseUrl, $assetsUrl, $project, $user, $navItems, $pageTitle, $bootJson */
?>
<!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') ?> - Deploy</title>

    <?php include constant('BASE_PATH') . '/core/views/project-head.php'; ?>

    <?= \PpPhp\Core\ModuleAssets::style('Deploy', 'Views/styles.css') ?>
    <?= \PpPhp\Core\ModuleAssets::style('Deploy', 'Views/deploy-app-theme.css', '', 'deployAppThemeCss') ?>
</head>

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

    <div id="mainArea" class="main-area">
        <div class="right-workspace w-100">
            <div class="ftp-app" id="ftpApp">

                <!-- ═══════════ Connection bar ═══════════ -->
                <div class="ftp-connbar">
                    <div class="cb-brand" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="<?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> FTP / SFTP client"><i class="bi bi-hdd-network-fill"></i></div>
                    <div class="cb-field">
                        <label>Server</label>
                        <select id="connSelect" class="cb-select" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Choose a saved server connection">
                            <option value="0">— No connection —</option>
                        </select>
                    </div>
                    <div class="cb-status" id="connStatus" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Live connection status">
                        <span class="dot dot-off" id="connDot"></span>
                        <span id="connStatusText">Disconnected</span>
                    </div>
                    <div class="cb-actions">
                        <div class="cb-btngroup">
                            <button class="btn btn-sm btn-outline-light" id="btnNewConn" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Add a new server connection"><i class="bi bi-plus-lg"></i><span>New</span></button>
                            <button class="btn btn-sm btn-outline-light" id="btnEditConn" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Edit the selected connection"><i class="bi bi-pencil"></i><span>Edit</span></button>
                            <button class="btn btn-sm btn-outline-light" id="btnDelConn" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Delete the selected connection"><i class="bi bi-trash"></i></button>
                            <button class="btn btn-sm btn-outline-light" id="btnTestConn" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Run a step-by-step connection test"><i class="bi bi-plug"></i><span>Test</span></button>
                        </div>
                        <button class="btn btn-sm btn-success" id="btnConnect" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Connect and browse the live server"><i class="bi bi-lightning-charge-fill"></i><span>Connect</span></button>
                        <button class="btn btn-sm btn-outline-light pp-guide-trigger" type="button" data-dep-help-open data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Open the Deploy guide — how to connect and publish safely" aria-label="Open Deploy guide"><i class="bi bi-question-circle-fill" aria-hidden="true"></i><span>Guide</span></button>
                    </div>
                </div>

                <!-- ═══════════ Upload toolbar ═══════════ -->
                <div class="ftp-uploadbar">
                    <div class="ub-group">
                        <span class="ub-label">Files</span>
                        <div class="segmented" id="modeSeg">
                            <button data-mode="changed" class="seg active" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Upload only files changed since the last upload to this server">Changed only</button>
                            <button data-mode="all-project" class="seg" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Upload the generated application (excludes local-only folders like .git and node_modules)">All project</button>
                            <button data-mode="all-output" class="seg" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Upload every file in the output folder, exactly as on disk">All output</button>
                        </div>
                    </div>
                    <div class="ub-sep"></div>
                    <div class="ub-group">
                        <span class="ub-label"><i class="bi bi-database"></i> Live DB</span>
                        <select id="dbConnectionSelect" class="ub-select" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Database written into the uploaded app's config — never your local project">
                            <option value="__keep__">Keep build settings</option>
                        </select>
                        <button class="pane-btn" id="btnManageDb" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Add, edit or delete live database connections"><i class="bi bi-gear"></i></button>
                    </div>
                    <div class="ub-sep"></div>
                    <div class="ub-group form-check form-switch mb-0" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Open the deployed site in your browser after a successful upload">
                        <input class="form-check-input" type="checkbox" id="openInBrowser" checked>
                        <label class="form-check-label small" for="openInBrowser">Open after</label>
                    </div>
                    <div class="ub-spacer"></div>
                    <button class="btn btn-sm btn-outline-secondary" id="btnDryRun" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Preview which files would upload — without connecting or changing anything"><i class="bi bi-search me-1"></i>Dry run</button>
                    <button class="btn btn-sm btn-primary btn-upload" id="btnUpload" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Upload the selected files to the connected server now"><i class="bi bi-cloud-arrow-up-fill me-1"></i>Upload to Server</button>
                </div>

                <!-- ═══════════ Dual-pane explorer ═══════════ -->
                <div class="ftp-panes">
                    <!-- Local -->
                    <section class="pane" id="localPane">
                        <header class="pane-head">
                            <i class="bi bi-pc-display"></i>
                            <span class="pane-title">Local site</span>
                            <span class="pane-sub" id="localRootLabel"></span>
                            <button class="pane-btn ms-auto" id="btnLocalRefresh" title="Refresh"><i class="bi bi-arrow-clockwise"></i></button>
                        </header>
                        <div class="crumbs" id="localCrumbs"></div>
                        <div class="filelist" id="localList"></div>
                    </section>

                    <div class="pane-divider"><i class="bi bi-arrow-right"></i></div>

                    <!-- Remote -->
                    <section class="pane" id="remotePane">
                        <header class="pane-head">
                            <i class="bi bi-hdd-network"></i>
                            <span class="pane-title">Remote site</span>
                            <span class="pane-sub" id="remoteHostLabel"></span>
                            <div class="ms-auto d-flex gap-1">
                                <button class="pane-btn" id="btnRemoteUp" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Go up one folder"><i class="bi bi-arrow-90deg-up"></i></button>
                                <button class="pane-btn" id="btnRemoteMkdir" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Create a new folder here"><i class="bi bi-folder-plus"></i></button>
                                <button class="pane-btn" id="btnRemoteSetTarget" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Use this folder as the upload target for this connection"><i class="bi bi-bullseye"></i></button>
                                <button class="pane-btn" id="btnRemoteRefresh" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Refresh the remote listing"><i class="bi bi-arrow-clockwise"></i></button>
                            </div>
                        </header>
                        <div class="crumbs" id="remoteCrumbs"></div>
                        <div class="filelist" id="remoteList">
                            <div class="pane-empty" id="remoteEmpty">
                                <i class="bi bi-hdd-network"></i>
                                <p>Not connected</p>
                                <span>Pick a server and press <strong>Connect</strong> to browse the live files.</span>
                            </div>
                        </div>
                    </section>
                </div>

                <!-- ═══════════ Bottom dock ═══════════ -->
                <div class="ftp-dock">
                    <div class="dock-tabs">
                        <button class="dock-tab active" data-tab="log"><i class="bi bi-list-task me-1"></i>Transfer log</button>
                        <button class="dock-tab" data-tab="history"><i class="bi bi-clock-history me-1"></i>History <span class="tab-badge" id="histBadge"></span></button>
                        <button class="dock-tab" data-tab="diag"><i class="bi bi-clipboard-pulse me-1"></i>Diagnostics</button>
                        <div class="ms-auto dock-stats" id="dockStats"></div>
                    </div>
                    <div class="progress dock-progress d-none" id="uploadProgressWrap"><div class="progress-bar progress-bar-striped progress-bar-animated" id="uploadProgress"></div></div>
                    <div class="dock-body">
                        <div class="dock-panel active" id="tab-log">
                            <div id="transferLog" class="transfer-log"><div class="dock-hint">Transfers will appear here.</div></div>
                        </div>
                        <div class="dock-panel" id="tab-history">
                            <table class="hist-table"><tbody id="historyBody"></tbody></table>
                            <div class="dock-hint" id="historyEmpty">No deployments recorded yet.</div>
                        </div>
                        <div class="dock-panel" id="tab-diag">
                            <div id="diagBody"><div class="dock-hint">Run <strong>Test</strong> to probe the connection step by step.</div></div>
                        </div>
                    </div>
                </div>

                <!-- ═══════════ Status bar ═══════════ -->
                <div class="ftp-statusbar">
                    <span id="statusMain"><i class="bi bi-circle-fill text-secondary me-1"></i>Ready</span>
                    <span class="ms-auto" id="statusRight"></span>
                </div>

            </div>
        </div>
    </div>

    <!-- ═══ Connection editor modal ═══ -->
    <div class="modal fade" id="connModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable conn-modal">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h6 class="modal-title fw-semibold"><i class="bi bi-hdd-network me-1"></i> <span id="connModalTitle">New connection</span></h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body cf">
                    <input type="hidden" id="pfId">
                    <div class="row g-2">
                        <div class="col-md-6">
                            <label class="form-label" for="pfName">Connection name</label>
                            <input type="text" class="form-control form-control-sm" id="pfName" placeholder="Production"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="A friendly name for this server, e.g. “Production” or “Staging”">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="pfProtocol">Protocol</label>
                            <select class="form-select form-select-sm" id="pfProtocol"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="FTP / FTPS (TLS) / SFTP (SSH). SFTP uses a single port and avoids passive-FTP firewall problems.">
                                <option value="ftp">FTP — File Transfer Protocol</option>
                                <option value="ftps">FTPS — FTP over explicit TLS</option>
                                <option value="sftp">SFTP — SSH File Transfer</option>
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label" for="pfHost">Host</label>
                            <input type="text" class="form-control form-control-sm" id="pfHost" placeholder="example.com"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Server hostname or IP. A bare domain works — the “ftp.” prefix is optional and tried automatically.">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label" for="pfPort">Port</label>
                            <input type="number" class="form-control form-control-sm" id="pfPort" placeholder="21"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="21 for FTP/FTPS, 22 for SFTP — filled in automatically when you pick a protocol.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="pfUser">Username</label>
                            <input type="text" class="form-control form-control-sm" id="pfUser" autocomplete="off" placeholder="username"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Login username. For SFTP on cPanel use the MAIN SSH account, not an “user@domain.com” FTP sub-account.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="pfPass">Password <span class="text-muted" id="pfPassHint"></span></label>
                            <div class="input-group input-group-sm">
                                <input type="password" class="form-control" id="pfPass" autocomplete="new-password" placeholder="password"
                                    data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="When editing, leave blank to keep the saved password. Stored encrypted.">
                                <button class="btn btn-outline-secondary" type="button" id="pfPassToggle" tabindex="-1"
                                    data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Show / hide the password"><i class="bi bi-eye"></i></button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="pfRemotePath">Remote path</label>
                            <input type="text" class="form-control form-control-sm" id="pfRemotePath" placeholder="/public_html/myapp"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Folder on the server to upload into. Tip: connect, then browse the remote pane and click the target icon to set this.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="pfSiteUrl">Site URL</label>
                            <input type="text" class="form-control form-control-sm" id="pfSiteUrl" placeholder="https://example.com/myapp"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Public URL of the deployed app — opened by “Open after” and the “Open now” button.">
                        </div>
                        <div class="col-12 pf-ftp-only">
                            <div class="form-check form-switch" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Recommended for FTP behind NAT/firewalls. Needs the server's passive port range open in its firewall.">
                                <input class="form-check-input" type="checkbox" id="pfPassive" checked>
                                <label class="form-check-label" for="pfPassive">Passive mode <span class="text-muted">(recommended behind firewalls)</span></label>
                            </div>
                        </div>
                        <div class="col-md-8 pf-sftp-only d-none">
                            <label class="form-label" for="pfKeyFile">Private key file <span class="text-muted">(optional)</span></label>
                            <input type="text" class="form-control form-control-sm" id="pfKeyFile" placeholder="/Users/me/.ssh/id_rsa"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Path to an SSH private key for key-based auth. Leave blank to use the password above.">
                        </div>
                        <div class="col-md-4 pf-sftp-only d-none">
                            <label class="form-label" for="pfKeyPass">Key passphrase</label>
                            <input type="password" class="form-control form-control-sm" id="pfKeyPass" autocomplete="new-password"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Passphrase protecting the private key, if it has one.">
                        </div>
                    </div>
                </div>
                <!-- Test + diagnostics: pinned above the footer so results never scroll away -->
                <div class="conn-testbar">
                    <button class="btn btn-sm btn-outline-info flex-shrink-0" id="btnTestInModal"
                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Probe this server step by step (DNS → port → login → data channel)"><i class="bi bi-plug me-1"></i> Test</button>
                    <span class="small" id="modalTestResult">Save or test the connection to verify it works.</span>
                </div>
                <div id="modalDiag" class="modal-diag"></div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSaveConn"
                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Save this connection (password stored encrypted)"><i class="bi bi-check-lg me-1"></i> Save connection</button>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ Live database connection manager modal ═══ -->
    <div class="modal fade" id="dbModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable conn-modal">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h6 class="modal-title fw-semibold"><i class="bi bi-database me-1"></i> Live database connections</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body cf">
                    <div class="cf-note">
                        <i class="bi bi-info-circle me-1"></i>
                        Written into <code>config/database.php</code> of the <strong>uploaded</strong> app so it talks to your production database — separate from your local dev database. Create one per live server.
                    </div>
                    <div class="mb-2">
                        <label class="form-label" for="dbmSelect">Saved live databases</label>
                        <select class="form-select form-select-sm" id="dbmSelect"
                            data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Pick a saved database to edit, or choose “New” to add one">
                            <option value="0">＋ New live database connection…</option>
                        </select>
                    </div>
                    <hr class="cf-hr">
                    <div class="row g-2">
                        <input type="hidden" id="dbmId">
                        <div class="col-md-6">
                            <label class="form-label" for="dbmName">Name</label>
                            <input type="text" class="form-control form-control-sm" id="dbmName" placeholder="Production DB"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="A label for this database, e.g. “Production DB”">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="dbmType">Driver</label>
                            <select class="form-select form-select-sm" id="dbmType"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="The database engine on the live server. Port auto-fills to match.">
                                <option value="mysql">MySQL / MariaDB</option>
                                <option value="pgsql">PostgreSQL</option>
                                <option value="sqlsrv">SQL Server</option>
                                <option value="sqlite">SQLite</option>
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label" for="dbmHost">Host</label>
                            <input type="text" class="form-control form-control-sm" id="dbmHost" placeholder="localhost"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Database host as seen FROM the live server — usually “localhost” on shared hosting, or a private DB host.">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label" for="dbmPort">Port</label>
                            <input type="text" class="form-control form-control-sm" id="dbmPort" placeholder="3306"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="3306 MySQL · 5432 PostgreSQL · 1433 SQL Server — auto-filled by driver.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="dbmDbname">Database name</label>
                            <input type="text" class="form-control form-control-sm" id="dbmDbname" placeholder="live_app_db"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Name of the production database (for SQLite, the file path).">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="dbmCharset">Charset</label>
                            <input type="text" class="form-control form-control-sm" id="dbmCharset" placeholder="utf8mb4"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Character set — utf8mb4 is recommended for MySQL/MariaDB.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="dbmUser">Username</label>
                            <input type="text" class="form-control form-control-sm" id="dbmUser" autocomplete="off" placeholder="db_user"
                                data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Database user with access to the production database.">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="dbmPass">Password <span class="text-muted" id="dbmPassHint"></span></label>
                            <div class="input-group input-group-sm">
                                <input type="password" class="form-control" id="dbmPass" autocomplete="new-password"
                                    data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="When editing, leave blank to keep the saved password. Stored encrypted.">
                                <button class="btn btn-outline-secondary" type="button" id="dbmPassToggle" tabindex="-1"
                                    data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Show / hide the password"><i class="bi bi-eye"></i></button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Pinned test bar so the result never scrolls away -->
                <div class="conn-testbar">
                    <button class="btn btn-sm btn-outline-info flex-shrink-0" id="btnDbTest"
                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Try connecting to this database with PDO (runs from this machine)"><i class="bi bi-plug me-1"></i> Test</button>
                    <span class="small" id="dbmTestResult">Test the connection before saving.</span>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-sm btn-outline-danger me-auto d-none" id="btnDbDelete"
                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Delete this saved database connection"><i class="bi bi-trash me-1"></i> Delete</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnDbSave"
                        data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Save this database (password stored encrypted)"><i class="bi bi-check-lg me-1"></i> Save database</button>
                </div>
            </div>
        </div>
    </div>

    <div id="actionFeedback"></div>

    <!-- in-app Guide (self-contained partial) -->
    <?php include __DIR__ . '/partials/help.php'; ?>

    <?php include constant('BASE_PATH') . '/core/views/project-scripts.php'; ?>

    <script>
        const projectSlug = <?= json_encode($project['slug'] ?? '') ?>;
        const baseUrl     = <?= json_encode($baseUrl) ?>;
        const boot        = <?= $bootJson ?>;
    </script>

    <?= \PpPhp\Core\ModuleAssets::script('Deploy', 'Views/scripts/core.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Deploy', 'Views/scripts/browser.js') ?>
    <?= \PpPhp\Core\ModuleAssets::script('Deploy', 'Views/scripts/init.js') ?>
</body>

</html>
