<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostImage;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Gate;

class MyPostController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = $request->user()->posts()->with('category');
        if ($status = $request->input('status')) {
            if ($status !== 'all') $query->where('status', $status);
        }
        return response()->json($query->latest()->paginate(10));
    }

    public function update(Request $request, Post $post): JsonResponse
    {
        Gate::authorize('update', $post);

        // 1. Validation
        $request->validate([
            'title'             => 'required|string|max:255',
            'meta_description'  => 'required|string|max:160',
            'category_id'       => 'required|exists:categories,id',
            'content'           => 'required|string',
            'tags'              => 'nullable|string',
            
            // Image Logic
            'deleted_image_ids' => 'nullable|array',         
            'existing_captions' => 'nullable|array',         
            'primary_existing_id' => 'nullable|integer', 
            
            // Mixed Items (Files or URLs)
            'new_items'         => 'nullable|array|max:5',
            'new_items.*.type'  => 'required|in:file,url',
            'new_items.*.file'  => 'required_if:new_items.*.type,file|image|max:2048',
            'new_items.*.url'   => 'required_if:new_items.*.type,url|url',
            'new_items.*.caption' => 'nullable|string',
            'new_items.*.is_primary' => 'required', // "true"/"false"
        ]);

        $data = $request->only(['title', 'category_id', 'content', 'meta_description']);
        
        $autoApprove = Setting::where('group', 'post')->where('key', 'auto_approval')->value('value');
        if ($request->user()->role !== 'admin') {
            $data['status'] = ($autoApprove === 'true') ? 'published' : 'pending';
        }

        if ($post->title !== $data['title']) {
            $data['slug'] = Post::generateUniqueSlug($data['title'], $post->id);
        }

        // Tags Update
        if ($request->filled('tags')) {
            $data['tags'] = json_decode($request->tags, true);
        } else {
            $data['tags'] = null;
        }

        $post->update($data);

        if ($request->filled('deleted_image_ids')) {
            $imagesToDelete = PostImage::whereIn('id', $request->deleted_image_ids)
                ->where('post_id', $post->id)
                ->get();

            foreach ($imagesToDelete as $img) {
                if ($img->image_path && str_contains($img->image_path, '/storage/')) {
                    $relativePath = str_replace('/storage/', '', $img->image_path);
                    Storage::disk('public')->delete($relativePath);
                }
                $img->delete();
            }
        }

        $post->images()->update(['is_primary' => false]);

        if ($request->filled('existing_captions')) {
            foreach ($request->existing_captions as $id => $caption) {
                PostImage::where('id', $id)
                    ->where('post_id', $post->id)
                    ->update(['caption' => $caption]);
            }
        }

        if ($request->filled('primary_existing_id')) {
            PostImage::where('id', $request->primary_existing_id)
                ->where('post_id', $post->id)
                ->update(['is_primary' => true]);
        }

        if ($request->has('new_items')) {
            $items = $request->input('new_items',[]); 
            
            foreach ($items as $index => $itemData) {
                $type = $itemData['type'];
                $caption = $itemData['caption'] ?? null;
                $isPrimary = filter_var($itemData['is_primary'], FILTER_VALIDATE_BOOLEAN);
                $finalPath = null;

                if ($type === 'file') {
                    if ($request->hasFile("new_items.$index.file")) {
                        $path = $request->file("new_items.$index.file")->store('posts', 'public');
                        $finalPath = '/storage/' . $path;
                    }
                } else {
                    $finalPath = $itemData['url'] ?? null;
                }

                if ($finalPath) {
                    PostImage::create([
                        'post_id' => $post->id,
                        'image_path' => $finalPath,
                        'caption' => $caption,
                        'is_primary' => $isPrimary
                    ]);
                }
            }
        }

        // 5. Sync Parent Post `image_path`
        $primaryImage = $post->images()->where('is_primary', true)->first();
        if (!$primaryImage) {
            $primaryImage = $post->images()->first();
            if ($primaryImage) {
                $primaryImage->update(['is_primary' => true]);
            }
        }

        $post->update(['image_path' => $primaryImage ? $primaryImage->image_path : null]);
        
        $message = ($post->status === 'pending') 
            ? 'Post updated and submitted for review.' 
            : 'Post updated successfully.';

        return response()->json(['message' => $message]);
    }

    public function destroy(Post $post): JsonResponse
    {
        Gate::authorize('delete', $post);
        
        foreach ($post->images as $img) {
            if ($img->image_path && str_contains($img->image_path, '/storage/')) {
                $relativePath = str_replace('/storage/', '', $img->image_path);
                Storage::disk('public')->delete($relativePath);
            }
        }

        $post->delete();
        return response()->json(null, 204);
    }
}