<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Barryvdh\DomPDF\Facade\Pdf;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class InvoiceController extends Controller
{
    public function createDownloadLink(Request $request, Order $order): JsonResponse
    {
        if ($order->user_id !== $request->user()->id) {
            abort(404);
        }

        $url = url('/api/v1/orders/' . $order->id . '/invoice/download');

        return response()->json([
            'data' => ['download_url' => $url],
            'message' => __('Lien de facture généré.'),
        ]);
    }

    public function download(Request $request, Order $order): Response
    {
        if ($order->user_id !== $request->user()->id) {
            abort(404);
        }

        $order->load('items', 'address', 'user');
        $invoiceNumber = $this->invoiceNumber($order);
        $issuedAt = now();
        $brandColor = (string) config('invoice.brand_color', '#ffa000');
        $brandName = (string) config('invoice.brand_name', 'Caddies+');
        $logoDataUri = $this->logoDataUri();
        $qrDataUri = $this->qrDataUri($order, $invoiceNumber, $issuedAt);

        $pdf = Pdf::loadView('invoices.order', [
            'order' => $order,
            'issuedAt' => $issuedAt,
            'invoiceNumber' => $invoiceNumber,
            'brandColor' => $brandColor,
            'brandName' => $brandName,
            'logoDataUri' => $logoDataUri,
            'qrDataUri' => $qrDataUri,
        ])->setPaper('a4');

        return $pdf->download('facture-' . $invoiceNumber . '.pdf');
    }

    private function logoDataUri(): ?string
    {
        $configuredPath = trim((string) config('invoice.logo_path'));
        if ($configuredPath === '') {
            return null;
        }

        $logoPath = $this->resolveLogoPath($configuredPath);
        if (! $logoPath) {
            return null;
        }

        $mimeType = File::mimeType($logoPath) ?: 'image/png';
        $content = File::get($logoPath);

        return 'data:' . $mimeType . ';base64,' . base64_encode($content);
    }

    private function resolveLogoPath(string $configuredPath): ?string
    {
        // Chemin absolu Linux/Mac/Windows.
        $isAbsolute = Str::startsWith($configuredPath, ['/','\\'])
            || (bool) preg_match('/^[A-Za-z]:[\\\\\\/]/', $configuredPath);

        if ($isAbsolute && File::exists($configuredPath)) {
            return $configuredPath;
        }

        $normalized = str_replace('\\', '/', $configuredPath);
        $trimmedPublic = Str::startsWith($normalized, 'public/')
            ? substr($normalized, 7)
            : $normalized;

        $candidates = [
            base_path($configuredPath),
            public_path($trimmedPublic),
            storage_path($configuredPath),
            resource_path($configuredPath),
        ];

        foreach ($candidates as $path) {
            if (File::exists($path)) {
                return $path;
            }
        }

        return null;
    }

    private function invoiceNumber(Order $order): string
    {
        return $order->ensureInvoiceNumber();
    }

    private function qrDataUri(Order $order, string $invoiceNumber, \DateTimeInterface $issuedAt): string
    {
        $payload = json_encode([
            'invoice_number' => $invoiceNumber,
            'order_number' => $order->number,
            'order_id' => $order->id,
            'total' => (float) $order->total,
            'currency' => 'XOF',
            'issued_at' => $issuedAt->format(DATE_ATOM),
        ], JSON_UNESCAPED_UNICODE);

        $result = (new Builder(
            writer: new PngWriter(),
            data: $payload ?: ('FACTURE:' . $invoiceNumber),
            size: 180,
            margin: 0,
        ))->build();

        return $result->getDataUri();
    }
}

