<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Frontend;
use App\Rules\FileTypeValidate;
use Illuminate\Http\Request;

class FrontendController extends Controller
{
    public function pagesList()
    {
        $pageTitle = 'Policy Pages';
        $pages     = Frontend::where('data_keys', 'policy_pages.element')->orderBy('id', 'desc')->get();
        return view('admin.setting.frontend.pages_list', compact('pageTitle', 'pages'));
    }

    public function addPage()
    {
        $pageTitle = 'Add Policy Page';
        return view('admin.setting.frontend.form', compact('pageTitle'));
    }

    public function editPage($id)
    {
        $pageTitle = 'Update Policy Page';
        $page      = Frontend::findOrFail($id);
        return view('admin.setting.frontend.form', compact('pageTitle', 'page'));
    }

    public function savePage(Request $request, $id = 0)
    {
        $request->validate([
            'title'       => 'required|string',
            'slug'        => ['required', 'string', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'],
            'description' => 'required|string',
        ]);

        if ($id) {
            $page     = Frontend::where('data_keys', 'policy_pages.element')->findOrFail($id);
            $notify[] = ['success', 'Page updated successfully'];
        } else {
            $page            = new Frontend();
            $page->data_keys = 'policy_pages.element';
            $notify[]        = ['success', 'Page added successfully'];
        }

        $exits = Frontend::where('slug', $request->slug);

        if ($id) {
            $exits->where('id', '!=', $id);
        }

        $exits = $exits->first();

        if ($exits) {
            $notify[] = ['error', 'Slug already exists'];
            return back()->withNotify($notify);
        }

        $dataValues = [
            'title'   => $request->title,
            'details' => $request->description,
        ];

        $page->data_values = $dataValues;
        $page->slug        = $request->slug;
        $page->save();

        return back()->withNotify($notify);
    }

    public function frontendElementSlugCheck($id = 0)
    {
        $content = Frontend::where('slug', request()->slug);
        if ($id) {
            $content = $content->where('id', '!=', $id);
        }
        $exist = $content->exists();
        return response()->json([
            'exists' => $exist,
        ]);
    }

    public function remove($id)
    {
        $page = Frontend::findOrFail($id);
        $page->delete();

        $notify[] = ['success', 'Policy page deleted successfully'];
        return back()->withNotify($notify);
    }

    public function frontendContent()
    {
        $pageTitle = 'Frontend Content';
        $frontend  = Frontend::where('data_keys', 'frontend.content')->first();

        return view('admin.setting.frontend.content', compact('pageTitle', 'frontend'));
    }

    public function frontendContentSave(Request $request)
    {
        $request->validate([
            'label_one'               => 'nullable|string',
            'label_two'               => 'nullable|string',
            'label_three'             => 'nullable|string',
            'banner_title'            => 'required|string',
            'banner_subtitle'         => 'required|string',
            'feature_one'             => 'nullable|string',
            'feature_two'             => 'nullable|string',
            'feature_three'           => 'nullable|string',
            'knowledge_base_title'    => 'required|string',
            'knowledge_base_subtitle' => 'required|string',
            'faq_title'               => 'required|string',
            'faq_subtitle'            => 'required|string',
            'cta_title'               => 'required|string',
            'cta_subtitle'            => 'required|string',
            'cta_button'              => 'required|string',
            'cta_image'               => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
            'auth_heading_one'        => 'required|string',
            'auth_heading_two'        => 'required|string',
            'auth_subheading'         => 'required|string',
            'image'                   => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
        ]);

        $frontend = Frontend::where('data_keys', 'frontend.content')->first();
        $ctaImage = $frontend->data_values->cta_image ?? '';
        $image    = $frontend->data_values->image ?? '';

        if ($request->cta_image) {
            try {
                $ctaImage = fileUploader($request->cta_image, getFilePath('ctaImage'), getFileSize('ctaImage'), $ctaImage);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload the image'];
                return back()->withNotify($notify);
            }
        }

        if ($request->image) {
            try {
                $image = fileUploader($request->image, getFilePath('authorizationPage'), getFileSize('authorizationPage'), $image);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload the image'];
                return back()->withNotify($notify);
            }
        }

        $frontend->data_values = [
            'label_one'               => $request->label_one,
            'label_two'               => $request->label_two,
            'label_three'             => $request->label_three,
            'banner_title'            => $request->banner_title,
            'banner_subtitle'         => $request->banner_subtitle,
            'feature_one'             => $request->feature_one,
            'feature_two'             => $request->feature_two,
            'feature_three'           => $request->feature_three,
            'knowledge_base_title'    => $request->knowledge_base_title,
            'knowledge_base_subtitle' => $request->knowledge_base_subtitle,
            'faq_title'               => $request->faq_title,
            'faq_subtitle'            => $request->faq_subtitle,
            'cta_title'               => $request->cta_title,
            'cta_subtitle'            => $request->cta_subtitle,
            'cta_button'              => $request->cta_button,
            'cta_image'               => $ctaImage,
            'auth_heading_one'        => $request->auth_heading_one,
            'auth_heading_two'        => $request->auth_heading_two,
            'auth_subheading'         => $request->auth_subheading,
            'image'                   => $image,
        ];

        $frontend->save();

        $notify[] = ['success', 'Frontend content saved successfully'];
        return back()->withNotify($notify);
    }

    public function faq()
    {
        $pageTitle = 'Faq';
        $faqs      = Frontend::where('data_keys', 'faq.element');

        $search = request()->search;
        if ($search) {
            $faqs->where('data_values->question', 'like', "%$search%")->orWhere('data_values->question', 'like', "%$search%");
        }

        $faqs = $faqs->paginate(getPaginate());
        return view('admin.setting.frontend.faq', compact('pageTitle', 'faqs'));
    }

    public function saveFaq(Request $request, $id = 0)
    {
        $request->validate([
            'question' => 'required',
            'answer'   => 'required',
        ]);

        if ($id) {
            $faq      = Frontend::where('data_keys', 'faq.element')->findOrFail($id);
            $notify[] = ['success', 'Faq updated successfully'];
        } else {
            $faq            = new Frontend();
            $faq->data_keys = 'faq.element';
            $notify[]       = ['success', 'Faq added successfully'];
        }

        $faq->data_values = [
            'question' => $request->question,
            'answer'   => $request->answer,
        ];

        $faq->save();

        return back()->withNotify($notify);
    }

    public function deleteFaq($id)
    {
        $faq = Frontend::where('data_keys', 'faq.element')->findOrFail($id);
        $faq->delete();

        $notify[] = ['success', 'Faq deleted successfully'];
        return back()->withNotify($notify);
    }

    public function seo()
    {
        $pageTitle = 'SEO Configuration';
        $seo       = Frontend::where('data_keys', 'seo.data')->first();

        if (!$seo) {
            $data_values           = '{"keywords":[],"description":"","social_title":"","social_description":"","image":null}';
            $data_values           = json_decode($data_values, true);
            $frontend              = new Frontend();
            $frontend->data_keys   = 'seo.data';
            $frontend->data_values = $data_values;
            $frontend->save();
        }
        return view('admin.setting.frontend.seo', compact('pageTitle', 'seo'));
    }

    public function saveSeo(Request $request)
    {
        $request->validate([
            'keywords'           => 'required|array',
            'description'        => 'required|string',
            'social_title'       => 'required|string',
            'social_description' => 'required|string',
            'image'              => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
        ]);

        $seo   = Frontend::where('data_keys', 'seo.data')->first();
        $image = $seo->data_values->image ?? '';

        if ($request->image) {
            try {
                $image = fileUploader($request->image, getFilePath('seo'), getFileSize('seo'), $image);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload the image'];
                return back()->withNotify($notify);
            }
        }

        $seo->data_values = [
            'keywords'           => $request->keywords,
            'description'        => $request->description,
            'social_title'       => $request->social_title,
            'social_description' => $request->social_description,
            'image'              => $image,
        ];

        $seo->save();

        $notify[] = ['success', 'Seo content updated successfully'];
        return back()->withNotify($notify);
    }
}
