<?php

namespace Workdo\MobileServiceManagement\Http\Controllers;

use App\Models\WorkSpace;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

use Workdo\MobileServiceManagement\Entities\MobileServiceCustomPage;
use Workdo\MobileServiceManagement\Entities\MobileServiceThemeSetting;

class MobileServiceThemeSettingController extends Controller
{
    // ===============================================
    // TOGGLE FUNCTION FOR ALL SECTIONS & PAGE ON/OFF
    // ===============================================
    public function toggle(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $key   = collect($request->except('_token'))->keys()->first();
            $value = $request->input($key);

            if ($key && str_starts_with($key, 'is_') && (str_ends_with($key, '_section_active') || str_ends_with($key, '_page_active'))) {

                MobileServiceThemeSetting::setSetting($key, $value);

                $type   = str_ends_with($key, '_page_active') ? 'Page' : 'Section';
                $status = $value === 'on' ? 'activated' : 'deactivated';

                return response()->json(['success' => __("{$type} has been {$status} successfully.")], 200);
            }

            return response()->json(['error' => __('Invalid request.')], 422);
        } else {
            return response()->json(['error' => __('Permission denied.')], 403);
        }
    }

    // ============================================
    // SITE SETTINGS
    // ============================================
    public function siteSettingsIndex()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $settings = MobileServiceThemeSetting::getAllSettings();
            return view('mobile-service-management::theme-setup.site-setup.index', compact('settings'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function siteSettingsStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $files = [
                'logo'        => 'logo_',
                'footer_logo' => 'footer_logo_',
                'favicon'     => 'favicon_',
            ];

            foreach ($files as $field => $prefix) {
                if ($request->hasFile($field)) {
                    $img             = $request->file($field);
                    $ext             = $img->getClientOriginalExtension();
                    $fileNameToStore = $prefix . time() . '.' . $ext;

                    $path = upload_file($request, $field, $fileNameToStore, 'mobileservice');
                    if ($path['flag'] == 1) {
                        $old = MobileServiceThemeSetting::getSetting($field, '');
                        if (!empty($old) && check_file($old)) {
                            delete_file($old);
                        }

                        MobileServiceThemeSetting::setSetting($field, $path['url']);
                    } else {
                        return redirect()->back()->with('error', __($path['msg']));
                    }
                }
            }

            $settings = [
                'site_title'         => $request->site_title,
                'footer_text'        => $request->footer_text,
                'footer_description' => $request->footer_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Site settings updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    // ============================================
    // HOME PAGE SETUP
    // ============================================
    public function homeSetupIndex()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $settings = MobileServiceThemeSetting::getAllSettings();

            return view('mobile-service-management::theme-setup.home-setup.index', compact('settings'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function bannerStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'banner_title'       => $request->banner_title,
                'banner_subtitle'    => $request->banner_subtitle,
                'banner_description' => $request->banner_description,
                'banner_image_icon'  => $request->banner_image_icon,
                'banner_image_text'  => $request->banner_image_text,
            ];

            if ($request->hasFile('banner_image')) {
                $img             = $request->file('banner_image');
                $ext             = $img->getClientOriginalExtension();
                $fileNameToStore = 'banner_image_' . time() . '.' . $ext;

                $path = upload_file($request, 'banner_image', $fileNameToStore, 'mobileservice');
                if ($path['flag'] == 1) {
                    $old_banner_image = MobileServiceThemeSetting::getSetting('banner_image', '');
                    if (!empty($old_banner_image) && check_file($old_banner_image)) {
                        delete_file($old_banner_image);
                    }

                    $settings['banner_image'] = $path['url'];
                } else {
                    return redirect()->back()->with('error', __($path['msg']));
                }
            }

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Banner section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function trackingStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'tracking_title'       => $request->tracking_title,
                'tracking_description' => $request->tracking_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Service tracking section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function expertiseStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'expertise_title'       => $request->expertise_title,
                'expertise_description' => $request->expertise_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Our Expertise section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function aboutStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'about_title'       => $request->about_title,
                'about_description' => $request->about_description,
                'about_image_text'  => $request->about_image_text,
                'facility_features' => $request->facility_features ? json_encode($request->facility_features) : null,
            ];

            if ($request->hasFile('about_image')) {
                $img             = $request->file('about_image');
                $ext             = $img->getClientOriginalExtension();
                $fileNameToStore = 'about_image_' . time() . '.' . $ext;

                $path = upload_file($request, 'about_image', $fileNameToStore, 'mobileservice');
                if ($path['flag'] == 1) {
                    $old_about_image = MobileServiceThemeSetting::getSetting('about_image', '');
                    if (!empty($old_about_image) && check_file($old_about_image)) {
                        delete_file($old_about_image);
                    }

                    $settings['about_image'] = $path['url'];
                } else {
                    return redirect()->back()->with('error', __($path['msg']));
                }
            }

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('About section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function testimonialsStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'testimonials_title'       => $request->testimonials_title,
                'testimonials_description' => $request->testimonials_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Testimonials section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function ctaStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'cta_title'       => $request->cta_title,
                'cta_description' => $request->cta_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('CTA section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    // ============================================
    // ABOUT PAGE SETUP
    // ============================================
    public function aboutSetupIndex()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $settings = MobileServiceThemeSetting::getAllSettings();

            // staff select in team
            $staffOptions = \App\Models\User::where('workspace_id', '=', getActiveWorkSpace())
                ->where('created_by', '=', creatorId())
                ->emp()
                ->pluck('name', 'id');
            $staffOptions->prepend(__('Select staff'), '');

            return view('mobile-service-management::theme-setup.about-setup.index', compact('settings', 'staffOptions'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function aboutStoryStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'story_title'       => $request->story_title,
                'story_description' => $request->story_description,
            ];

            if ($request->hasFile('story_image')) {
                $img             = $request->file('story_image');
                $ext             = $img->getClientOriginalExtension();
                $fileNameToStore = 'story_image_' . time() . '.' . $ext;

                $path = upload_file($request, 'story_image', $fileNameToStore, 'mobileservice');
                if ($path['flag'] == 1) {
                    $old_story_image = MobileServiceThemeSetting::getSetting('story_image', '');
                    if (!empty($old_story_image) && check_file($old_story_image)) {
                        delete_file($old_story_image);
                    }

                    $settings['story_image'] = $path['url'];
                } else {
                    return redirect()->back()->with('error', __($path['msg']));
                }
            }

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Our story section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function aboutMissionStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'mission_title'       => $request->mission_title,
                'mission_description' => $request->mission_description,
                'mission_items'       => $request->mission_items ? json_encode(array_values($request->mission_items)) : null,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Our Mission section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function aboutTeamStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'team_title'       => $request->team_title,
                'team_description' => $request->team_description,
                'team_members'     => $request->team_members ? json_encode(array_values($request->team_members)) : null,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Our Team section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function aboutCtaStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'about_cta_title'       => $request->about_cta_title,
                'about_cta_description' => $request->about_cta_description,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('CTA section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    // ============================================
    // CONTACT PAGE SETUP
    // ============================================
    public function contactSetupIndex()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $settings = MobileServiceThemeSetting::getAllSettings();
            return view('mobile-service-management::theme-setup.contact-setup.index', compact('settings'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function contactInfoStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $serviceHours = $request->service_hours;
            if (is_string($serviceHours)) {
                $serviceHours = json_decode($serviceHours, true);
            }

            $settings = [
                'location_title'    => $request->location_title,
                'contact_address'   => $request->contact_address,
                'hours_title'       => $request->hours_title,
                'service_hours'     => $serviceHours ? json_encode(array_values($serviceHours)) : null,
                'contact_title'     => $request->contact_title,
                'contact_phone'     => $request->contact_phone,
                'contact_email'     => $request->contact_email,
                'contact_emergency' => $request->contact_emergency,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Contact information updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function contactSocialStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'social_links' => $request->social_links ? json_encode(array_values($request->social_links)) : null,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Follow us links updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function contactMapStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'map_title'       => $request->map_title,
                'map_description' => $request->map_description,
                'map_iframe'      => $request->map_iframe,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('Our repair center section updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    // ============================================
    // FAQ & CUSTOM PAGES SETUP
    // ============================================
    public function faqCustomSetupIndex()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $settings = MobileServiceThemeSetting::getAllSettings();

            // Custom Pages & Slug Get
            $pages           = MobileServiceCustomPage::where('created_by', creatorId())->where('workspace', getActiveWorkSpace())->get();
            $activeworkspace = WorkSpace::where('id', Auth::user()->active_workspace)->first();
            $slug            = $activeworkspace->slug;

            return view('mobile-service-management::theme-setup.faq-custom-setup.index', compact('settings', 'pages', 'slug'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function faqStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $settings = [
                'faq_data' => $request->faqs ? json_encode(array_values($request->faqs)) : null,
            ];

            MobileServiceThemeSetting::setMultipleSettings($settings);

            return redirect()->back()->with('success', __('FAQ page updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function customPageCreate()
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            return view('mobile-service-management::theme-setup.faq-custom-setup.custom-pages.create');
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function customPageStore(Request $request)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'name'     => 'required',
                    'title'    => 'required',
                    'contents' => 'required',
                ]
            );

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();
                return redirect()->back()->with('error', $messages->first());
            }

            $page                 = new MobileServiceCustomPage();
            $page->name           = $request->name;
            $page->title          = $request->title;
            $page->contents       = $request->contents;
            $page->show_in_footer = $request->has('show_in_footer') ? true : false;
            $page->workspace      = getActiveWorkSpace();
            $page->created_by     = creatorId();
            $page->save();

            return redirect()->back()->with('success', __('The custom page has been created successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function customPageEdit($id)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $page = MobileServiceCustomPage::where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->find($id);

            return view('mobile-service-management::theme-setup.faq-custom-setup.custom-pages.edit', compact('page'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function customPageUpdate(Request $request, $id)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'name'     => 'required',
                    'title'    => 'required',
                    'contents' => 'required',
                ]
            );

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();
                return redirect()->back()->with('error', $messages->first());
            }

            $page = MobileServiceCustomPage::where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->find($id);

            $page->name           = $request->name;
            $page->title          = $request->title;
            $page->contents       = $request->contents;
            $page->show_in_footer = $request->has('show_in_footer') ? true : false;
            $page->save();

            return redirect()->back()->with('success', __('The custom page details are updated successfully'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function customPageDestroy($id)
    {
        if (Auth::user()->isAbleTo('mobileservice theme setup manage')) {

            $page = MobileServiceCustomPage::where('created_by', creatorId())
                ->where('workspace', getActiveWorkSpace())
                ->find($id);
            $page->delete();

            return redirect()->back()->with('success', __('The custom page has been deleted'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
}
