<?php


namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Str;

use App\Models\User;
use App\Models\Post;
use App\Models\Tag;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image; // If you use intervention/image

use Illuminate\Support\Facades\Auth;


class PostController extends Controller
{
    public function List()
    {
        $titles = Post::with('author', 'category')->get();
        return view('admin.Post.index', compact('titles'));
    }
    public function Trashed()
    {
        $titles = Post::onlyTrashed()->with('author', 'category')->get();
        return view('admin.Post.index-tras', compact('titles'));
    }
    public function Restore($id)
    {
        $post = Post::withTrashed()->find($id)->restore();
        return redirect()->route('post.list')->with('success', 'Post Restore successfully!');
    }

    public function View($id)
    {
        return 'we are worknin on this section';
        // $blog = Post::with('author', 'category')->where('id', $id)->first();
        // $tags = Tag::where('status', 1)->get();
        // return view('admin.Post.view', compact('blog', 'tags'));
    }

    public function Add()
    {
        $title = "Create Post";
        $categories = Category::where('status', 1)->get();
        $tags = Tag::where('status', 1)->get();
        return view('admin.Post.create', compact('title', 'categories', 'tags'));
    }

    public function storeold(Request $request)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:posts,slug',
            'content' => 'required|string|max:10000',
            'post_image' => 'nullable|image|max:2048',
            // 'featured_image' => 'nullable|image|max:2048|dimensions:max_width=4000,max_height=2000',
            'meta_title' => 'nullable|string|max:255',
            'meta_keywords' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'status' => 'required|in:0,1',
            'is_featured' => 'required|in:0,1',
            'published_at' => 'nullable|date',
            'tag_id' => 'nullable|array',
            'tag_id.*' => 'exists:tags,id',
        ]);

        // Generate slug if not provided
        $slug = Str::slug($request->slug) ?? Str::slug($request->title);
        if (Post::where('slug', $slug)->exists()) {
            return back()->withErrors(['slug' => 'Slug already exists'])->withInput();
        }

        // Handle image
        $imagePath = null;
        if ($request->hasFile('post_image')) {
            $file = $request->file('post_image');
            // list($width, $height) = getimagesize($file->getPathname());
            // if (round($width / $height, 2) !== 2.00) {
            //     return back()->withErrors(['post_image' => 'Image ratio must be 2:1'])->withInput();
            // }
            $filename = "{$slug}.{$file->getClientOriginalExtension()}";
            $file->storeAs('posts', $filename, 'public');
            $imagePath = 'posts/' . $filename;
        }
        //         $imagePath = null;

        // if ($request->hasFile('post_image')) {
        //     $file = $request->file('post_image');
        //     $filename = "{$slug}." . $file->getClientOriginalExtension();

        //     // public/posts folder me move karega
        //     $file->move(public_path('posts'), $filename);

        //     // DB me save hoga
        //     $imagePath = 'posts/' . $filename;
        // }



        // Create post
        $post = Post::create([
            'category_id' => $request->category_id,
            'title' => $request->title,
            'slug' => $slug,
            'post_by' => Auth::id(),
            'content' => $request->content,
            'post_image' => $imagePath,
            'published_at' => $request->published_at,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'meta_keywords' => $request->meta_keywords,
            'status' => $request->status,
            'is_featured' => $request->is_featured,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Attach tags
        if ($request->filled('tag_id')) {
            $post->tags()->attach($request->tag_id);
        }

        return redirect()->route('post.list')->with('success', 'Post created successfully!');
    }
    public function store(Request $request)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:posts,slug',
            'content' => 'required|string|max:10000',
            'post_image' => 'nullable|image|max:2048',
            'meta_title' => 'nullable|string|max:255',
            'meta_keywords' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'status' => 'required|in:0,1',
            'is_featured' => 'required|in:0,1',
            'published_at' => 'nullable|date',
            'tag_id' => 'nullable|array',
            'tag_id.*' => 'exists:tags,id',
        ]);

        // Generate slug if not provided
        $slug = Str::slug($request->slug) ?? Str::slug($request->title);
        if (Post::where('slug', $slug)->exists()) {
            return back()->withErrors(['slug' => 'Slug already exists'])->withInput();
        }

        // Handle image
        $imagePath = null;

        if ($request->hasFile('post_image')) {
            $file = $request->file('post_image');
            // filename
            $filename = $slug . '.' . $file->getClientOriginalExtension();
            // move to public/posts
            $file->move(public_path('posts'), $filename);
            $imagePath = 'posts/' . $filename;
        }

        // Create post
        $post = Post::create([
            'category_id' => $request->category_id,
            'title' => $request->title,
            'slug' => $slug,
            'post_by' => Auth::id(),
            'content' => $request->content,
            'post_image' => $imagePath,
            'published_at' => $request->published_at,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'meta_keywords' => $request->meta_keywords,
            'status' => $request->status,
            'is_featured' => $request->is_featured,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Attach tags
        if ($request->filled('tag_id')) {
            $post->tags()->attach($request->tag_id);
        }

        return redirect()->route('post.list')->with('success', 'Post created successfully!');
    }

    public function edit($id)
    {
        $post = Post::with('tags')->findOrFail($id); // Include tags
        $categories = Category::where('status', 1)->get();
        $tags = Tag::where('status', 1)->get();
        $title = "Edit Post";
        $url = route('edit.post', $id);
        return view('admin.post.edit', compact('title', 'url', 'categories', 'post', 'tags'));
    }

    public function update(Request $request, $id)
    {
        $post = Post::findOrFail($id);
        // Validate request
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:posts,slug,' . $post->id,
            'content' => 'required|string|max:10000',
            'post_image' => 'nullable|image|max:2048',
            'meta_title' => 'nullable|string|max:255',
            'meta_keywords' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'status' => 'required|in:0,1',
            'published_at' => 'nullable|date',
            'tag_id' => 'nullable|array',
            'tag_id.*' => 'exists:tags,id',
        ]);

        // Generate slug if not provided
        $slug = Str::slug($request->slug) ?? Str::slug($request->title);
        if (Post::where('slug', $slug)->where('id', '!=', $post->id)->exists()) {
            return back()->withErrors(['slug' => 'Slug already exists'])->withInput();
        }

        // Handle image replacement
        $imagePath = $post->post_image;

        if ($request->hasFile('post_image')) {
            $file = $request->file('post_image');
            $filename = $slug . '.' . $file->getClientOriginalExtension();
            if ($imagePath && file_exists(public_path($imagePath))) {
                unlink(public_path($imagePath));
            }
            $file->move(public_path('posts'), $filename);
            $imagePath = 'posts/' . $filename;
        }

        // Update post
        $post->update([
            'category_id' => $request->category_id,
            'title' => $request->title,
            'slug' => $slug,
            'content' => $request->content,
            'post_image' => $imagePath,
            'status' => $request->status,
            'is_featured' => $request->is_featured,
            'published_at' => $request->published_at,
            'meta_title' => $request->meta_title,
            'meta_description' => $request->meta_description,
            'meta_keywords' => $request->meta_keywords,
            'updated_at' => now(),
        ]);
        $post->tags()->sync($request->tag_id ?? []);

        return redirect()->route('post.list')->with('success', 'Post updated successfully!');
    }

    public function premanentdestroy($id)
    {
        $post = Post::onlyTrashed()->find($id);

        $imagePath = $post->post_image;

        if ($imagePath && file_exists(public_path($imagePath))) {
            unlink(public_path($imagePath));
        }
        $post->forceDelete();
        // $post->delete();

        return redirect()->route('post.list')->with('success', 'Post permanently deleted successfully!');
    }
    public function destroy($id)
    {
        $post = Post::findOrFail($id);
        $post->delete();
        return redirect()->route('post.list')->with('success', 'Post deleted successfully!');
    }

    public function changeStatusAjax(Request $request)
    {
        $post = Post::findOrFail($request->id);
        $post->status = $post->status == 1 ? 0 : 1;
        $post->save();

        return response()->json([
            'success' => true,
            'status' => $post->status,
            'message' => 'Status updated successfully.',
        ]);
    }
}
