<?php

namespace Rvsitebuilder\Wysiwyg\Listeners;

use Illuminate\Support\Facades\DB;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Wysiwyg\Events\AfterSave;

class SaveGlobalPost
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param \Rvsitebuilder\Wysiwyg\Events\afterSave $event
     */
    public function handle(AfterSave $event)
    {
        $data = $event->data['global_post'];

        if ($data) {
            try {
                DB::beginTransaction();

                CoreSetting::updateOrCreate([
                    'key' => 'blog_global_header_view',
                ], [
                    'value' => $data['header_content_view'],
                ]);
                CoreSetting::updateOrCreate([
                    'key' => 'blog_global_header_edit',
                ], [
                    'value' => $data['header_content_edit'],
                ]);
                CoreSetting::updateOrCreate([
                    'key' => 'blog_global_footer_view',
                ], [
                    'value' => $data['footer_content_view'],
                ]);
                CoreSetting::updateOrCreate([
                    'key' => 'blog_global_footer_edit',
                ], [
                    'value' => $data['footer_content_edit'],
                ]);
                DB::commit();

                $response['globalpost']['status'] = 'success';
                $response['globalpost']['msg'] = 'Save Global Post 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['globalpost']['status'] = 'error';
                $response['globalpost']['msg'] = $errorMsg;
            }

            return $response;
        }
    }
}
