<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ __('فاتورة') }} - {{ $invoice->number }}</title>
    @php
        $branding = app(\App\Domain\Shared\Services\SettingsService::class);
        $brand = app(\App\Domain\Shared\Services\BrandingService::class)->forCurrentAcademy();
        // show_logo_in_invoice, invoice_header and invoice_footer_text were all
        // collected by the branding screen and read by nothing. This is the
        // surface they were collected for.
        $brandLogo = $brand->showLogoInInvoice ? $brand->logoUrl : null;
        $invoiceHeaderUrl = $brand->invoiceHeaderUrl;
        $brandPrimary = $brand->primary;
        $academyName = $brand->academyName;
        $academyAddress = $brand->address;
        // The issuing branch is the invoice's own branch. This used to be
        // Branch::where('academy_id', ...)->first() — the academy's *first*
        // branch, whichever that happened to be — so a customer served at
        // branch B walked out holding a document with branch A's name, address
        // and phone on it. Invoice carries branch_id (and BelongsToBranch), so
        // the document can state the branch that actually issued it.
        $branch = $invoice->branch;

        // Load invoice template for field visibility — for the branch that
        // issued the invoice. resolveFor() prefers a branch-specific default
        // and only then the academy-wide one, so the wrong id printed another
        // branch's blocks and footer text. 0 is "no branch of mine", which
        // falls through to the academy-wide default, exactly as
        // ReceiptService does for a payment with no branch.
        $invoiceTpl = \App\Domain\POS\Models\ReceiptTemplate::resolveFor($invoice->branch_id ?? 0, 'invoice');
        $f = $invoiceTpl?->visible_fields ?? \App\Domain\POS\Models\ReceiptTemplate::defaultInvoiceFields();
        $tplSettings = $invoiceTpl?->settings ?? \App\Domain\POS\Models\ReceiptTemplate::defaultInvoiceSettings();
        $receiptFooter = !empty($tplSettings['footer_text'])
            ? $tplSettings['footer_text']
            : ($brand->invoiceFooterText ?: ($brand->receiptFooterText ?: 'تم إنشاء هذه الفاتورة إلكترونياً ولا تحتاج إلى توقيع'));
        $showSignature = $brand->showSignatureInInvoice;
        $signature = $brand->signatureUrl;
        $termsText = $brand->termsAndConditions;
        $taxNumber = $branding->get('financial.tax_registration_number', '');
    @endphp
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Cairo', 'Noto Sans Arabic', sans-serif;
            direction: rtl;
            font-size: 14px;
            color: #333;
            background: #f3f4f6;
            padding: 16px;
        }
        .invoice-wrapper {
            max-width: 700px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 20px;
            border-bottom: 3px solid {{ $brandPrimary }};
            gap: 12px;
            flex-wrap: wrap;
        }
        .header .brand { display: flex; align-items: center; gap: 12px; }
        .header .brand img { height: 45px; object-fit: contain; }
        .header .brand h1 { font-size: 20px; color: {{ $brandPrimary }}; margin: 0; }
        .header .meta { text-align: left; font-size: 12px; color: #666; min-width: 140px; }
        .header .meta p { margin-bottom: 3px; }

        .parties {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
            padding: 16px 20px;
        }
        .party { padding: 12px; background: #f8fafc; border-radius: 8px; }
        .party h3 { font-size: 11px; color: #64748b; margin-bottom: 6px; text-transform: uppercase; font-weight: 600; }
        .party p { margin-bottom: 2px; font-size: 13px; }

        .items-table { padding: 0 20px 16px; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 400px; }
        th { background: {{ $brandPrimary }}; color: white; padding: 10px 12px; text-align: right; font-size: 12px; font-weight: 600; }
        td { padding: 10px 12px; border-bottom: 1px solid #e2e8f0; font-size: 13px; }
        tr:last-child td { border-bottom: none; }

        .totals-section { padding: 16px 20px; border-top: 1px solid #e2e8f0; }
        .totals { margin-right: auto; width: 100%; max-width: 280px; }
        .totals .row { display: flex; justify-content: space-between; padding: 5px 0; font-size: 13px; }
        .totals .row.total { font-weight: bold; font-size: 16px; border-top: 2px solid #333; padding-top: 10px; margin-top: 5px; }
        .totals .row.paid { color: #166534; }
        .totals .row.due { color: #dc2626; font-weight: bold; }

        .payments-section { padding: 0 20px 16px; }
        .payments-section h3 { font-size: 14px; margin-bottom: 8px; font-weight: 600; }

        .status-badge {
            display: inline-block;
            padding: 3px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }
        .status-paid { background: #dcfce7; color: #166534; }
        .status-sent, .status-pending { background: #dbeafe; color: #1e40af; }
        .status-overdue { background: #fef2f2; color: #991b1b; }
        .status-partially_paid { background: #fef9c3; color: #854d0e; }
        .status-draft { background: #f3f4f6; color: #374151; }
        .status-cancelled { background: #f3f4f6; color: #6b7280; }

        .footer {
            padding: 16px 20px;
            text-align: center;
            font-size: 11px;
            color: #94a3b8;
            border-top: 1px solid #e2e8f0;
        }

        .actions {
            padding: 16px 20px;
            display: flex;
            justify-content: center;
            gap: 12px;
            flex-wrap: wrap;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 24px;
            min-height: 48px;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            font-family: inherit;
            text-decoration: none;
            transition: background 0.15s;
            -webkit-tap-highlight-color: transparent;
        }
        .btn-print { background: {{ $brandPrimary }}; color: white; }
        .btn-print:active { opacity: 0.85; }
        .btn-share { background: #f3f4f6; color: #374151; }
        .btn-share:active { background: #e5e7eb; }

        /* Mobile adjustments */
        @media (max-width: 600px) {
            body { padding: 8px; }
            .header { padding: 16px; flex-direction: column; gap: 12px; }
            .header .meta { text-align: right; }
            .parties { grid-template-columns: 1fr; gap: 10px; padding: 12px 16px; }
            .items-table { padding: 0 12px 12px; }
            th, td { padding: 8px 6px; font-size: 12px; }
            .totals-section { padding: 12px 16px; }
            .totals { max-width: 100%; }
            .actions { padding: 12px 16px; }
            .btn { width: 100%; padding: 14px 20px; }
            .footer { padding: 12px 16px; }
        }

        @media print {
            body { background: white; padding: 10px; }
            .invoice-wrapper { box-shadow: none; border-radius: 0; }
            .actions { display: none !important; }
            .items-table { overflow: visible; }
            table { min-width: unset; }
        }
    </style>
</head>
<body>
    <div class="invoice-wrapper">
        <div class="header">
            <div class="brand">
                @if(($f['header_logo'] ?? true) && $invoiceHeaderUrl)
                <img src="{{ $invoiceHeaderUrl }}" alt="{{ $academyName }}">
                @elseif(($f['header_logo'] ?? true) && $brandLogo)
                <img src="{{ $brandLogo }}" alt="{{ $academyName }}">
                @endif
                <div>
                    <h1>{{ __('فاتورة') }}</h1>
                    @if($f['header_academy_name'] ?? true)
                    <p style="color: #64748b; margin-top: 2px; font-size: 13px;">{{ $academyName }}</p>
                    @endif
                    @if(($f['header_branch'] ?? true) && $branch)
                    <p style="color: #94a3b8; font-size: 11px;">{{ $branch->name_ar }}</p>
                    @endif
                    @if(($f['header_tax_number'] ?? false) && $taxNumber)
                    <p style="color: #94a3b8; font-size: 11px;">{{ __('الرقم الضريبي') }}: {{ $taxNumber }}</p>
                    @endif
                </div>
            </div>
            <div class="meta">
                <p><strong>{{ __('رقم الفاتورة') }}:</strong> {{ $invoice->number }}</p>
                <p><strong>{{ __('التاريخ') }}:</strong> {{ $invoice->issue_date ?? $invoice->created_at?->format('Y-m-d') }}</p>
                @if($invoice->due_date)
                <p><strong>{{ __('الاستحقاق') }}:</strong> {{ $invoice->due_date }}</p>
                @endif
                <p style="margin-top: 5px;">
                    @php $statusValue = $invoice->status?->value ?? $invoice->status ?? 'draft'; @endphp
                    <span class="status-badge status-{{ $statusValue }}">{{ __($statusValue) }}</span>
                </p>
            </div>
        </div>

        @if(($f['client_details'] ?? true) || ($f['header_branch'] ?? true))
        <div class="parties">
            @if($f['client_details'] ?? true)
            <div class="party">
                <h3>{{ __('العميل') }}</h3>
                @if($invoice->billable)
                <p><strong>{{ $invoice->billable->full_name ?? $invoice->billable->name_ar ?? $invoice->billable->person?->name_ar ?? '-' }}</strong></p>
                @if($invoice->billable->phone ?? $invoice->billable->person?->phone ?? null)
                <p dir="ltr" style="color: #666;">{{ $invoice->billable->phone ?? $invoice->billable->person?->phone }}</p>
                @endif
                @endif
            </div>
            @endif
            @if($f['header_branch'] ?? true)
            <div class="party">
                <h3>{{ __('من') }}</h3>
                <p><strong>{{ $academyName }}</strong></p>
                @if($branch)
                @if($branch->address)
                <p style="color: #666;">{{ $branch->address }}</p>
                @endif
                @if($branch->phone)
                <p dir="ltr" style="color: #666;">{{ $branch->phone }}</p>
                @endif
                @endif
            </div>
            @endif
        </div>
        @endif

        @if($f['items_table'] ?? true)
        <div class="items-table">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>{{ __('الوصف') }}</th>
                        <th>{{ __('الكمية') }}</th>
                        <th>{{ __('سعر الوحدة') }}</th>
                        <th>{{ __('الإجمالي') }}</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($invoice->items as $i => $item)
                    @php
                        $itemMeta = is_array($item->metadata) ? $item->metadata : [];
                        $hasOverride = !empty($itemMeta['original_price']) && isset($itemMeta['overridden_price']);
                    @endphp
                    <tr>
                        <td>{{ $i + 1 }}</td>
                        <td>
                            {{ $item->description }}
                            @if($hasOverride)
                            <div style="font-size:10px; color:#dc2626; margin-top:2px;">
                                {{ __('السعر الأصلي') }}: <span dir="ltr" style="text-decoration:line-through">{{ format_money($itemMeta['original_price']) }}</span>
                                @if(!empty($itemMeta['override_reason']))
                                — {{ $itemMeta['override_reason'] }}
                                @endif
                            </div>
                            @endif
                        </td>
                        <td>{{ $item->quantity }}</td>
                        <td dir="ltr">
                            @if($hasOverride)
                            <span style="text-decoration:line-through; color:#9ca3af; font-size:11px;">{{ format_money($itemMeta['original_price']) }}</span><br>
                            <span style="color:#dc2626; font-weight:bold;">{{ format_money($itemMeta['overridden_price']) }}</span>
                            @else
                            {{ format_money($item->unit_price) }}
                            @endif
                        </td>
                        <td dir="ltr">{{ format_money($item->total_amount) }}</td>
                    </tr>
                    @empty
                    <tr><td colspan="5" style="text-align: center; color: #999;">{{ __('لا توجد بنود') }}</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @endif

        <div class="totals-section">
            <div class="totals">
                @if($f['subtotal'] ?? true)
                <div class="row">
                    <span>{{ __('المجموع الفرعي') }}</span>
                    <span dir="ltr">{{ format_money($invoice->subtotal_amount ?? $invoice->total_amount) }}</span>
                </div>
                @endif
                @if(($f['discount'] ?? true) && $invoice->discount_amount > 0)
                <div class="row">
                    <span>{{ __('الخصم') }}</span>
                    <span dir="ltr" style="color: #dc2626;">-{{ format_money($invoice->discount_amount) }}</span>
                </div>
                @endif
                @if(($f['service_fee'] ?? true) && ($invoice->service_fee_amount ?? 0) > 0)
                <div class="row">
                    <span>{{ __('رسوم الخدمة') }}</span>
                    <span dir="ltr">{{ format_money($invoice->service_fee_amount) }}</span>
                </div>
                @endif
                @if(($f['tax_amount'] ?? true) && $invoice->tax_amount > 0)
                <div class="row">
                    <span>{{ __('الضريبة') }}</span>
                    <span dir="ltr">{{ format_money($invoice->tax_amount) }}</span>
                </div>
                @endif
                <div class="row total">
                    <span>{{ __('الإجمالي') }}</span>
                    <span dir="ltr">{{ format_money($invoice->total_amount) }}</span>
                </div>
                @if(($f['paid_amount'] ?? true) && $invoice->paid_amount > 0)
                <div class="row paid">
                    <span>{{ __('المدفوع') }}</span>
                    <span dir="ltr">{{ format_money($invoice->paid_amount) }}</span>
                </div>
                <div class="row due">
                    <span>{{ __('المتبقي') }}</span>
                    <span dir="ltr">{{ format_money($invoice->due_amount) }}</span>
                </div>
                @endif
            </div>
        </div>

        @if(($f['payments_history'] ?? true) && $invoice->payments && $invoice->payments->count())
        <div class="payments-section">
            <h3>{{ __('المدفوعات') }}</h3>
            <table>
                <thead>
                    <tr>
                        <th>{{ __('التاريخ') }}</th>
                        <th>{{ __('الطريقة') }}</th>
                        <th>{{ __('المبلغ') }}</th>
                        <th>{{ __('الحالة') }}</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($invoice->payments as $payment)
                    <tr>
                        <td dir="ltr">{{ $payment->created_at?->format('Y-m-d') }}</td>
                        <td>{{ __($payment->method instanceof \BackedEnum ? $payment->method->value : $payment->method) }}</td>
                        <td dir="ltr">{{ format_money($payment->amount) }}</td>
                        <td>{{ __($payment->status instanceof \BackedEnum ? $payment->status->value : $payment->status) }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        @endif

        @if(($f['signature'] ?? false) && $showSignature && $signature)
        <div style="padding: 12px 20px; text-align: end;">
            <img src="{{ Storage::disk('public')->url($signature) }}" alt="{{ __('التوقيع') }}" style="height: 50px; object-fit: contain;">
            <p style="font-size: 11px; color: #94a3b8; margin-top: 4px;">{{ __('التوقيع المعتمد') }}</p>
        </div>
        @endif

        @if(($f['terms_conditions'] ?? false) && $termsText)
        <div style="padding: 12px 20px; border-top: 1px solid #e2e8f0; font-size: 11px; color: #64748b;">
            <p style="font-weight: 600; margin-bottom: 4px;">{{ __('الشروط والأحكام') }}</p>
            <p style="white-space: pre-wrap;">{{ $termsText }}</p>
        </div>
        @endif

        @if($f['footer_text'] ?? true)
        <div class="footer">
            {{ $receiptFooter }}
        </div>
        @endif

        <div class="actions">
            <button onclick="window.print()" class="btn btn-print">
                <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
                </svg>
                {{ __('طباعة') }}
            </button>
            <button onclick="shareInvoice()" class="btn btn-share" id="share-btn" style="display:none;">
                <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"/>
                </svg>
                {{ __('مشاركة') }}
            </button>
        </div>
    </div>

    <script>
        if (navigator.share) {
            document.getElementById('share-btn').style.display = 'inline-flex';
        }
        function shareInvoice() {
            if (navigator.share) {
                navigator.share({
                    title: '{{ __("فاتورة") }} {{ $invoice->number }}',
                    url: window.location.href
                }).catch(function() {});
            }
        }
    </script>
</body>
</html>
