<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\ParentCategory;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;

class PostController extends Controller
{
    public function addPost(Request $request)
    {
        $categories_html = '';
        $pcategories = ParentCategory::whereHas('children')->orderBy('name', 'asc')->get();
        $categories = Category::where('parent', 0)->orderBy('name', 'asc')->get();
        if (count($pcategories) > 0) {

            foreach ($pcategories as $item) {
                $categories_html .= '<optgroup label="' . $item->name . '">';
                foreach ($item->children as $category) {
                    $categories_html .= '<option value="' . $category->id . '">' . $category->name . '</option>';
                }
                $categories_html .= '</optgroup>';
            }
        }

        if (count($categories) > 0) {
            foreach ($categories as $item) {
                $categories_html .= '<option value="' . $item->id . '">' . $item->name . '</option>';
            }
        }

        $data = [
            'pageTitle' => 'Add new post',
            'categories_html' => $categories_html
        ];
        return view('back.pages.post.add_post', $data);
    }


    public function createPost(Request $request)
    {
        $request->validate([
            'title' => 'required|unique:posts,title',
            'content' => 'required',
            'category' => 'required|exists:categories,id',
            'featured_image' => 'nullable|mimes:png,jpg,jpeg|max:3072',
        ]);

        if ($request->hasFile('featured_image')) {
            $file = $request->file('featured_image');
            $path = 'images/posts/';
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path($path), $filename);

            $resized_path = $path . 'resized/';
            if (!File::isDirectory($resized_path)) {
                File::makeDirectory($resized_path, 0777, true, true);
            }
            Image::make($path . $filename)
                ->fit(250, 250)->save($resized_path . 'thumb_' . $filename);
            Image::make($path . $filename)
                ->fit(512, 320)->save($resized_path . 'resized_' . $filename);
            // Mass assignment for creating a post
            $post = Post::create([
                'author_id' => Auth::id(),
                'category' => $request->category,
                'title' => $request->title,
                'content' => $request->content,
                'featured_image' => $filename,
                'tags' => $request->tags,
                'meta_keywords' => $request->meta_keywords,
                'meta_description' => $request->meta_description,
                'visibility' => $request->visibility,
            ]);

            if ($post) {
                return response()->json(['status' => 1, 'message' => 'New post has been successfully created.']);
            } else {
                return response()->json(['status' => 0, 'message' => 'Something went wrong.']);
            }
        } else {
            return response()->json(['status' => 0, 'message' => 'Featured image is required.']);
        }
    }

    public function allPost(Request $request)
    {
        $data = [
            'pageTitle' => 'Posts',
        ];
        return view('back.pages.post.posts', $data);
    }

    public function editPost(Request $request, $id = null)
    {
        $post = Post::findOrFail($id);
        $categories_html = '';
        $pcategories = ParentCategory::whereHas('children')->orderBy('name', 'asc')->get();
        $categories = Category::where('parent', 0)->orderBy('name', 'asc')->get();
        if (count($pcategories) > 0) {

            foreach ($pcategories as $item) {
                $categories_html .= '<optgroup label="' . $item->name . '">';
                foreach ($item->children as $category) {
                    $selected = $category->id == $post->category ? 'selected' : '';
                    $categories_html .= '<option value="' . $category->id . '"' . $selected . '>' . $category->name . '</option>';
                }
                $categories_html .= '</optgroup>';
            }
        }
        if (count($categories) > 0) {
            foreach ($categories as $item) {
                $selected = $item->id == $post->category ? 'selected' : '';
                $categories_html .= '<option value="' . $item->id . '"' . $selected . '>' . $item->name . '</option>';
            }
        }
        $data = [
            'pageTitle' => 'Edit',
            'post' => $post,
            'categories_html' => $categories_html
        ];

        return view('back.pages.post.edit_post', $data);
    }

    public function updatePost(Request $request)
    {
        $post = Post::findOrFail($request->post_id);
        $featured_image_name = $post->featured_image;
    
        $request->validate([
            'title' => 'required|unique:posts,title,' . $post->id,
            'content' => 'required',
            'category' => 'required|exists:categories,id',
            'featured_image' => 'nullable|mimes:jpeg,jpg,png|max:3072'
        ]);
    
        if ($request->hasFile('featured_image')) {
            $old_featured_image = $post->featured_image;
            $path = public_path('images/posts/');
            $file = $request->file('featured_image');
            $filename = time() . '_' . $file->getClientOriginalName();
    
            // Save original
            $file->move($path, $filename);
    
            // Save resized versions
            $resized_path = $path . 'resized/';
            if (!File::exists($resized_path)) {
                File::makeDirectory($resized_path, 0755, true);
            }
    
            Image::make($path . $filename)->fit(250, 250)->save($resized_path . 'thumb_' . $filename);
            Image::make($path . $filename)->fit(512, 320)->save($resized_path . 'resized_' . $filename);
    
            // Delete old images
            if ($old_featured_image && File::exists($path . $old_featured_image)) {
                File::delete($path . $old_featured_image);
                File::delete($resized_path . 'thumb_' . $old_featured_image);
                File::delete($resized_path . 'resized_' . $old_featured_image);
            }
    
            $featured_image_name = $filename;
        }
    
        $updated = $post->update([
            'author_id' => Auth::id(),
            'category' => $request->category,
            'title' => $request->title,
            'content' => $request->content,
            'featured_image' => $featured_image_name,
            'tags' => $request->tags,
            'meta_keywords' => $request->meta_keywords,
            'meta_description' => $request->meta_description,
            'visibility' => $request->visibility,
        ]);
    
        if ($updated) {
            return response()->json(['status' => 1, 'message' => 'Blog post has been successfully updated.']);
        } else {
            return response()->json(['status' => 0, 'message' => 'Something went wrong.']);
        }
    }
    
}
