<?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 SaveMetaAutoProcess implements ChainProcessInterface
{
    /**
     * TODO:: savetype == 'saveall'.
     *
     * @param ChainContext $context
     */
    public function execute(ChainContext $context)
    {
        if ('saveall' !== $context['savetype']) {
            RVLog::debug('skip process');

            return false;
        }
        $saveMetaAuto = $this->saveMetaAuto($context['meta_auto']);

        $context['response']['meta_auto']['status'] = $saveMetaAuto['status'];
        $context['response']['meta_auto']['response_msg'] = $saveMetaAuto['msg'];
    }

    public function saveMetaAuto($request)
    {
        try {
            $slug_id = $request['slug_id'];
            $title_auto = $request['meta_title_auto'];
            $des_auto = $request['meta_des_auto'];

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

            if (\strlen($title_auto) > 255) {
                $title_auto = substr($title_auto, 0, 250);
            }

            if (\strlen($des_auto) > 255) {
                $des_auto = substr($des_auto, 0, 250);
            }

            $slug->slugble->getSeo()->update([
                'meta_title_auto' => $title_auto,
                'meta_des_auto' => $des_auto,
            ]);

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