<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\File;
use Lib\Site\MixmanifestLib;
use Rvsitebuilder\Core\Models\CoreSetting;

class SiteThemeController extends Controller
{
    public function getThemeStyle(Request $request)
    {
        $theme_color = $request->theme_color;
        $urlTheme = config('rvsitebuildercms.cdn').'/service/html/theme/css/'.$theme_color.'.css';
        $content = guzzle_get_contents($urlTheme);

        return response()->json([
          'theme_css' => $content,
      ], 200);
    }

    public function updateTheme(Request $request)
    {
        $fullwidth = $request->fullwidth;
        $theme_color = $request->theme_color;
        $content = isset($request->theme_css) ? $request->theme_css : '';

        if (false == is_dir(public_path('storage').'/myheader/theme/')) {
            mkdir(public_path('storage').'/myheader/theme/');
        }

        CoreSetting::updateOrCreate([
            'key' => 'theme_color',
        ], [
            'value' => $theme_color,
        ]);

        CoreSetting::updateOrCreate(['key' => 'fullwidth'], ['value' => $fullwidth]);

        if (empty($content)) {
            $urlTheme = config('rvsitebuildercms.cdn').'/service/html/theme/css/'.$theme_color.'.css';
            $content = guzzle_get_contents($urlTheme);
        }

        File::put(public_path('storage').'/myheader/theme/theme.css', $content);
        MixmanifestLib::mixStorageFile();

        return response()->json([
            'status' => 'success',
        ], 200);
    }
}
