<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Pages;
use App\Models\Admin\PageSections;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class PagesController extends Controller
{
    public function getPagesPage()
    {
        $pagesData = Pages::select('id', 'position_order', 'page_name')->orderBy('position_order')->get();
        foreach ($pagesData as $page) {
            $page->encrypted_id = Crypt::encrypt($page->id);
        }

        $currentPage = "manage_pages";
        return view('admin.page_sequences_ops', compact('pagesData', 'currentPage'));
    }

    public function savePagesSequence(Request $request)
    {
        if (isset($request->page_ids) && count($request->page_ids) > 0) {
            if (isset($request->sequences) && count($request->sequences) > 0) {
                $sequences = $request->sequences;
            } else {
                $sequences = ["1"];
            }
        }
        $executions = 0;

        if (isset($sequences) && count($sequences) > 0) {
            $encrypted_ids = $request->page_ids;
            foreach ($encrypted_ids as $key => $encrypted_id) {
                $id = Crypt::decrypt($encrypted_id);
                $sequence = $sequences[$key];

                $page = Pages::findOrFail($id);
                $page->position_order = $sequence;
                $page->save();
                $executions += 1;
            }
            if ($executions == 0) {
                $request->session()->flash('error', 'Can\'t update the data!');
                return redirect()->route('get.pages.page');
            } else {
                $request->session()->flash('success', 'Sequence is updated Successfully!');
                return redirect()->route('manage.pages');
            }
        } else {
            $request->session()->flash('error', 'Data is not there!');
            return redirect()->route('get.pages.page');
        }
    }

    public function managePages()
    {
        $pagesData = Pages::select('id', 'position_order', 'page_name', 'header_footer_name', 'client_page_urls', 'visibility', 'status')->orderBy('position_order')->get();
        foreach ($pagesData as $page) {
            $page->encrypted_id = Crypt::encrypt($page->id);
        }
        $currentPage = "manage_pages";
        $model = Crypt::encrypt('Pages');
        return view('admin.manage_pages', compact('pagesData', 'model', 'currentPage'));
    }

    public function addPage(Request $request)
    {
        if (session('role') == 'superadmin') {
            if ($request->isMethod('post')) {
                $request->validate([
                    'header_footer_name' => 'required|string',
                    'page_name' => 'required|string'
                ], [
                    'header_footer_name.required' => 'Header/Footer name is required!',
                    'header_footer_name.string' => 'Header/Footer name must be a string!',
                    'page_name.required' => 'Page name is required!',
                    'page_name.string' => 'Page name must be a string!'
                ]);

                $page_order = Pages::max('position_order');
                $position_order = ($page_order !== null) ? $page_order + 1 : 1;

                $page = [
                    'position_order' => $position_order,
                    'page_name' => $request->page_name,
                    'client_page_urls' => $request->client_page_link,
                    'header_footer_name' => $request->header_footer_name,
                    'page_headline' => $request->page_headline,
                    'breadcrumb_headline' => $request->breadcrumb_headline,
                    'description' => htmlspecialchars($request->description, ENT_QUOTES),
                    'meta_title' => $request->meta_title,
                    'meta_keyword' => $request->meta_keyword,
                    'meta_description' => htmlspecialchars($request->meta_description, ENT_QUOTES),
                ];
                if (!empty($request->file('page_image'))) {
                    $path = 'images/pages/';
                    $filePath = $this->storeImage($request->file('page_image'), $path);
                    $page['page_image'] = $filePath;
                }

                if (Pages::create($page)) {
                    $request->session()->flash('success', 'Page is created Successfully!');
                    return redirect()->route('manage.pages');
                } else {
                    $request->session()->flash('error', 'Creation Error!');
                    return redirect()->route('add.page');
                }
            } else {
                $section_enc_id = Crypt::encrypt(0);
                $currentPage = "manage_pages";
                return view('admin.page-ops', compact('section_enc_id', 'currentPage'));
            }
        }
    }

    public function editPage(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'header_footer_name' => 'required|string',
                'page_name' => 'required|string'
            ], [
                'header_footer_name.required' => 'Header/Footer name is required!',
                'header_footer_name.string' => 'Header/Footer name must be a string!',
                'page_name.required' => 'Page name is required!',
                'page_name.string' => 'Page name must be a string!'
            ]);

            $id = Crypt::decrypt($request->page);
            $page = Pages::findOrFail($id);
            if (session('role') == 'superadmin') {
                $page->client_page_urls = $request->client_page_link;
            }
            $page->page_name = $request->page_name;
            $page->header_footer_name = $request->header_footer_name;
            $page->page_headline = $request->page_headline;
            $page->breadcrumb_headline = $request->breadcrumb_headline;
            $page->description = htmlspecialchars($request->description, ENT_QUOTES);
            $page->meta_title = $request->meta_title;
            $page->meta_keyword = $request->meta_keyword;
            $page->meta_description = htmlspecialchars($request->meta_description, ENT_QUOTES);
            if (!empty($request->file('page_image'))) {
                $path = 'images/pages/';
                $filePath = $this->storeImage($request->file("page_image"), $path, $page->page_image);
                $page->page_image = $filePath;
            }

            if ($page->save()) {
                $request->session()->flash('success', 'Page is updated Successfully!');
                return redirect()->route('manage.pages');
            } else {
                $request->session()->flash('error', 'Updation Error!');
                return redirect()->route('edit.page', $request->page);
            }
        } else {
            $page = Pages::where('id', Crypt::decrypt($request->page))->firstOrFail();
            $page->encrypted_id = $request->page;
            $sectionsData = PageSections::where(['page_id' => Crypt::decrypt($request->page), 'parent_id' => null])->orderBy('position_order')->get();
            foreach ($sectionsData as $section) {
                $section->encrypted_id = Crypt::encrypt($section->id);
            }

            $section_enc_id = Crypt::encrypt(0);
            $currentPage = "manage_pages";
            $model = Crypt::encrypt('PageSections');
            return view('admin.page-ops', compact('section_enc_id', 'page', 'sectionsData', 'model', 'currentPage'));
        }
    }

    public function getSectionsPage(Request $request)
    {
        $page_enc_id = $request->page;
        $section_enc_id = $request->section;
        if ($section_enc_id == 0) {
            $sectionsData = PageSections::select('id', 'position_order', 'section_headline')->where(['page_id' => Crypt::decrypt($page_enc_id), 'parent_id' => null])->orderBy('position_order')->get();
            foreach ($sectionsData as $section) {
                $section->encrypted_id = Crypt::encrypt($section->id);
            }
        } else {
            $sectionsData = PageSections::select('id', 'position_order', 'section_headline')->where(['page_id' => Crypt::decrypt($page_enc_id), 'parent_id' => Crypt::decrypt($section_enc_id)])->orderBy('position_order')->get();
            foreach ($sectionsData as $subsection) {
                $subsection->encrypted_id = Crypt::encrypt($subsection->id);
            }
        }

        $currentPage = "manage_pages";
        return view('admin.section_sequences_ops', compact('sectionsData', 'page_enc_id', 'section_enc_id', 'currentPage'));
    }

    public function saveSectionsSequence(Request $request)
    {
        $page_id = Crypt::decrypt($request->page);
        if (isset($request->section) && !empty($request->section)) {
            $section_id = Crypt::decrypt($request->section);
        } else {
            $section_id = 0;
        }
        if (isset($request->section_ids) && count($request->section_ids) > 0) {
            if (isset($request->sequences) && count($request->sequences) > 0) {
                $sequences = $request->sequences;
            } else {
                $sequences = ["1"];
            }
        }
        $executions = 0;

        if (isset($sequences) && count($sequences) > 0) {
            $encrypted_ids = $request->section_ids;
            foreach ($encrypted_ids as $key => $encrypted_id) {
                $id = Crypt::decrypt($encrypted_id);
                $sequence = $sequences[$key];

                if ($section_id != 0) {
                    $section = PageSections::where(["id" => $id, "page_id" => $page_id, "parent_id" => $section_id])->first();
                } else {
                    $section = PageSections::where(["id" => $id, "page_id" => $page_id, "parent_id" => null])->first();
                }
                $section->position_order = $sequence;
                $section->save();
                $executions += 1;
            }
            if ($executions == 0) {
                $request->session()->flash('error', 'Can\'t update the data!');
                return redirect()->route('get.sections.page', ["page" => $request->page, "section" => $request->section]);
            } else {
                $request->session()->flash('success', 'Sequence is updated Successfully!');
                if ($section_id != 0) {
                    return redirect()->route('edit.page.section', ["page" => $request->page, "section" => $request->section]);
                } else {
                    return redirect()->route('edit.page', ["page" => $request->page, "section" => $request->section]);
                }
            }
        } else {
            $request->session()->flash('error', 'Data is not there!');
            return redirect()->route('get.sections.page', ["page" => $request->page, "section" => $request->section]);
        }
    }

    public function addPageSection(Request $request)
    {
        if (session('role') == 'superadmin') {
            if ($request->isMethod('post')) {
                $request->validate([
                    'default_section_name' => 'required|string',
                    'section_headline' => 'required|string',
                    'section_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'default_section_name.required' => 'Default section name is required!',
                    'default_section_name.string' => 'Default section name must be a string!',
                    'section_headline.required' => 'Section headline is required!',
                    'section_headline.string' => 'Section headline must be a string!',
                    'section_image.image' => 'The file must be an image!',
                    'section_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'section_image.max' => 'The image must not be larger than 2MB!'
                ]);

                $page_id = Crypt::decrypt($request->page);
                $section_order = PageSections::where(["page_id" => $page_id, "parent_id" => null])->max('position_order');
                $position_order = ($section_order !== null) ? $section_order + 1 : 1;

                $section = [
                    'page_id' => $page_id,
                    'default_section_name' => $request->default_section_name,
                    'position_order' => $position_order,
                    'section_title' => $request->section_title,
                    'section_headline' => $request->section_headline,
                    'description' => htmlspecialchars($request->description, ENT_QUOTES),
                    'button_name' => $request->button_name,
                    'button_link' => $request->button_link,
                ];
                if (!empty($request->file('section_image'))) {
                    $path = 'images/pages/sections/';
                    $filePath = $this->storeImage($request->file("section_image"), $path);
                    $section['section_image'] = $filePath;
                }
                if (!empty($request->file('section_video'))) {
                    $path = 'images/pages/sections/';
                    $videoPath = $this->storeImage($request->file("section_video"), $path);
                    $section['section_video'] = $videoPath;
                }

                $image_paths = [];
                if ($request->hasFile('more_images')) {
                    $path = 'images/pages/sections/';
                    foreach ($request->file('more_images') as $file) {
                        $filePath = $this->storeImage($file, $path);
                        $image_paths[] = $filePath;
                    }
                    $section['more_images'] = json_encode($image_paths);
                }

                if (PageSections::create($section)) {
                    $request->session()->flash('success', 'Section is inserted Successfully!');
                    return redirect()->route('edit.page', $request->page);
                } else {
                    $request->session()->flash('error', 'Insertion Error!');
                    return redirect()->route('add.page.section', $request->page);
                }
            } else {
                $page_enc_id = $request->page;
                $currentPage = "manage_pages";
                return view('admin.page-section-ops', compact('page_enc_id', 'currentPage'));
            }
        }
    }

    public function editPageSection(Request $request)
    {
        if ($request->isMethod('post')) {
            if (session('role') == 'superadmin') {
                $request->validate([
                    'default_section_name' => 'required|string',
                    'section_headline' => 'required|string',
                    'section_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'default_section_name.required' => 'Default section name is required!',
                    'default_section_name.string' => 'Default section name must be a string!',
                    'section_headline.required' => 'Section headline is required!',
                    'section_headline.string' => 'Section headline must be a string!',
                    'section_image.image' => 'The file must be an image!',
                    'section_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'section_image.max' => 'The image must not be larger than 2MB!'
                ]);
            } elseif (session('role') == 'admin') {
                $request->validate([
                    'section_headline' => 'required|string',
                    'section_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'section_headline.required' => 'Section headline is required!',
                    'section_headline.string' => 'Section headline must be a string!',
                    'section_image.image' => 'The file must be an image!',
                    'section_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'section_image.max' => 'The image must not be larger than 2MB!'
                ]);
            }

            $id = Crypt::decrypt($request->section);
            $section = PageSections::findOrFail($id);
            if (session('role') == 'superadmin') {
                $section->default_section_name = $request->default_section_name;
            }
            $section->section_title = $request->section_title;
            $section->section_headline = $request->section_headline;
            $section->description = htmlspecialchars($request->description, ENT_QUOTES);
            $section->button_name = $request->button_name;
            $section->button_link = $request->button_link;

            if (!empty($request->file('section_image'))) {
                $path = 'images/pages/sections/';
                $filePath = $this->storeImage($request->file("section_image"), $path, $section->section_image);
                $section->section_image = $filePath;
            }
            if (!empty($request->file('section_video'))) {
                $path = 'images/pages/sections/';
                $videoPath = $this->storeImage($request->file("section_video"), $path, $section->section_video);
                $section->section_video = $videoPath;
            }

            $image_paths = [];
            if ($request->hasFile('more_images')) {
                $more_images = json_decode($section->more_images, true);
                if (!empty($more_images)) {
                    foreach ($more_images as $image) {
                        $this->removeImage($image);
                    }
                }

                $path = 'images/pages/sections/';
                foreach ($request->file('more_images') as $file) {
                    $filePath = $this->storeImage($file, $path);
                    $image_paths[] = $filePath;
                }
                $section->more_images = json_encode($image_paths, JSON_HEX_APOS | JSON_HEX_QUOT);
            }

            if ($section->save()) {
                $request->session()->flash('success', 'Section is updated Successfully!');
                return redirect()->route('edit.page', $request->page);
            } else {
                $request->session()->flash('error', 'Updation Error!');
                return redirect()->route('edit.page.section', ["page" => $request->page, "section" => $request->section]);
            }
        } else {
            $page_enc_id = $request->page;
            $section = PageSections::where('id', Crypt::decrypt($request->section))->firstOrFail();
            $section->encrypted_id = $request->section;
            $subSectionsData = PageSections::where(['page_id' => Crypt::decrypt($page_enc_id), 'parent_id' => Crypt::decrypt($request->section)])->orderBy('position_order')->get();
            foreach ($subSectionsData as $subsection) {
                $subsection->encrypted_id = Crypt::encrypt($subsection->id);
            }
            $currentPage = "manage_pages";
            $model = Crypt::encrypt('PageSections');
            return view('admin.page-section-ops', compact('section', 'page_enc_id', 'subSectionsData', 'model', 'currentPage'));
        }
    }

    public function addPageSubSection(Request $request)
    {
        if ($request->isMethod('post')) {
            if (session('role') == 'superadmin') {
                $request->validate([
                    'default_subsection_name' => 'required|string',
                    'subsection_headline' => 'required|string',
                    'subsection_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'default_subsection_name.required' => 'Default section name is required!',
                    'default_subsection_name.string' => 'Default section name must be a string!',
                    'subsection_headline.required' => 'Section headline is required!',
                    'subsection_headline.string' => 'Section headline must be a string!',
                    'subsection_image.image' => 'The file must be an image!',
                    'subsection_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'subsection_image.max' => 'The image must not be larger than 2MB!'
                ]);
            } elseif (session('role') == 'admin') {
                $request->validate([
                    'subsection_headline' => 'required|string',
                    'subsection_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'subsection_headline.required' => 'Section headline is required!',
                    'subsection_headline.string' => 'Section headline must be a string!',
                    'subsection_image.image' => 'The file must be an image!',
                    'subsection_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'subsection_image.max' => 'The image must not be larger than 2MB!'
                ]);
            }

            $page_enc_id = $request->page;
            $section_enc_id = $request->section;
            $page_id = Crypt::decrypt($page_enc_id);
            $section_id = Crypt::decrypt($section_enc_id);
            $subsection_order = PageSections::where(["page_id" => $page_id, "parent_id" => $section_id])->max('position_order');
            $position_order = ($subsection_order !== null) ? $subsection_order + 1 : 1;

            $subsection = [
                'page_id' => $page_id,
                'parent_id' => $section_id,
                'position_order' => $position_order,
                'section_title' => $request->subsection_title,
                'section_headline' => $request->subsection_headline,
                'section_icon' => $request->subsection_icon,
                'description' => htmlspecialchars($request->description, ENT_QUOTES)
            ];
            if (session('role') == 'superadmin') {
                $subsection['default_section_name'] = $request->default_subsection_name;
            }
            if (!empty($request->file('subsection_image'))) {
                $path = 'images/pages/sections/';
                $filePath = $this->storeImage($request->file("subsection_image"), $path);
                $subsection['section_image'] = $filePath;
            }

            if (PageSections::create($subsection)) {
                $request->session()->flash('success', 'Sub-Section is inserted Successfully!');
                return redirect()->route('edit.page.section', ["page" => $page_enc_id, "section" => $section_enc_id]);
            } else {
                $request->session()->flash('error', 'Insertion Error!');
                return redirect()->route('add.page.subsection', ["page" => $page_enc_id, "section" => $section_enc_id]);
            }
        } else {
            $page_enc_id = $request->page;
            $section_enc_id = $request->section;
            $currentPage = "manage_pages";
            return view('admin.page-subsection-ops', compact('page_enc_id', 'section_enc_id', 'currentPage'));
        }
    }

    public function editPageSubSection(Request $request)
    {
        if ($request->isMethod('post')) {
            if (session('role') == 'superadmin') {
                $request->validate([
                    'default_subsection_name' => 'required|string',
                    'subsection_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'default_subsection_name.required' => 'Default section name is required!',
                    'default_subsection_name.string' => 'Default section name must be a string!',
                    'subsection_image.image' => 'The file must be an image!',
                    'subsection_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'subsection_image.max' => 'The image must not be larger than 2MB!'
                ]);
            } elseif (session('role') == 'admin') {
                $request->validate([
                    'subsection_image' => 'image|mimes:jpeg,png,jpg,gif,webp|max:2048'
                ], [
                    'subsection_image.image' => 'The file must be an image!',
                    'subsection_image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif, webp.',
                    'subsection_image.max' => 'The image must not be larger than 2MB!'
                ]);
            }

            $id = Crypt::decrypt($request->subsection);
            $subsection = PageSections::findOrFail($id);
            if (session('role') == 'superadmin') {
                $subsection->default_section_name = $request->default_subsection_name;
            }
            $subsection->section_title = $request->subsection_title;
            $subsection->section_headline = $request->subsection_headline;
            $subsection->section_icon = $request->subsection_icon;
            $subsection->description = htmlspecialchars($request->description, ENT_QUOTES);

            if (!empty($request->file('subsection_image'))) {
                $path = 'images/pages/sections/';
                $filePath = $this->storeImage($request->file("subsection_image"), $path, $subsection->section_image);
                $subsection->section_image = $filePath;
            }

            if ($subsection->save()) {
                $request->session()->flash('success', 'Sub-Section is updated Successfully!');
                return redirect()->route('edit.page.section', ["page" => $request->page, "section" => $request->section]);
            } else {
                $request->session()->flash('error', 'Updation Error!');
                return redirect()->route('edit.page.subsection', ["page" => $request->page, "section" => $request->section, "subsection" => $request->subsection]);
            }
        } else {
            $page_enc_id = $request->page;
            $section_enc_id = $request->section;
            $subsection = PageSections::where('id', Crypt::decrypt($request->subsection))->firstOrFail();
            $subsection->encrypted_id = $request->subsection;
            $currentPage = "manage_pages";
            return view('admin.page-subsection-ops', compact('subsection', 'page_enc_id', 'section_enc_id', 'currentPage'));
        }
    }
}
