########################################
# POS RECEIPT PRINTING (ZATCA SIMPLE TAX INVOICE)
# طباعة فاتورة الطلب + قصاصات الباركود للخدمات
########################################

You are an expert full-stack engineer (Node.js + React) and POS printing specialist.
We already have:
- Orders module (طلبات الصالون / طلبات التطبيق)
- Services & products lines linked to orders
- Employees (with first_name, last_name)
- Company settings table or config
- Payments with payment method info (cash / card / etc.)

We want to implement **thermal receipt printing** that is:
1) ZATCA Phase 1 compliant (Simplified Tax Invoice with QR)
2) Same design and layout as the attached sample receipts (Qamar Samaya salon)
3) Printed on standard thermal paper (58mm width)
4) Generates **extra small barcode slips** per service for the staff.

========================================
# 1) DATA SOURCE & SETTINGS (الإعدادات)
========================================

Create / extend a table (or config) for company settings, e.g. `company_settings`:

Fields:
- id
- company_name_ar        // صالون قمر سمايا النسائي
- phone                  // الجوال
- branch_name            // اسم الفرع (اختياري)
- cr_number              // السجل التجاري
- vat_number             // الرقم الضريبي
- address_line           // العنوان
- city                   // المدينة
- extra_note             // ملاحظات أسفل الفاتورة (اختياري)

Behavior:
- When printing, read all of these from settings.
- If any of the required fields (company_name_ar, vat_number, cr_number) is missing:
  - still print the invoice but show placeholders like "—" AND
  - log a warning or show message in UI to complete company settings in "الإعدادات".

Add UI section:
- صفحة إعدادات الفاتورة / معلومات المنشأة
- تسمح بتعديل هذه الحقول.


========================================
# 2) RECEIPT DATA MODEL (بيانات الفاتورة)
========================================

For a given order (salon order or app order), gather:

From order:
- invoice_number             // رقم الفاتورة
- status (completed, cancelled, etc.)  // حالة الفاتورة
- order_date_time            // تاريخ/وقت الفاتورة
- booking_date_time          // تاريخ/وقت الحجز (إن وجد)
- print_date_time            // وقت الطباعة الحالي
- customer_name              // اسم العميل (from customer record)
- payment_method             // طريقة الدفع (cash, mada, visa, etc.)
- payment_type_label         // نص يوضح النقدي/شبكي/بطاقة…
- cashier_user_name          // اليوزر الذي أنشأ/طبع الفاتورة

Totals:
- subtotal_before_discount   // سعر الخدمات/المنتجات قبل الخصم
- discount_amount            // مجموع الخصم
- vat_rate                   // usually 0.15
- vat_amount
- total_with_vat             // الإجمالي مع الضريبة
- paid_amount
- remaining_amount
- status text for remaining  // "مبالغ مستردة" or "لا يوجد مبلغ مسترد" based on logic

Lines (order_items):
For each line we need:
- service_or_product_name    // اسم الخدمة أو المنتج
- line_type                  // "service" or "product"
- execution_time             // وقت تنفيذ الخدمة (أو وقت الحجز/البدء)
- assigned_employee_id       // nullable
- assigned_employee_first_name
- assigned_employee_last_name
- discount_line_amount or %
- price_line                 // سعر السطر (شامل/غير شامل بحسب النظام، المهم نفس الفاتورة)
- quantity (if needed, but تصميمك يستخدم سطر لكل خدمة)

Rule:
- If line_type = "service" AND employee assigned → show employee first + last names in the "Expert" column.
- If line_type = "product" → leave Expert column blank (or show "—").


========================================
# 3) RECEIPT LAYOUT (تصميم الفاتورة 58mm)
========================================

Implement a **printable HTML/CSS template** for the receipt (React component) that:

- Is RTL (direction: rtl; text-align: right)
- Has width ~ 58mm (or 210px–230px) for thermal printers.
- Matches the sample design exactly:

Header:
- Title line: "فاتورة ضريبية مبسطة" (centered, small font)
- Company name (big, bold): e.g. "صالون قمر سمايا النسائي"
- Phone number
- Branch name or manager name (e.g. "سلمان الفارسي") if available
- VAT number label: "الرقم الضريبي:"
- CR number label: "السجل التجاري:"
- Invoice number label: "رقم الفاتورة:"
- Invoice status: "حالة الفاتورة: مكتملة / ملغاة / ..."
- Invoice date/time: "تاريخ الفاتورة:"
- Booking date/time: "تاريخ الحجز:" (from–to)
- Print date: "تاريخ الطباعة:"
- Payment info block:
  - "طريقة الدفع: نقدي / شبكي / Mada / Visa ..."
  - "نوع الدفع: شبكي / كاش .."
  - terminal name or last 4 digits if available, e.g. "اسم المحصلة / رقم الجهاز: 8546"

Body table (as in sample):

Columns (RTL):

| الوقت Time | الموظفة Expert | الخصم Dist | السعر Price | اسم الخدمة / المنتج Service |

- Use small font.
- Each line row shows:
  - execution_time (HH:MM AM/PM)
  - Expert: employee full name if line_type = service; else blank
  - Dist: discount for that line (0.00 if none)
  - Price: line price
  - Service: line name

Footer summary table:

Left to right (matching your sample):

Row 1:
- "Discount" (English)
- "%"
- "Price" then قيمة الخصم بالريال

Row 2:
- "سعر الخدمات/المنتجات"  → subtotal_before_discount

Row 3:
- "VAT 15%" (or according to vat_rate)
- قيمة الضريبة

Row 4:
- "Total" → total_with_vat

Row 5:
- "paid" → paid_amount

Row 6:
- "Remain" → remaining_amount

Row 7:
- If remaining_amount = 0 AND there is refundable amount → show:
  - "مبالغ مستردة" or similar text.
- Else if no remaining/refund → "0 ر.س" and appropriate text.

Footer:
- Print cashier username: "طبع بواسطة: [username]"
- Optional note from settings: `extra_note`
- ZATCA QR code (see next section) printed at bottom center.


========================================
# 4) ZATCA QR CODE (رمز الاستجابة للزكاة والدخل)
========================================

Add a QR code at the bottom of the receipt that complies with **ZATCA Simplified Tax Invoice** Phase 1 TLV format.

Fields to encode in TLV:

1. Seller name         → company_name_ar
2. VAT registration no → vat_number
3. Invoice timestamp   → invoice_date_time (ISO 8601)
4. Invoice total       → total_with_vat
5. VAT total           → vat_amount

Implementation:

- Create a helper function, e.g. `generateZatcaQrPayload(data)` that builds TLV bytes then base64 encodes them.
- Use a QR library in the frontend (e.g. `qrcode.react`) or backend (e.g. `qrcode`) to render the QR image from the base64 string.
- Place the QR code at the bottom of the receipt in the print layout.

No need to implement Phase 2 (hash / cryptographic signing), only Phase 1 textual QR is required.


========================================
# 5) PRINTING MECHANISM (آلية الطباعة)
========================================

Implement a React page or dialog:

Route example:
- `/orders/:id/print-receipt`

Behavior:

- Load order data, build receipt view using the template above.
- Provide a "طباعة" button that calls `window.print()` using a dedicated print stylesheet.

CSS for print:
- `@media print`:
  - Set page size for 58mm roll:
    - `width: 58mm;`
    - `margin: 0;`
  - Hide UI elements (buttons, headers) and keep only the receipt.
- Ensure fonts are legible on thermal printer.

Optionally:
- Allow re-printing; log who printed and when (append to an order_prints table).


========================================
# 6) BARCODE SLIPS FOR EACH SERVICE
# قصاصات باركود لكل خدمة
========================================

When printing an order, we also want to print **additional small slips** (one per service line) that will be handed to the service provider.

For each service line in the order (NOT for product lines):

Generate a small ticket (another HTML print block) with:

- Client name
- Order number
- Service name
- Assigned employee name (الخبيرة المنفذة)
- Execution time
- A **barcode** which will be scanned later in the mobile app.

Barcode content proposal (string):

`{orderId}-{lineId}`

Example: `"SO123-5"`

We will use this later in the app to:
- Mark service as "in progress"
- Mark service as "completed"

Implementation:

- Use a barcode library suitable for browser printing, such as:
  - `JsBarcode` (for Code128) or any library you prefer.
- Create a React component: `<ServiceTicket />` that renders the slip.
- Style it for 58mm width, short height, minimal text.

Printing behavior:

Option A (simple):
- On "Print receipt", open a print view that contains:
  - The full invoice as first section.
  - Then each service slip below it, each on its own page break.
- Use `page-break-after: always;` (or `break-after`) in CSS so each slip is printed on a separate small receipt section.

Option B (separate button):
- Button "طباعة الفاتورة"
- Button "طباعة قصاصات الخدمات"
- Each opens its own print view.

Any option is acceptable; choose the easier one and keep CSS clean.


========================================
# 7) LINKING TO ORDER & SECURITY
========================================

- Only authenticated users with proper permissions should access print routes.
- Use the **current logged-in user** as the "printer":
  - Save username in the order print log.
  - Show `طبع بواسطة: [username]` in the footer.

Add optional `order_prints` table:

- id
- order_id
- printed_by_user_id
- printed_at (datetime)
- print_type ("receipt", "service_slips")

This is optional but helpful.


========================================
# 8) ARABIC LABELS AND VALIDATION
========================================

All labels in the receipt **must be in Arabic exactly as in the sample**, with small English words where shown:

- "فاتورة ضريبية مبسطة"
- "حالة الفاتورة: مكتملة / ..."
- "تاريخ الفاتورة:"
- "تاريخ الحجز:"
- "تاريخ الطباعة:"
- "طريقة الدفع:"
- "نوع الدفع:"
- "اسم المحصلة:" (أو ما يناسب بيانات الدفع لديك)
- Table headers:
  - "Time"
  - "Expert"
  - ".Disct" أو ".Dist" (نفس الكتابة الموجودة لديك)
  - "Price"
  - "Service"
- Summary labels:
  - "سعر الخدمات/المنتجات"
  - "الضريبة 15%" (or VAT X%)
  - "المجموع"
  - "المدفوع"
  - "المتبقي"
  - "Discount / Price / %"
- Footer text for refunds / remain:
  - Use your current wording, e.g. "مبالغ مستردة" أو "لا يوجد مبلغ مسترد".

If any required data missing (e.g., customer name is null):
- Handle gracefully (show "عميل نقدي") instead of crashing.


========================================
# 9) CODE ORGANIZATION
========================================

- Put all receipt-related React components under:
  - `src/components/receipt/` or `src/features/orders/receipt/`.
- Put accounting/ZATCA helpers under:
  - `src/utils/zatcaQr.js`
  - `src/utils/barcode.js` (if needed)
- Keep business logic (order totals, VAT calculations) on the backend, and send ready-to-use numbers in the API response for printing:
  - e.g., an endpoint: `GET /orders/:id/print-data` that returns exactly what the receipt needs:
    - company_info
    - order_header
    - order_lines
    - totals
    - zatca_qr_payload

########################################
# END OF SPEC
########################################
