<?php
// data_owner/run_r_scripts.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php';
require_once '../includes/jupyter_helpers.php';
// Ensure only Data Owners can access this page
redirect_if_not_role('Data Owner');

// Build the Jupyter URL for the iframe. Default to localhost access with the dev token.
$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
);
$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();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_owner.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_owner.php");
        ?>

        <!-- Page Content -->
        <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>

            <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">Work with R inside JupyterLab</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">
                                Approved data sources you manage or have access to are synced to
                                <code><?= htmlspecialchars($workspaceRelativeDir ?: 'datasources') ?></code> inside Jupyter.
                                Only datasets with Approved permissions appear here.
                            </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 currently have any Approved data sources. Approve requests in the permissions panel to make them available here.
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($workspaceSync['missing'])): ?>
                                <div class="alert alert-warning rounded mb-3">
                                    <strong>Some files 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 Jupyter environment below to build, run, and share your R notebooks. Use the
                            toolbar menu inside Jupyter to create new R notebooks and access saved work under <em>Files</em>.
                        </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">
                            Need more room? <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 datasets directly from this workspace.
                            </div>
                        </div>
                        <p class="mb-0">
                            After your access is approved, refresh this page to launch the embedded notebook environment.
                        </p>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
<!-- Footer -->
<?php
// Include Footer file for owner pages
include_once("../includes/footer_owner.php");
?>   
</body>
</html>
