<?php

namespace App\Http\Controllers\Admin\Grapesjs;

use App\Models\Page;
use App\Models\PageVersion;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class PageStorageController extends Controller
{
    public function load(Page $page)
    {
        return response()->json([
            'data' => $page->gjs_source,
        ]);
    }

    public function store(Request $request, Page $page)
    {

        $validated = $request->validate([
            'gjs_html'       => 'nullable',
            'gjs_css'        => 'nullable',
            'gjs_js'         => 'nullable',
            'gjs_source'     => 'nullable',
        ]);

        $page->update([
            'content'         => $validated['gjs_html'] ?? '',
            'css'             => $validated['gjs_css'] ?? '',
            'js'              => $validated['gjs_js'] ?? '',
            'gjs_source'      => $validated['gjs_source'] ?? '[]',
        ]);

        return response()->noContent();
    }

    // Helper methods for extracting data from project JSON
    private function extractHtmlFromComponents($component)
    {
        if (empty($component)) return '';

        // Simple HTML extraction - you might need a more sophisticated approach
        if (isset($component['components'])) {
            return $this->componentsToHtml($component['components']);
        }

        return '';
    }

    private function componentsToHtml($components)
    {
        $html = '';
        foreach ($components as $component) {
            if (isset($component['tagName'])) {
                $html .= "<{$component['tagName']}";
                if (isset($component['classes'])) {
                    $html .= ' class="' . implode(' ', $component['classes']) . '"';
                }
                $html .= '>';

                if (isset($component['components'])) {
                    $html .= $this->componentsToHtml($component['components']);
                } elseif (isset($component['content'])) {
                    $html .= htmlspecialchars($component['content']);
                }

                $html .= "</{$component['tagName']}>";
            }
        }
        return $html;
    }

    private function generateCssFromStyles($styles)
    {
        if (empty($styles)) return '';

        $css = '';
        foreach ($styles as $style) {
            if (isset($style['css'])) {
                $css .= $style['css'] . "\n";
            }
        }
        return $css;
    }
}
