<?php
// data_hybrid/r_in_jupyter.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php';
require_once '../includes/jupyter_helpers.php';

redirect_if_not_role('Data Contributor');

$hasRJupyterAccess = has_r_access();
$workspaceSync = ['synced' => [], 'missing' => [], 'workspace_dir' => null];
$workspaceRelativeDir = null;
$workspaceError = null;

if ($hasRJupyterAccess && isset($_SESSION['person_id'])) {
    $dataSourceManager = new DataSource($pdo);
    try {
        $workspaceSync = $dataSourceManager->prepareJupyterWorkspace(
            (int) $_SESSION['person_id'],
            dirname(__DIR__) . '/uploads/jupyter_workspace'
        );
        $workspaceRelativeDir = 'datasources/user_' . (int) $_SESSION['person_id'];
    } catch (Exception $e) {
        $workspaceError = $e->getMessage();
    }
}

$jupyterBaseUrl = dsp_jupyter_base_url();
$jupyterToken = dsp_jupyter_token();
$jupyterIframeUrl = dsp_jupyter_iframe_url(
    $jupyterBaseUrl,
    $jupyterToken,
    isset($_SESSION['person_id']) ? (int) $_SESSION['person_id'] : null
);
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once("../includes/header_contributor.php"); ?>
<body>
    <div class="wrapper">
        <?php include_once("../includes/nav_contributor.php"); ?>

        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">R in JupyterHub</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php if (isset($_SESSION['message'])): ?>
                <div class="alert alert-<?= $_SESSION['message_type'] ?> alert-dismissible fade show rounded" role="alert">
                    <?= $_SESSION['message'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php
                unset($_SESSION['message'], $_SESSION['message_type']);
                ?>
            <?php endif; ?>

            <div class="card shadow-sm rounded mb-4">
                <div class="card-header bg-light rounded-top d-flex align-items-center justify-content-between">
                    <h5 class="mb-0">Collaborative R Workspace</h5>
                    <?php if ($hasRJupyterAccess): ?>
                        <span class="badge bg-success-subtle text-success rounded-pill"><i class="fas fa-flask me-1"></i> Enabled</span>
                    <?php else: ?>
                        <span class="badge bg-warning-subtle text-warning rounded-pill"><i class="fas fa-lock me-1"></i> Disabled</span>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <?php if ($hasRJupyterAccess): ?>
                        <?php if ($workspaceError): ?>
                            <div class="alert alert-danger rounded mb-3">
                                <strong>Workspace error:</strong> <?= htmlspecialchars($workspaceError) ?>
                            </div>
                        <?php else: ?>
                            <p class="mb-3">
                                Only Approved data sources are copied into
                                <code><?= htmlspecialchars($workspaceRelativeDir ?: 'datasources') ?></code>
                                inside Jupyter. Use these files when collaborating with Data Owners.
                            </p>
                            <?php if (!empty($workspaceSync['synced'])): ?>
                                <div class="table-responsive mb-3">
                                    <table class="table table-sm table-striped align-middle">
                                        <thead class="table-light">
                                            <tr>
                                                <th>#</th>
                                                <th>Data Source</th>
                                                <th>Data Type</th>
                                                <th>Category</th>
                                                <th>Filename</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($workspaceSync['synced'] as $idx => $syncedItem): ?>
                                                <tr>
                                                    <td><?= $idx + 1 ?></td>
                                                    <td><?= htmlspecialchars($syncedItem['title']) ?></td>
                                                    <td><?= htmlspecialchars($syncedItem['data_type'] ?? 'N/A') ?></td>
                                                    <td><?= htmlspecialchars($syncedItem['category'] ?? 'N/A') ?></td>
                                                    <td><code><?= htmlspecialchars(basename($syncedItem['relative_path'])) ?></code></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-info rounded mb-3">
                                    You do not have any Approved data sources yet. Once your requests are approved, refresh this page.
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($workspaceSync['missing'])): ?>
                                <div class="alert alert-warning rounded mb-3">
                                    <strong>Some items were skipped:</strong>
                                    <ul class="mb-0">
                                        <?php foreach ($workspaceSync['missing'] as $missingItem): ?>
                                            <li><?= htmlspecialchars($missingItem['title']) ?> — <?= htmlspecialchars($missingItem['reason']) ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                        <p class="mb-3">
                            Launch the embedded JupyterLab environment to build notebooks, explore shared datasets, and collaborate with Data Owners.
                            Use the <em>Files</em> panel to open existing work or create a new R Notebook from the launcher.
                        </p>
                        <div class="ratio ratio-16x9 border rounded overflow-hidden">
                            <iframe
                                src="<?= htmlspecialchars($jupyterIframeUrl, ENT_QUOTES, 'UTF-8') ?>"
                                title="R in JupyterHub"
                                allowfullscreen
                                loading="lazy"
                                referrerpolicy="no-referrer"
                            ></iframe>
                        </div>
                        <p class="mt-3 mb-0">
                            Prefer a dedicated window? <a href="<?= htmlspecialchars($jupyterIframeUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Open Jupyter in a new tab</a>.
                        </p>
                    <?php else: ?>
                        <div class="alert alert-warning rounded d-flex align-items-start gap-3">
                            <i class="fas fa-circle-info mt-1"></i>
                            <div>
                                <strong>R in JupyterHub is currently disabled for your account.</strong><br>
                                Contact a DAC Staff administrator to enable R/Jupyter access so you can analyse data directly from this workspace.
                            </div>
                        </div>
                        <p class="mb-0">
                            Once access is enabled, refresh this page to launch the JupyterLab environment.
                        </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php include_once("../includes/footer_contributor.php"); ?>
</body>
</html>
