<?php

declare(strict_types=1);

namespace PpPhp\Core;

class BaseProjectController
{
    protected function requireProjectAuth(string $slug, Config $config): ?array
    {
        if (session_status() === PHP_SESSION_NONE) {
            // Match the generated apps: httponly + SameSite always, secure only
            // when the request really is HTTPS (otherwise the cookie is dropped).
            $https = (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off')
                || ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443)
                || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
            session_set_cookie_params([
                'lifetime' => 0, 'path' => '/', 'httponly' => true, 'samesite' => 'Lax', 'secure' => $https,
            ]);
            session_start();
        }
        if (!isset($_SESSION['user'])) {
            $this->redirect($config->get('base_url') . '/login');
            return null;
        }

        $dbConfig = $config->get('db_config');
        $dsn = "mysql:host={$dbConfig->get('host')};port={$dbConfig->get('port')};dbname={$dbConfig->get('dbname')};charset=utf8mb4";
        $pdo = new \PDO($dsn, $dbConfig->get('user'), $dbConfig->get('pass'), [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        ]);

        $stmt = $pdo->prepare('SELECT * FROM projects WHERE slug = ? AND created_by = ?');
        $stmt->execute([$slug, $_SESSION['user']['id']]);
        $project = $stmt->fetch();

        if (!$project && $_SESSION['user']['role'] === 'superadmin') {
            $stmt = $pdo->prepare('SELECT * FROM projects WHERE slug = ?');
            $stmt->execute([$slug]);
            $project = $stmt->fetch();
        }

        if (!$project) {
            http_response_code(404);
            echo 'Project not found.';
            exit;
        }

        return $project;
    }

    protected function renderShell(string $slug, array $project, array $navItems, string $innerContent, Config $config): string
    {
        $baseUrl = $config->get('base_url');
        $assetsUrl = $config->get('assets_url');
        $user = $_SESSION['user'];

        ob_start();
        // Include the workspace shell view that expects these variables
        include __DIR__ . '/../modules/ProjectWorkspace/Views/shell.php';
        return ob_get_clean();
    }

    private function redirect(string $url): void
    {
        header('Location: ' . $url);
        exit;
    }
}