<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Http\Requests\Member\RateDocumentRequest;
use App\Http\Requests\Member\StoreDocumentRequest;
use App\Http\Requests\Member\StoreShareKnowledgeRequest;
use App\Models\Document;
use App\Models\ForumPost;
use App\Services\Member\ShareKnowledgeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Inertia\Inertia;
use Inertia\Response as InertiaResponse;

// ══════════════════════════════════════════════════════════════════
//  InPractice — Member\ShareKnowledgeController
//  Location: app/Http/Controllers/Member/ShareKnowledgeController.php
//
//  Thin controller — Bible compliant.
//  Every method: receive → call service → return response.
//  Zero business logic.
//
//  Routes:
//    GET    /app/share-knowledge                index
//    GET    /app/share-knowledge/create-post    createPost
//    POST   /app/share-knowledge/posts          storePost
//    GET    /app/share-knowledge/upload         createDocument
//    POST   /app/share-knowledge/documents      storeDocument
//    GET    /app/share-knowledge/documents/{d}  showDocument
//    GET    /app/share-knowledge/documents/{d}/download  download
//    PATCH  /app/share-knowledge/documents/{d}/rate      rate → JSON
//    GET    /app/go                             externalRedirect
// ══════════════════════════════════════════════════════════════════

class ShareKnowledgeController extends Controller
{
    public function __construct(
        private readonly ShareKnowledgeService $shareService
    ) {}

    /**
     * Share Knowledge landing — combined feed of posts + documents.
     * GET /app/share-knowledge
     */
    public function index(Request $request): InertiaResponse
    {
        $data = $this->shareService->index(
            $request->user(),
            $request->only(['hub_id', 'type', 'search'])
        );

        return Inertia::render('Member/ShareKnowledge/Index', $data);
    }

    /**
     * Create text post form.
     * GET /app/share-knowledge/create-post
     */
    public function createPost(): InertiaResponse
    {
        return Inertia::render('Member/ShareKnowledge/CreatePost');
    }

    /**
     * Store new text post.
     * POST /app/share-knowledge/posts
     */
    public function storePost(StoreShareKnowledgeRequest $request): RedirectResponse
    {
        $post = $this->shareService->createPost($request->user(), $request->validated());

        return redirect()->route('member.forum.show', $post->id)
                         ->with('success', __('forum.knowledge_shared'));
    }

    /**
     * Upload PDF form.
     * GET /app/share-knowledge/upload
     */
    public function createDocument(): InertiaResponse
    {
        return Inertia::render('Member/ShareKnowledge/CreateDocument',
            $this->shareService->createDocument()
        );
    }

    /**
     * Store uploaded PDF document.
     * POST /app/share-knowledge/documents
     */
    public function storeDocument(StoreDocumentRequest $request): RedirectResponse
    {
        $document = $this->shareService->uploadDocument(
            $request->user(),
            $request->validated(),
            $request->file('file')
        );

        return redirect()->route('member.share.index')
                         ->with('success', __('documents.upload_success'));
    }

    /**
     * Show single document.
     * GET /app/share-knowledge/documents/{document}
     */
    public function showDocument(Document $document): InertiaResponse
    {
        $data = $this->shareService->showDocument(auth()->user(), $document);

        return Inertia::render('Member/ShareKnowledge/ShowDocument', $data);
    }

    /**
     * Download PDF — increments counter, streams file.
     * GET /app/share-knowledge/documents/{document}/download
     */
    public function download(Document $document): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $path = $this->shareService->download(auth()->user(), $document);

        return Response::download($path, $document->original_filename);
    }

    /**
     * Stream PDF inline for the viewer iframe — no forced download.
     * GET /app/share-knowledge/documents/{document}/preview
     */
    public function preview(Document $document): \Symfony\Component\HttpFoundation\Response
    {
        abort_if($document->status === 'rejected', 404);

        $path = \Illuminate\Support\Facades\Storage::disk('public')->path($document->file_path);
        abort_if(! file_exists($path), 404);

        return response()->file($path, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . $document->original_filename . '"',
        ]);
    }

    /**
     * Rate a document 1–5 stars — JSON, no page reload.
     * PATCH /app/share-knowledge/documents/{document}/rate
     */
    public function rate(RateDocumentRequest $request, Document $document): JsonResponse
    {
        $result = $this->shareService->rateDocument(
            $request->user(),
            $document,
            (int) $request->validated('rating')
        );

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

    /**
     * External link redirect warning page.
     * GET /app/go?url=https://...
     *
     * Every external URL shared on the platform goes through here.
     * Member sees a warning before leaving InPractice.
     */
    public function externalRedirect(Request $request): InertiaResponse
    {
        $url = $request->query('url', '');

        // Basic safety — must be a valid http/https URL
        if (! filter_var($url, FILTER_VALIDATE_URL) ||
            ! in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) {
            abort(400, 'Invalid URL');
        }

        return Inertia::render('Member/ShareKnowledge/ExternalRedirect', [
            'url' => $url,
        ]);
    }

    public function destroyDocument(Document $document): RedirectResponse
    {
        $this->shareService->deleteDocument(auth()->user(), $document);
        return redirect()->route('member.share.index')
                        ->with('success', __('documents.deleted'));
    }
}