<?php

namespace Rvsitebuilder\Wysiwyg\Process\SaveSite;

use Illuminate\Support\Facades\DB;
use Lib\Util\RVLog;
use Rvsitebuilder\Core\Models\CoreSlug;
use SRIO\ChainOfResponsibility\ChainContext;
use SRIO\ChainOfResponsibility\ChainProcessInterface;

class SaveContentProcess implements ChainProcessInterface
{
    /**
     * TODO:: savetype == 'saveall' or 'content'.
     *
     * @param ChainContext $context
     */
    public function execute(ChainContext $context)
    {
        if ('saveall' !== $context['savetype'] && 'content' !== $context['savetype']) {
            RVLog::debug('skip process');

            return false;
        }

        $savePage = $this->savePage($context['page']);

        $context['response']['page']['status'] = $savePage['status'];
        $context['response']['page']['response_msg'] = $savePage['msg'];
    }

    public function savePage($request)
    {
        try {
            $slug_id = $request['slug_id'];
            $content_view = $request['content_view'];
            $content_edit = $request['content_edit'];

            DB::beginTransaction();
            $slug = CoreSlug::find($slug_id);
            $slug->slugble->update([
                'content_view' => $content_view,
                'content_edit' => $content_edit,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            DB::commit();

            //To fixed undefined logo-mobile.png
            if (!file_exists(public_path('storage').'/images/logo-mobile.png')) {
                $contents = guzzle_get_contents(config('rvsitebuildercms.cdn').'/templates/rvs_library/100/images/thumbnails/logo-mobile.png');
                file_put_contents(public_path('storage').'/images/logo-mobile.png', $contents);
            }

            $response['status'] = 'success';
            $response['msg'] = 'Saved Content success';
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage().' at line:'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            $response['status'] = 'error';
            $response['msg'] = $errorMsg;
        }

        return $response;
    }
}
