<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Post;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $title = 'Posts';
        $posts = Post::orderBy('id', 'desc')->with(['user', 'category'])->latest()->paginate(10);
        return view('admin.posts.index', compact('title', 'posts'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $title = 'Create Post';
        $categories = Category::all();
        return view('admin.posts.create', compact('title', 'categories'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|min:3|max:255',
            'slug' => 'required|string|max:255|unique:posts,slug',
            'category_id' => 'required|exists:categories,id',

        ]);

        $data['user_id'] = auth()->id();

        $post = Post::create($data);

        session()->flash('swal', [
            'icon' => 'success',
            'title' => __('Success'),
            'text' => __('Post created successfully.'),
            'timer' => 2500,
            'showConfirmButton' => false,
        ]);

        return redirect()->route('admin.posts.edit', $post->id);
    }

    /**
     * Display the specified resource.
     */
    public function show(Post $post)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Post $post)
    {
        $title = 'Edit Post';
        $categories = Category::all();
        $tags = Tag::all();

        return view('admin.posts.edit', compact('title', 'post', 'categories', 'tags'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Post $post)
    {
        $data = $request->validate([
            'title' => 'required|string|min:3|max:255',
            'slug' => 'required|string|max:255|unique:posts,slug,' . $post->id,
            'category_id' => 'required|exists:categories,id',
            'excerpt' => 'nullable',
            'content' => 'nullable',
            'image' => 'nullable|image',
            'tags' => 'nullable|array',
            'tags.*' => 'exists:tags,id',
            'is_published' => 'required|boolean',
        ]);

        if ($request->hasFile('image')) {
            // Delete the old image if it exists
            if ($post->image_path) {
                Storage::delete($post->image_path);
            }
            // Store the new image
            $data['image_path'] = Storage::put('posts', $request->image);
        }

        $post->update($data);

        // Sync tags if provided
        if (isset($data['tags'])) {
            $post->tags()->sync($data['tags']);
        } else {
            $post->tags()->detach();
        }

        // Flash success message
        session()->flash('swal', [
            'icon' => 'success',
            'title' => __('Success'),
            'text' => __('Post updated successfully.'),
            'timer' => 2500,
            'showConfirmButton' => false,
        ]);

        return redirect()->route('admin.posts.edit', $post->id);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Post $post)
    {
        if ($post->image_path) {
            Storage::delete($post->image_path);
        }

        // Delete the post
        $post->delete();

        session()->flash('swal', [
            'icon' => 'success',
            'title' => __('Success'),
            'text' => __('Post deleted successfully.'),
            'timer' => 2500,
            'showConfirmButton' => false,
        ]);
        return redirect()->route('admin.posts.index');
    }
}
