<?php

namespace App\Http\Controllers\Admin;

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

class BlogsController extends Controller
{
    public function checkBlogLink($link, $encrypted_id = "")
    {
        $link = str_replace(['/', ' '], '-', $link);
        $link = preg_replace('/[^a-z0-9-]+/', '-', $link);
        $link = trim($link, '-');
        $link = preg_replace('/-+/', '-', $link);
        $original_link = $link;

        $id = (isset($encrypted_id) && !empty($encrypted_id)) ? Crypt::decrypt($encrypted_id) : 0;
        $suffix = 1;
        do {
            $count = $id != 0 ? Blogs::where('blog_url', $link)->where('id', '!=', $id)->count() : Blogs::where('blog_url', $link)->count();

            if ($count > 0) {
                $link = $original_link . '-' . $suffix;
                $suffix++;
            } else {
                break;
            }
        } while (true);

        return $link;
    }

    public function manageBlogs()
    {
        $blogs = Blogs::select('id', 'position_order', 'blog_headline', 'blog_url', 'blog_image', 'status')->orderBy('position_order')->get();
        foreach ($blogs as $blog) {
            $blog->encrypted_id = Crypt::encrypt($blog->id);
        }

        $currentPage = "manage_blogs";
        $model = Crypt::encrypt('Blogs');
        return view('admin.manage_blogs', ['blogsData' => $blogs, 'model' => $model, 'currentPage' => $currentPage]);
    }

    public function addBlog(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                // 'blog_category' => 'required',
                'blog_headline' => 'required|string',
                'blog_url' => 'required|string',
                'written_by' => 'nullable|string',
            ], [
                // 'blog_category.required' => 'Please provide a category for the blog.',
                'blog_headline.required' => 'Please provide a headline for the blog.',
                'blog_headline.string' => 'Blog headline must be a string.',
                'blog_url.required' => 'Please provide URL for the blog.',
                'blog_url.string' => 'URL must be a string.',
                'written_by.string' => 'The author name must be a string.',
            ]);

            $order = Blogs::max('position_order');
            $position_order = ($order !== null) ? $order + 1 : 1;
            // $show_in_categories = json_encode($request->show_in_categories);

            if (!empty($request->blog_url)) {
                $link = strtolower($request->blog_url);
            } else {
                $link = strtolower($request->blog_headline);
            }
            $blog_url = $this->checkBlogLink($link);

            $blog = [
                'position_order' => $position_order,
                'blog_headline' => $request->blog_headline,
                'blog_url' => $blog_url,
                'blog_category' => $request->blog_category,
                'short_description' => htmlspecialchars($request->short_description, ENT_QUOTES),
                'description' => htmlspecialchars($request->description, ENT_QUOTES),
                'written_by' => $request->written_by,
                // 'writer_instagram' => $request->writer_instagram,
                // 'writer_linkedin' => $request->writer_linkedin,
                // 'writer_x' => $request->writer_x,
                // 'writer_facebook' => $request->writer_facebook,
                // 'writer_threads' => $request->writer_threads,
                'post_date' => $request->post_date,
                'meta_title' => $request->meta_title,
                'meta_keyword' => $request->meta_keyword,
                'meta_description' => htmlspecialchars($request->meta_description, ENT_QUOTES),
            ];

            if (!empty($request->file('blog_image'))) {
                $path = 'images/blogs/';
                $filePath = $this->storeImage($request->file('blog_image'), $path);
                $blog['blog_image'] = $filePath;
            }
            if (!empty($request->file('writer_image'))) {
                $path = 'images/blogs/writers/';
                $filePath = $this->storeImage($request->file('writer_image'), $path);
                $blog['writer_image'] = $filePath;
            }

            $blog_created = Blogs::create($blog);
            if ($blog_created) {
                $request->session()->flash('success', 'Blog is inserted Successfully!');
                return redirect()->route('manage.blogs');
                //     if ((isset($request->section_titles) && count($request->section_titles) > 0) && (isset($request->section_headlines) && count($request->section_headlines) > 0)) {
                //         DB::beginTransaction();
                //         try {
                //             $total_sections = count($request->section_headlines);
                //             for ($i = 0; $i < $total_sections; $i++) {
                //                 $blog_section = array(
                //                     'blog_id' => $blog_created->id,
                //                     'section_title' => $request->section_titles[$i],
                //                     'section_headline' => $request->section_headlines[$i],
                //                     'description' => htmlspecialchars($request->descriptions[$i]),
                //                 );

                //                 if ($request->hasFile("section_images.$i")) {
                //                     $path = 'images/blogs/sections/';
                //                     $filePath = $this->storeImage($request->file("section_images.$i"), $path);
                //                     $blog_section['section_image'] = $filePath;
                //                 }

                //                 $blog_section_created = BlogSections::create($blog_section);
                //                 if ($blog_section_created) {
                //                     $blog_section_created->update([
                //                         'default_section_name' => 'section_' . $blog_section_created->id
                //                     ]);
                //                 }
                //             }
                //             DB::commit();
                //             $request->session()->flash('success', 'Blog & Sections are inserted Successfully!');
                //             return redirect()->route('manage_blogs');
                //         } catch (\Exception $e) {
                //             DB::rollBack();
                //             $request->session()->flash('error', 'Section Insertion Error: ' . $e->getMessage());
                //             return redirect()->back();
                //         }
                //     }
                // } else {
                //     $request->session()->flash('error', 'Blog Insertion Error!');
                //     return redirect()->back();
            }
        } else {
            $currentPage = "manage_blogs";
            return view('admin.blog-ops', ['currentPage' => $currentPage]);
        }
    }

    public function editBlog(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                // 'blog_category' => 'required',
                'blog_headline' => 'required|string',
                'blog_url' => 'required|string',
                'written_by' => 'string',
            ], [
                // 'blog_category.required' => 'Please provide a category for the blog.',
                'blog_headline.required' => 'Please provide a headline for the blog.',
                'blog_headline.string' => 'Blog headline must be a string.',
                'blog_url.required' => 'Please provide URL for the blog.',
                'blog_url.string' => 'URL must be a string.',
                'written_by.string' => 'The author name must be a string.',
            ]);

            // $show_in_categories = json_encode($request->show_in_categories);

            if (!empty($request->blog_url)) {
                $link = strtolower($request->blog_url);
            } else {
                $link = strtolower($request->blog_headline);
            }
            $blog_url = $this->checkBlogLink($link, $request->blog);

            $blog_id = Crypt::decrypt($request->blog);
            $blog = Blogs::findOrFail($blog_id);
            $blog->blog_headline = $request->blog_headline;
            $blog->blog_url = $blog_url;
            $blog->blog_category = $request->blog_category;
            $blog->short_description = htmlspecialchars($request->short_description, ENT_QUOTES);
            $blog->description = htmlspecialchars($request->description, ENT_QUOTES);
            $blog->written_by = $request->written_by;
            // $blog->writer_instagram = $request->writer_instagram;
            // $blog->writer_linkedin = $request->writer_linkedin;
            // $blog->writer_x = $request->writer_x;
            // $blog->writer_facebook = $request->writer_facebook;
            // $blog->writer_threads = $request->writer_threads;
            $blog->post_date = $request->post_date;
            $blog->meta_title = $request->meta_title;
            $blog->meta_keyword = $request->meta_keyword;
            $blog->meta_description = htmlspecialchars($request->meta_description, ENT_QUOTES);

            if (!empty($request->file('blog_image'))) {
                $path = 'images/blogs/';
                $filePath = $this->storeImage($request->file("blog_image"), $path, $blog->blog_image);
                $blog->blog_image = $filePath;
            }
            if (!empty($request->file('writer_image'))) {
                $path = 'images/blogs/writers/';
                $filePath = $this->storeImage($request->file("writer_image"), $path, $blog->section_image);
                $blog->writer_image = $filePath;
            }

            if ($blog->save()) {
                $request->session()->flash('success', 'Blog is updated Successfully!');
                return redirect()->route('manage.blogs');
                // DB::beginTransaction();
                // try {
                //     if (isset($request->section) && count($request->section) > 0) {
                //         foreach ($request->section as $i => $enc_blog_section) {
                //             $blog_section_id = !empty($enc_blog_section) ? Crypt::decrypt($enc_blog_section) : 0;
                //             if ($blog_section_id == 0) {
                //                 $blog_section = array(
                //                     'blog_id' => $blog_id,
                //                     'section_title' => $request->section_titles[$i],
                //                     'section_headline' => $request->section_headlines[$i],
                //                     'description' => htmlspecialchars($request->descriptions[$i]),
                //                 );

                //                 if ($request->hasFile("section_images.$i")) {
                //                     $path = 'images/blogs/sections/';
                //                     $filePath = $this->storeImage($request->file("section_images.$i"), $path);
                //                     $blog_section['section_image'] = $filePath;
                //                 }

                //                 $blog_section_created = BlogSections::create($blog_section);
                //                 if ($blog_section_created) {
                //                     $blog_section_created->update([
                //                         'default_section_name' => 'section_' . $blog_section_created->id
                //                     ]);
                //                 }
                //             } else {
                //                 $blog_section = BlogSections::findOrFail($blog_section_id);
                //                 $blog_section->section_title = $request->section_titles[$i];
                //                 $blog_section->section_headline = $request->section_headlines[$i];
                //                 $blog_section->description = htmlspecialchars($request->descriptions[$i]);

                //                 if ($request->hasFile("section_images.$i")) {
                //                     $path = 'images/blogs/sections/';
                //                     $filePath = $this->storeImage($request->file("section_images.$i"), $path, $blog_section->section_image);
                //                     $blog_section->section_image = $filePath;
                //                 }

                //                 $blog_section->save();
                //             }
                //         }
                //     }
                //     DB::commit();
                //     $request->session()->flash('success', 'Blog & Sections are updated Successfully!');
                //     return redirect()->route('manage_blogs');
                // } catch (\Exception $e) {
                //     DB::rollBack();
                //     $request->session()->flash('error', 'Section Updation Error: ' . $e->getMessage());
                //     return redirect()->back();
                // }
            } else {
                $request->session()->flash('error', 'Blog Updation Error!');
                return redirect()->back();
            }
        } else {
            $id = Crypt::decrypt($request->blog);
            $blog = Blogs::where('id', $id)->firstOrFail();
            $blog->encrypted_id = $request->blog;

            $currentPage = "manage_blogs";
            return view('admin.blog-ops', ["blog" => $blog, 'currentPage' => $currentPage]);
        }
    }
}
