<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    @php
        $paper = strtoupper((string)($paper ?? 'A4'));
        $isPos = in_array($paper, ['POS','POS80','RECEIPT','80'], true);

        $siteName = $settings['SiteName'] ?? '';
        $address  = $settings['Address'] ?? '';
        $mobile   = $settings['mobile'] ?? '';
        $taxNo    = $settings['taxNumber'] ?? '';

        // Logo -> Base64 (عشان dompdf)
        $logoSrc = null;
        if (!empty($settings['logo'])) {
            $logoUrl  = \Illuminate\Support\Facades\Storage::url($settings['logo']); // /storage/...
            $logoPath = public_path($logoUrl);

            if (@file_exists($logoPath)) {
                $ext = strtolower(pathinfo($logoPath, PATHINFO_EXTENSION));
                $mime = 'image/png';
                if ($ext === 'jpg' || $ext === 'jpeg') $mime = 'image/jpeg';
                elseif ($ext === 'gif') $mime = 'image/gif';

                $data = @file_get_contents($logoPath);
                if ($data !== false) {
                    $logoSrc = 'data:' . $mime . ';base64,' . base64_encode($data);
                }
            }
        }

        $client = optional($order->client);
        $orderDate = $order->order_date ?: ($order->invoice_date ?: optional($order->created_at)->format('Y-m-d'));

        // QR
        $qrSrc = null;
        try {
            $Qcode = $order->generatQrcode(
                $siteName,
                $taxNo,
                $orderDate,
                $order->total,
                $order->tax_value
            );

            if (!empty($Qcode)) {
                $qrSrc = $Qcode;

                // لو رجع base64 بدون prefix
                if (strpos($qrSrc, 'data:image') !== 0 && strpos($qrSrc, 'http') !== 0 && strpos($qrSrc, '/') !== 0) {
                    $qrSrc = 'data:image/png;base64,' . $qrSrc;
                }
            }
        } catch (\Exception $e) {
            $qrSrc = null;
        }

        // totals
        $dist = $order->discount;
        if (!empty($order->discount) && (int)$order->discount_type === 2) {
            $dist = $order->total * ($order->discount / 100);
        }
    @endphp

    <title>Invoice {{ $order->invoice_number }}</title>

    <style>
        @page { margin: {{ $isPos ? '3mm' : '10mm' }}; }

        html, body {
            direction: rtl;        /* ✅ RTL صحيح */
            font-family: DejaVu Sans, sans-serif;
            font-size: {{ $isPos ? '10px' : '12px' }};
        }

        .wrap { width: {{ $isPos ? '80mm' : '100%' }}; }
        .hr { border-top:1px solid #000; margin:6px 0; }
        .small { font-size: {{ $isPos ? '9px' : '11px' }}; }
        .right { text-align: right; }
        .center { text-align: center; }

        table { width:100%; border-collapse: collapse; direction: rtl; }
        th, td { border:1px solid #000; padding: {{ $isPos ? '3px' : '6px' }}; vertical-align: middle; }
        th { background:#f2f2f2; font-weight:bold; text-align:center; }
        td { text-align:center; }

        .no-border, .no-border td { border:0 !important; }
        .totals th { width: 35%; }

        /* ✅ للأرقام (تبقى LTR داخل العربي) */
        .ltr { direction:ltr; unicode-bidi: plaintext; }
    </style>
</head>

<body>
<div class="wrap">

    {{-- Header --}}
    <table class="no-border">
        <tr>
            <td class="no-border right" style="width:70%;">
                @if($siteName)<div><b>{{ $siteName }}</b></div>@endif
                @if($taxNo)<div class="small">الرقم الضريبي: <span class="ltr">{{ $taxNo }}</span></div>@endif
                @if($address)<div class="small">{!! $address !!}</div>@endif
                @if($mobile)<div class="small"><span class="ltr">{{ $mobile }}</span></div>@endif
            </td>
            <td class="no-border center" style="width:30%;">
                @if($logoSrc)
                    <img src="{{ $logoSrc }}" style="max-width: {{ $isPos ? '60mm' : '50mm' }}; max-height: 25mm;">
                @endif
            </td>
        </tr>
    </table>

    <div class="hr"></div>

    {{-- Invoice + Client info --}}
    <table class="no-border">
        <tr>
            <td class="no-border right">
                <b>فاتورة رقم:</b> <span class="ltr">{{ $order->invoice_number }}</span><br>
                <b>التاريخ:</b> <span class="ltr">{{ $orderDate }}</span><br>
                <b>طريقة الدفع:</b> {{ $order->payment_type }}
            </td>
            <td class="no-border right">
                <b>العميل:</b> {{ $client->name }}<br>
                @if($client->mobile)<b>الجوال:</b> <span class="ltr">{{ $client->mobile }}</span><br>@endif
                @if($client->address)<span class="small"><b>العنوان:</b> {{ $client->address }}</span><br>@endif
                @if($client->taxnumber)<span class="small"><b>الرقم الضريبي:</b> <span class="ltr">{{ $client->taxnumber }}</span></span>@endif
            </td>
        </tr>
    </table>

    <div class="hr"></div>

    {{-- Items --}}
    <table>
        <thead>
        @if($isPos)
            <tr>
                <th style="width:7%;">#</th>
                <th class="right">الصنف</th>
                <th style="width:12%;">الكمية</th>
                <th style="width:20%;">الإجمالي</th>
            </tr>
        @else
            <tr>
                <th style="width:5%;">#</th>
                <th class="right">الصنف</th>
                <th style="width:15%;">الموظف</th>
                <th style="width:10%;">الوحدة</th>
                <th style="width:10%;">الكمية</th>
                <th style="width:15%;">السعر</th>
                <th style="width:15%;">الإجمالي</th>
            </tr>
        @endif
        </thead>

        <tbody>
        @php $i=1; $totalQty=0; @endphp

        @if(isset($order->items) && count($order->items))
            @foreach($order->items as $item)
                @php
                    $name = $item->product_name ?? optional($item->product)->full_name ?? optional($item->product)->name ?? '—';
                    $qty  = (float)($item->qty ?? 0);
                    $price = (float)($item->price ?? 0);
                    $lineTotal = isset($item->total) ? (float)$item->total : ($qty * $price);
                    $totalQty += $qty;
                @endphp

                @if($isPos)
                    <tr>
                        <td><span class="ltr">{{ $i++ }}</span></td>
                        <td class="right">{{ $name }}</td>
                        <td><span class="ltr">{{ $qty }}</span></td>
                        <td><span class="ltr">{{ $lineTotal }}</span></td>
                    </tr>
                @else
                    <tr>
                        <td><span class="ltr">{{ $i++ }}</span></td>
                        <td class="right">{{ $name }}</td>
                        <td>{{ optional($item->employee)->name }}</td>
                        <td>{{ $item->unit_name ?? '' }}</td>
                        <td><span class="ltr">{{ $qty }}</span></td>
                        <td><span class="ltr">{{ $price }}</span></td>
                        <td><span class="ltr">{{ $lineTotal }}</span></td>
                    </tr>
                @endif
            @endforeach
        @else
            <tr>
                <td colspan="{{ $isPos ? 4 : 7 }}">لا توجد أصناف</td>
            </tr>
        @endif
        </tbody>
    </table>

    <div class="hr"></div>

    {{-- Totals --}}
    <table class="totals">
        <tbody>
            <tr>
                <th class="right">إجمالي الكميات</th><td><span class="ltr">{{ $totalQty }}</span></td>
                <th class="right">قبل الضريبة</th><td><span class="ltr">{{ $order->total_without_tax ?? '' }}</span></td>
            </tr>
            <tr>
                <th class="right">الخصم</th><td><span class="ltr">{{ $dist }}</span></td>
                <th class="right">الضريبة</th><td><span class="ltr">{{ round((float)$order->tax_value,2) }}</span></td>
            </tr>
            <tr>
                <th class="right">الإجمالي</th><td><span class="ltr">{{ $order->total }}</span></td>
                <th class="right">المدفوع</th><td><span class="ltr">{{ $order->paid }}</span></td>
            </tr>
            <tr>
                <th class="right">المتبقي</th><td><span class="ltr">{{ $order->due }}</span></td>
                <th class="right"></th><td></td>
            </tr>
        </tbody>
    </table>

    {{-- Notes + QR --}}
    @if(!empty($settings['InvoiceNotes']) || !empty($order->note) || $qrSrc)
        <div class="hr"></div>

        @if(!empty($settings['InvoiceNotes']))
            <div class="small">{!! $settings['InvoiceNotes'] !!}</div>
        @endif

        @if(!empty($order->note))
            <div class="small">{{ $order->note }}</div>
        @endif

        @if($qrSrc)
            <div class="center" style="margin-top:6px;">
                <img src="{{ $qrSrc }}" style="width: {{ $isPos ? '40mm' : '35mm' }};">
            </div>
        @endif
    @endif

</div>
</body>
</html>