<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Lib\Content\FooterLib;
use Rvsitebuilder\Core\Models\CoreFooter;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Wysiwyg\Http\Requests\ResetFooterRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveFooterRequest;

class FooterController extends Controller
{
    public function saveFooter(SaveFooterRequest $request)
    {
        $page_id = $request->input('page_id');
        $content_view = $request->input('content_view');
        $content_edit = $request->input('content_edit');
        $cdnImg = [];
        if ($request->has('cdn')) {
            $cdnImg = $request->input('cdn');
        }

        try {
            DB::transaction(function () use ($content_view ,$content_edit, $page_id,$cdnImg) {
                $page = CorePage::find($page_id);

                $footer = CoreFooter::find($page->footer_id);
                $footer->content_view = $this->downloadImgCdn($cdnImg, $content_view);
                $footer->content_edit = $this->downloadImgCdn($cdnImg, $content_edit);
                $footer->created_at = date('Y-m-d H:i:s');
                $footer->save();
            });
            DB::commit();

            $response = [
            'status' => 'success',
            'messages' => 'Save Footer Success',
            //'debug_msg' => $debug_msg
        ];

            return response()->json($response);
        } catch (\Exception $e) {
            DB::rollBack();

            return 'false:'.$e->getMessage().' at line:'.$e->getLine();
        }
    }

    public function saveInfomation(Request $request)
    {
        try {
            DB::beginTransaction();

            CoreSetting::updateOrCreate(['key' => 'title_info'], ['value' => $request->input('title')]);
            CoreSetting::updateOrCreate(['key' => 'content_info'], ['value' => $request->input('detail')]);
            //  query process
            DB::commit();

            $response = [
                'status' => 'success',
                'messages' => 'Save Infomation Success',
                //'debug_msg' => $debug_msg
            ];

            return response()->json($response);
        } 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__));
            exit;
        }
    }

    public function downloadImgCdn($cdnImg, $content)
    {
        if (count($cdnImg)) {
            foreach ($cdnImg as $key => $value) {
                $pathUpload = public_path('storage').'/images/'.basename($value);

                if (!File::exists($pathUpload)) {
                    $contents = guzzle_get_contents($value);
                    File::put($pathUpload, $contents);
                }

                $filePath[] = addslashes(URL::to(Storage::url('images/'.basename($value))));
            }

            $content = str_replace($cdnImg, $filePath, $content);
        }

        return $content;
    }

    public function resetFooter(ResetFooterRequest $request)
    {
        $slug_id = $request->input('slug_id');
        $slug = CoreSlug::find($slug_id);
        $footer_id = $slug->slugble->footer_id;

        if (!$slug->isHomepage()) {
            $slug->slugble->update(['footer_id' => 0]);
            CoreFooter::where('id', '<>', 1)->where('id', '=', $footer_id)->delete();
        }

        //return Footer content
        if ($slug->isPost() || $slug->isCategory()) {
            $footer = FooterLib::getMasterFooterBlog($slug);
        } else {
            $footer = FooterLib::getMasterFooter($slug);
        }

        return $footer->content_edit;
    }
}
