<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use App\Models\Sale\Sale;
use App\Models\Sale\SaleActivity;
use App\Models\Sale\SaleOfferDocument;
use App\Services\Sale\SaleDocumentRenderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Teklif belgesi (teklif mektubu): oluşturma, listeleme, PDF/Word indirme.
 * Mail / mesaj gönderimi ilgili modüller hazır olduğunda bağlanacak.
 */
class SaleOfferDocumentController extends Controller
{
    public function __construct(private SaleDocumentRenderService $renderer)
    {
    }

    private function authorizeSale(Sale $sale): void
    {
        abort_unless((int) $sale->agency_id === (int) Auth::user()->currentAgencyId(), 403, 'Bu işlem için yetkiniz yok.');
    }

    /** Satışın belgeleri (modal listesi için). */
    public function index(Sale $sale)
    {
        $this->authorizeSale($sale);

        return response()->json([
            'success' => true,
            'documents' => $this->documentsPayload($sale),
            'next_number' => $this->renderer->nextNumber($sale->agency),
        ]);
    }

    /** Belge oluştur: içerik o anki şablon + satış verisiyle sabitlenir. */
    public function store(Request $request, Sale $sale)
    {
        $this->authorizeSale($sale);

        $validated = $request->validate([
            'document_number' => 'nullable|string|max:100',
        ]);

        $number = trim((string) ($validated['document_number'] ?? ''))
            ?: $this->renderer->nextNumber($sale->agency);

        $sale->loadMissing(['agency', 'customer', 'items', 'assignedAgent']);

        $document = SaleOfferDocument::create([
            'agency_id' => $sale->agency_id,
            'sale_id' => $sale->id,
            'created_by' => Auth::id(),
            'document_number' => $number,
            'title' => 'Teklif Belgesi ' . $number,
            'content' => $this->renderer->render($sale, $number),
        ]);

        SaleActivity::create([
            'agency_id' => $sale->agency_id,
            'sale_id' => $sale->id,
            'performed_by' => Auth::id(),
            'activity_type' => 'note',
            'subject' => 'Teklif Belgesi Oluşturuldu',
            'description' => "<b>{$number}</b> numaralı teklif belgesi oluşturuldu.",
            'metadata' => ['sale_offer_document_id' => $document->id],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Belge oluşturuldu: ' . $number,
            'document' => $this->documentPayload($document),
            'next_number' => $this->renderer->nextNumber($sale->agency),
            'documents' => $this->documentsPayload($sale),
        ]);
    }

    /** Belgeyi PDF veya Word olarak indir. */
    public function download(Sale $sale, SaleOfferDocument $document, Request $request)
    {
        $this->authorizeSale($sale);
        abort_if($document->sale_id !== $sale->id, 404);

        $format = $request->get('format', 'pdf');
        $slug = preg_replace('/[^A-Za-z0-9\-_]/', '-', $document->document_number) ?: 'belge';

        if ($format === 'word') {
            return response($this->renderer->wordFromHtml($document->content))
                ->header('Content-Type', 'application/msword; charset=UTF-8')
                ->header('Content-Disposition', 'attachment; filename="teklif-belgesi-' . $slug . '.doc"');
        }

        $pdf = $this->renderer->pdfFromHtml($document->content);
        if ($pdf === null) {
            // PDF kütüphanesi yoksa HTML olarak gösterilir (yazdırılabilir)
            return response($document->content)->header('Content-Type', 'text/html; charset=UTF-8');
        }

        return response($pdf)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="teklif-belgesi-' . $slug . '.pdf"');
    }

    /** Belge önizleme (tarayıcıda HTML). */
    public function preview(Sale $sale, SaleOfferDocument $document)
    {
        $this->authorizeSale($sale);
        abort_if($document->sale_id !== $sale->id, 404);

        return response($document->content)->header('Content-Type', 'text/html; charset=UTF-8');
    }

    public function destroy(Sale $sale, SaleOfferDocument $document)
    {
        $this->authorizeSale($sale);
        abort_if($document->sale_id !== $sale->id, 404);

        $number = $document->document_number;
        $document->delete();

        SaleActivity::create([
            'agency_id' => $sale->agency_id,
            'sale_id' => $sale->id,
            'performed_by' => Auth::id(),
            'activity_type' => 'note',
            'subject' => 'Teklif Belgesi Silindi',
            'description' => "<b>{$number}</b> numaralı teklif belgesi silindi.",
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Belge silindi.',
            'documents' => $this->documentsPayload($sale),
            'next_number' => $this->renderer->nextNumber($sale->agency),
        ]);
    }

    // ─── Yardımcılar ──────────────────────────────────────────────────────────

    private function documentsPayload(Sale $sale): array
    {
        return $sale->offerDocuments()->with('creator:id,first_name,last_name')->get()
            ->map(fn (SaleOfferDocument $d) => $this->documentPayload($d))
            ->all();
    }

    private function documentPayload(SaleOfferDocument $d): array
    {
        return [
            'id' => $d->id,
            'number' => $d->document_number,
            'date' => $d->created_at?->format('d.m.Y H:i'),
            'creator' => $d->creator->full_name ?? null,
            'preview_url' => route('agency.sales.offer-documents.preview', [$d->sale_id, $d->id]),
            'pdf_url' => route('agency.sales.offer-documents.download', [$d->sale_id, $d->id]) . '?format=pdf',
            'word_url' => route('agency.sales.offer-documents.download', [$d->sale_id, $d->id]) . '?format=word',
        ];
    }
}
