<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PurchaseOrder;
use Mpdf\Mpdf;
use Mpdf\Output\Destination;

class OrderPdfController extends Controller
{
    protected function ensureAdminAccess(): void
    {
        $user = auth()->user();
        if (! $user || ! $user->is_admin || ! $user->is_active) {
            abort(403, 'غير مصرح');
        }
    }

    protected function createMpdf(string $format = 'A4'): Mpdf
    {
        return new Mpdf([
            'mode' => 'utf-8',
            'format' => $format,
            'default_font' => 'xbriyaz',
            'default_font_size' => 10,
            'margin_left' => 10,
            'margin_right' => 10,
            'margin_top' => 16,
            'margin_bottom' => 16,
            'autoArabic' => true,
            'mirrorMargins' => true,
        ]);
    }

    public function customerInvoice(Order $order)
    {
        $this->ensureAdminAccess();

        $order->load(['items.variant.product', 'user', 'paymentMethod']);

        $html = view('pdf.customer-invoice', ['order' => $order])->render();

        $mpdf = $this->createMpdf('A4');
        $mpdf->WriteHTML($html);

        return response($mpdf->Output(null, Destination::STRING_RETURN))
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'inline; filename="invoice-' . $order->id . '.pdf"');
    }

    public function shippingWaybill(Order $order)
    {
        $this->ensureAdminAccess();

        $order->load(['user', 'shippingAddress']);

        $html = view('pdf.shipping-waybill', ['order' => $order])->render();

        $mpdf = $this->createMpdf('A5');
        $mpdf->WriteHTML($html);

        return response($mpdf->Output(null, Destination::STRING_RETURN))
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'inline; filename="waybill-' . $order->id . '.pdf"');
    }

    /**
     * إذن تجهيز بضاعة - وثيقة لكل مورد بأصنافه وكمياته فقط.
     */
    public function supplierPreparationSlip(PurchaseOrder $purchaseOrder)
    {
        $this->ensureAdminAccess();

        $purchaseOrder->load(['items.variant.product', 'supplier', 'sourceOrder']);

        $html = view('pdf.supplier-preparation-slip', ['purchaseOrder' => $purchaseOrder])->render();

        $mpdf = $this->createMpdf('A4');
        $mpdf->SetBasePath(str_replace('\\', '/', storage_path('app/public')));
        $mpdf->WriteHTML($html);

        return response($mpdf->Output(null, Destination::STRING_RETURN))
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'inline; filename="preparation-slip-' . $purchaseOrder->id . '.pdf"');
    }
}
