<?php

declare(strict_types=1);

namespace PpPhp\Modules\Designer\Controllers;

use Throwable;
use PpPhp\Core\Config;
use PpPhp\Core\DB;
use PpPhp\Core\ModuleManager;
use PpPhp\Core\Security;
use PpPhp\Core\Designer\Layouts\LayoutFactory;

/**
 * Handles Designer layout insertion requests.
 *
 * This controller intentionally follows PPphp's existing controller style:
 * - no external Request object
 * - no framework JsonResponse dependency
 * - echoes JSON directly
 */
final class DesignerLayoutController
{
    public function __construct(
        private Config $config,
        private ModuleManager $moduleManager
    ) {}

    public function create(string $slug): void
    {
        header('Content-Type: application/json');

        try {
            $this->initProject($slug);

            $input = json_decode(file_get_contents('php://input'), true);
            if (!is_array($input)) {
                $input = $_POST;
            }

            $layoutId = trim((string)($input['layout'] ?? ''));

            if ($layoutId === '') {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Layout id is required.',
                ]);
                return;
            }

            $components = LayoutFactory::make($layoutId);

            if (!is_array($components) || $components === []) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'message' => 'Layout not found or empty: ' . $layoutId,
                ]);
                return;
            }

            echo json_encode([
                'success' => true,
                'layout' => $layoutId,
                'components' => $components,
            ]);
        } catch (Throwable $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Layout request failed.',
                'error' => $e->getMessage(),
            ]);
        }
    }

    private function initProject(string $slug): void
    {
        Security::RequireAuth();

        DB::Init();

        $project = DB::Select('projects', [
            'slug' => $slug,
            'created_by' => Security::CurrentUserData()['id'] ?? null,
        ]);

        if (empty($project) && Security::IsAdmin()) {
            $project = DB::Select('projects', ['slug' => $slug]);
        }

        if (empty($project)) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'message' => 'Project not found.',
            ]);
            exit;
        }

        // Standalone projects have no project DB — applying a layout is pure
        // (LayoutFactory), so skip the connection instead of fataling on it.
        if (\PpPhp\Core\ProjectDatabaseProfile::isStandaloneSlug($slug)) {
            return;
        }
        DB::Init($slug);
        DB::SetConnection($slug);
    }
}
