<?php

namespace App\Http\Controllers\Admin;

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

class PostController extends Controller
{
    /**
     * Display a listing of the posts.
     */
    public function index()
    {
        $posts = Post::latest()->paginate(10);
        return view('admin.posts.index', compact('posts'));
    }

    /**
     * Show the form for creating a new post.
     */
    public function create()
    {
        $post = new Post();
        return view('admin.posts.form', compact('post'));
    }

    /**
     * Store a newly created post in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'image_path' => 'nullable|string|max:255',
            'is_published' => 'boolean',
        ]);

        $post = new Post();
        $post->title = $validated['title'];
        $post->slug = Str::slug($validated['title']);
        $post->content = $validated['content'];
        $post->is_published = $request->boolean('is_published');
        
        if ($post->is_published) {
            $post->published_at = now();
        }

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/posts'), $filename);
            $post->image_path = 'uploads/posts/' . $filename;
        } elseif ($request->filled('image_path')) {
            $post->image_path = $request->image_path;
        }

        $post->save();

        return redirect()->route('admin.posts.index')->with('success', 'Post created successfully.');
    }

    /**
     * Show the form for editing the specified post.
     */
    public function edit(Post $post)
    {
        return view('admin.posts.form', compact('post'));
    }

    /**
     * Update the specified post in storage.
     */
    public function update(Request $request, Post $post)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'image_path' => 'nullable|string|max:255',
            'is_published' => 'boolean',
        ]);

        $post->title = $validated['title'];
        
        // Only update slug if title changed significantly to preserve SEO, or simplify and just update
        if ($post->isDirty('title')) {
            $post->slug = Str::slug($validated['title']);
        }

        $post->content = $validated['content'];
        
        // Handle publish date setting
        $willBePublished = $request->boolean('is_published');
        if ($willBePublished && !$post->is_published) {
            $post->published_at = now();
        } elseif (!$willBePublished) {
            $post->published_at = null;
        }
        $post->is_published = $willBePublished;

        if ($request->hasFile('image')) {
            // Delete old file if it was a direct upload (optional, maybe keep it if it's in media library?)
            // For now, let's only delete if it was in uploads/posts to avoid deleting shared media
            if ($post->image_path && Str::startsWith($post->image_path, 'uploads/posts/') && file_exists(public_path($post->image_path))) {
                @unlink(public_path($post->image_path));
            }

            $file = $request->file('image');
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/posts'), $filename);
            $post->image_path = 'uploads/posts/' . $filename;
        } elseif ($request->filled('image_path')) {
            $post->image_path = $request->image_path;
        }

        $post->save();

        return redirect()->route('admin.posts.index')->with('success', 'Post updated successfully.');
    }

    /**
     * Remove the specified post from storage.
     */
    public function destroy(Post $post)
    {
        if ($post->image_path && file_exists(public_path($post->image_path))) {
            @unlink(public_path($post->image_path));
        }
        
        $post->delete();

        return redirect()->route('admin.posts.index')->with('success', 'Post deleted successfully.');
    }
}
