<?php

namespace Rvsitebuilder\Wysiwyg\Process\SaveSite;

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

class SaveHeaderProcess implements ChainProcessInterface
{
    /**
     * TODO:: savetype == 'saveall' or 'header'
     *        and isMasterHeader(true) or isBanner(true).
     *
     * @param ChainContext $context
     */
    public function execute(ChainContext $context)
    {
        if ((0 == $context['isMasterHeader'] && 'false' == $context['isBanner']) || ('saveall' != $context['savetype'] && 'header' != $context['savetype'])) {
            RVLog::debug('skip process');

            return false;
        }

        $saveHeader = $this->saveHeader($context['header']);

        $context['response']['header']['status'] = $saveHeader['status'];
        $context['response']['header']['response_msg'] = $saveHeader['msg'];
    }

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

            DB::beginTransaction();
            $slug = CoreSlug::find($slug_id);

            if ((0 == $slug->slugble->header_id) && (!$slug->isHomepage())) {
                //if use master header and is not home page update self
                $newHeader = new CoreHeader();
                $newHeader->content_view = $content_view;
                $newHeader->content_edit = $content_edit;
                $newHeader->save();

                $slug->slugble->update([
                      'header_id' => $newHeader->id,
              ]);
            } elseif (($slug->slugble->header_id == $slug->getMasterHeaderId()) && (!$slug->isHomepage())) {
                $newHeader = new CoreHeader();
                $newHeader->content_view = $content_view;
                $newHeader->content_edit = $content_edit;
                $newHeader->save();

                $slug->slugble->update([
                      'header_id' => $newHeader->id,
              ]);
            } else {
                // update self
                $slug->slugble->getHeader()->update([
                      'content_view' => $content_view,
                      'content_edit' => $content_edit,
              ]);
            }

            DB::commit();
            $response['status'] = 'success';
            $response['msg'] = 'Saved Header 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;
    }
}
