<?php
namespace App\Http\Controllers\Admin;

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

class PostsController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::with(['category', 'author', 'country'])
            ->when($request->search, fn($q) => $q->where('title', 'like', "%{$request->search}%"))
            ->when($request->category, fn($q) => $q->where('category_id', $request->category))
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->latest('published_at')
            ->paginate(20)
            ->withQueryString();

        $categories = Category::orderBy('name')->get();

        return view('admin.posts.index', compact('posts', 'categories'));
    }

    public function edit(Post $post)
    {
        $post->load(['category', 'tags', 'author']);
        $categories = Category::orderBy('name')->get();
        $authors    = User::whereIn('role', ['author', 'editor', 'super_admin'])
            ->where('is_active', true)->get();

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

    public function update(Request $request, Post $post)
    {
        $data = $request->validate([
            'title'         => 'required|string|max:500',
            'excerpt'       => 'nullable|string',
            'content'       => 'nullable|string',
            'category_id'   => 'required|exists:categories,id',
            'author_id'     => 'nullable|exists:users,id',
            'status'        => 'required|in:draft,published,archived',
            'is_featured'   => 'boolean',
            'is_breaking'   => 'boolean',
            'featured_image'=> 'nullable|string',
        ]);

        $data['is_featured'] = $request->boolean('is_featured');
        $data['is_breaking'] = $request->boolean('is_breaking');

        // Handle image upload
        if ($request->hasFile('image_file')) {
            $path = $request->file('image_file')->store('posts/' . date('Y/m'), 'public');
            $data['featured_image'] = \Storage::disk('public')->url($path);
        }

        $post->update($data);

        return redirect()->route('admin.posts.edit', $post)->with('success', 'Post updated.');
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return redirect()->route('admin.posts.index')->with('success', 'Post deleted.');
    }

    public function toggleFeatured(Post $post)
    {
        $post->update(['is_featured' => !$post->is_featured]);
        return back()->with('success', $post->is_featured ? 'Marked as featured.' : 'Removed from featured.');
    }

    public function toggleBreaking(Post $post)
    {
        $post->update(['is_breaking' => !$post->is_breaking]);
        return back();
    }
}
