<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\Models\Post;
use AleshaCMS\Models\CMS\ContentType;
use AleshaCMS\Models\CMS\AuditLog;
use AleshaCMS\Models\CMS\Taxonomy;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PostController extends Controller
{
    public function index(Request $request, string $type = 'post')
    {
        $posts = Post::ofType($type)
            ->with('author')
            ->when($request->search, fn($q) => $q->where('title', 'like', "%{$request->search}%"))
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->latest()
            ->paginate(20);

        $contentType = ContentType::where('slug', $type)->first();

        if ($request->wantsJson()) {
            return response()->json([
                'data' => $posts->map(fn($p) => [
                    'id'         => $p->id,
                    'title'      => $p->title,
                    'slug'       => $p->slug,
                    'type'       => $p->content_type,
                    'status'     => $p->status,
                    'author'     => $p->author->name,
                    'created_at' => $p->created_at->format('M d, Y'),
                    'edit_url'   => route('admin.posts.edit', [$type, $p->id]),
                ]),
                'meta' => [
                    'current_page' => $posts->currentPage(),
                    'last_page'    => $posts->lastPage(),
                    'total'        => $posts->total(),
                    'per_page'     => $posts->perPage(),
                ],
            ]);
        }

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

    public function create(string $type = 'post')
    {
        $contentType = ContentType::where('slug', $type)->first();
        $categories  = Taxonomy::where('type', 'category')->get();
        $tags        = Taxonomy::where('type', 'tag')->get();
        return view('admin.posts.create', compact('type', 'contentType', 'categories', 'tags'));
    }

    public function store(Request $request, string $type = 'post')
    {
        if (is_string($request->page_builder)) {
            $request->merge(['page_builder' => json_decode($request->page_builder, true) ?? null]);
        }

        $data = $request->validate([
            'title'                   => 'required|string|max:255',
            'slug'                    => 'nullable|string|max:255|unique:posts',
            'content'                 => 'nullable|string',
            'excerpt'                 => 'nullable|string',
            'status'                  => 'required|in:draft,published,scheduled',
            'published_at'            => 'required|date',
            'seo'                     => 'nullable|array',
            'custom_fields'           => 'nullable|array',
            'page_builder'            => 'nullable|array',
            'builder_fullpage'        => 'nullable|boolean',
            'featured_image_caption'  => 'nullable|string|max:500',
        ]);

        $data['slug']             = $data['slug'] ?? Str::slug($data['title']);
        $data['user_id']          = auth()->id();
        $data['content_type']     = $type;
        $data['content']          = isset($data['content']) ? clean($data['content']) : null;
        $data['builder_fullpage'] = (bool)$request->input('builder_fullpage', false);

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

        if ($request->hasFile('featured_image')) {
            $post->addMedia($request->file('featured_image'))
                ->withCustomProperties(['caption' => $request->input('featured_image_caption', '')])
                ->toMediaCollection('featured');
        }

        if ($request->has('taxonomies')) {
            $post->taxonomies()->sync($request->input('taxonomies', []));
        }

        AuditLog::log('post.created', $post, [], $post->toArray());

        if ($request->wantsJson()) {
            return response()->json([
                'success'  => true,
                'message'  => 'Content saved.',
                'redirect' => route('admin.posts.index', $type),
            ]);
        }

        return redirect()->route('admin.posts.index', $type)
            ->with('success', 'Content saved.');
    }

    public function edit(string $type, Post $post)
    {
        $contentType      = ContentType::where('slug', $type)->first();
        $categories       = Taxonomy::where('type', 'category')->get();
        $tags             = Taxonomy::where('type', 'tag')->get();
        $selectedTaxonomy = $post->taxonomies->pluck('id')->toArray();
        return view('admin.posts.edit', compact('post', 'type', 'contentType', 'categories', 'tags', 'selectedTaxonomy'));
    }

    public function update(Request $request, string $type, Post $post)
    {
        if (is_string($request->page_builder)) {
            $request->merge(['page_builder' => json_decode($request->page_builder, true) ?? null]);
        }

        $data = $request->validate([
            'title'                   => 'required|string|max:255',
            'slug'                    => 'nullable|string|max:255|unique:posts,slug,' . $post->id,
            'content'                 => 'nullable|string',
            'excerpt'                 => 'nullable|string',
            'status'                  => 'required|in:draft,published,scheduled',
            'published_at'            => 'required|date',
            'seo'                     => 'nullable|array',
            'custom_fields'           => 'nullable|array',
            'page_builder'            => 'nullable|array',
            'builder_fullpage'        => 'nullable|boolean',
            'featured_image_caption'  => 'nullable|string|max:500',
        ]);

        $data['slug']             = $data['slug'] ?? Str::slug($data['title']);
        $data['content']          = isset($data['content']) ? clean($data['content']) : null;
        $data['builder_fullpage'] = (bool)$request->input('builder_fullpage', false);
        $old = $post->toArray();
        $post->update($data);

        if ($request->hasFile('featured_image')) {
            $post->clearMediaCollection('featured');
            $post->addMedia($request->file('featured_image'))
                ->withCustomProperties(['caption' => $request->input('featured_image_caption', '')])
                ->toMediaCollection('featured');
        } elseif ($request->filled('featured_image_caption')) {
            $featuredMedia = $post->getFirstMedia('featured');
            if ($featuredMedia) {
                $featuredMedia->setCustomProperty('caption', $request->input('featured_image_caption'));
                $featuredMedia->save();
            }
        }

        $post->taxonomies()->sync($request->input('taxonomies', []));

        AuditLog::log('post.updated', $post, $old, $post->fresh()->toArray());

        if ($request->wantsJson()) {
            return response()->json([
                'success'  => true,
                'message'  => 'Content updated.',
                'redirect' => route('admin.posts.index', $type),
            ]);
        }

        return redirect()->route('admin.posts.index', $type)
            ->with('success', 'Content updated.');
    }

    public function destroy(string $type, Post $post)
    {
        AuditLog::log('post.deleted', $post, $post->toArray());
        $post->delete();

        if (request()->wantsJson()) {
            return response()->json(['success' => true]);
        }

        return redirect()->route('admin.posts.index', $type)->with('success', 'Deleted.');
    }
}
