<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Models\Category;
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\Http;
use Illuminate\Support\Facades\Log;
use fivefilters\Readability\Readability;
use fivefilters\Readability\Configuration;
use App\Services\AiService;
use App\Models\AiProvider;

class PostController extends Controller
{
    /**
     * Get categories for the submission form
     */
    public function getCategories(): JsonResponse
    {
        $categories = Category::whereNull('parent_id')
            ->with(['children' => function($query) {
                $query->select('id', 'name', 'parent_id')->orderBy('name');
            }])
            ->select('id', 'name')
            ->orderBy('name')
            ->get();

        return response()->json($categories);
    }

    /**
     * Store a manually submitted post or a fetched post
     */
    public function store(Request $request): JsonResponse
    {
        $submissionEnabled = Setting::where('group', 'post')->where('key', 'submission_enabled')->value('value');
        
        if ($submissionEnabled === 'false' && $request->user()->role !== 'admin') {
            return response()->json(['message' => 'Submissions are currently closed.'], 403);
        }

        $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',
            
            // Mixed Media Validation
            'items'            => 'nullable|array|max:5',
            'items.*.type'     => 'required|in:file,url',
            'items.*.file'     => 'required_if:items.*.type,file|image|max:2048',
            'items.*.url'      => 'required_if:items.*.type,url|url',
            'items.*.caption'  => 'nullable|string|max:255',
            'items.*.is_primary' => 'required', 
        ]);

        $data = $request->only(['title', 'category_id', 'content', 'meta_description']);
        $data['user_id'] = $request->user()->id;
        
        $data['slug'] = Post::generateUniqueSlug($data['title']);

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

        // Auto-Approval Logic
        $autoApproveSetting = Setting::where('group', 'post')->where('key', 'auto_approval')->value('value');
        
        if ($request->user()->role === 'admin') {
            $data['status'] = 'published';
        } else {
            $data['status'] = ($autoApproveSetting === 'true') ? 'published' : 'pending';
        }

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

        // Handle Mixed Media
        if ($request->has('items')) {
            $items = $request->input('items',[]);
            $mainCoverPath = null;

            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("items.$index.file")) {
                        $path = $request->file("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
                    ]);

                    if ($isPrimary) {
                        $mainCoverPath = $finalPath;
                    }
                }
            }

            if (!$mainCoverPath && count($items) > 0) {
                $firstImage = $post->images()->first();
                if ($firstImage) {
                    $mainCoverPath = $firstImage->image_path;
                    $firstImage->update(['is_primary' => true]);
                }
            }

            $post->update(['image_path' => $mainCoverPath]);
        }

        return response()->json([
            'message' => 'News submitted successfully!',
            'post' => $post
        ], 201);
    }

    /**
     * Fetch and extract article content from a given URL
     */
    public function fetchUrl(Request $request, AiService $aiService): JsonResponse
    {
        $quickFetchSetting = Setting::where('group', 'post')->where('key', 'quick_fetch_enabled')->value('value');
        
        if ($quickFetchSetting === 'false' && $request->user()->role !== 'admin') {
            return response()->json(['message' => 'The Quick Fetch tool is currently disabled by the administrator.'], 403);
        }

        $request->validate([
            'url' => 'required|url',
            'rewrite' => 'boolean',
            'prompt' => 'nullable|string' 
        ]);

        $url = $request->url;
        $rewrite = filter_var($request->rewrite, FILTER_VALIDATE_BOOLEAN);
        $customPrompt = $request->input('prompt'); 

        $parsedUrl = parse_url($url);
        $sourceDomain = isset($parsedUrl['host']) ? str_ireplace('www.', '', $parsedUrl['host']) : 'External Source';

        try {
            $response = Http::withHeaders([
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            ])->timeout(15)->withoutVerifying()->get($url);

            if ($response->failed()) {
                return response()->json(['message' => 'Failed to fetch the article (HTTP ' . $response->status() . ').'], 400);
            }

            $html = $response->body();
            if (empty($html)) {
                return response()->json(['message' => 'The provided URL returned empty content.'], 400);
            }

            $configuration = new Configuration();
            $configuration->setFixRelativeUrls(true); 
            $configuration->setOriginalUrl($url);
            $readability = new Readability($configuration);

            if ($readability->parse($html)) {
                
                $title = (string) $readability->getTitle();
                $content = (string) $readability->getContent();
                $image = $readability->getImage();

                if (empty($title)) $title = 'Fetched Article';

                if ($rewrite) {
                    $provider = AiProvider::where('is_active', true)->where('is_enabled', true)->first();
                    
                    if (!$provider) {
                        return response()->json([
                            'message' => 'AI Provider is not active. Using original content.', 
                            'title' => Str::limit(strip_tags($title), 200), 
                            'content' => $content, 
                            'image' => $image,
                            'source_domain' => $sourceDomain 
                        ]);
                    }

                    try {
                        $aiResult = $aiService->rewrite($content, $customPrompt);

                        if (is_array($aiResult) && isset($aiResult['skip'])) {
                            throw new \Exception("AI rejected the content: " . ($aiResult['reason'] ?? 'Unknown'));
                        }

                        if (is_array($aiResult)) {
                            $title = $aiResult['title'] ?? $title;
                            $content = $aiResult['content'] ?? $content;
                        } elseif (is_string($aiResult) && !empty($aiResult)) {
                            $content = $aiResult;
                        }
                    } catch (\Exception $aiError) {
                        return response()->json(['message' => 'AI Rewrite Failed: ' . $aiError->getMessage()], 422);
                    }
                }

                $title = Str::limit(strip_tags($title), 200);

                return response()->json([
                    'title' => $title,
                    'content' => $content, 
                    'image' => $image,     
                    'source_domain' => $sourceDomain, 
                    'message' => $rewrite ? 'Article fetched and rewritten via AI!' : 'Article fetched successfully!'
                ]);
            }

            return response()->json(['message' => 'Could not extract readable content from this URL.'], 400);

        } catch (\Exception $e) {
            Log::error('Fetch URL Error: ' . $e->getMessage());
            return response()->json(['message' => 'Server Error: ' . $e->getMessage()], 500);
        }
    }
}