<p-toast />
<p-confirmDialog />

<div class="orders-page">
  <app-page-header title="PURCHASES.PURCHASE_ORDERS" subtitle="PURCHASES.TITLE" (refresh)="retry()">
    <p-button
      [label]="'PURCHASES.NEW_ORDER' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
  </app-page-header>

  <ng-template #bodyTpl let-o>
    <tr>
      <td class="mono">{{ o.order_number }}</td>
      <td>{{ o.date }}</td>
      <td>{{ o.expected_delivery_date || '-' }}</td>
      <td>{{ o.supplier_name }}</td>
      <td class="amount">{{ o.total | number:'1.2-2' }}</td>
      <td>
        <p-tag
          [value]="getStatusLabel(o.status)"
          [severity]="getStatusSeverity(o.status)"
        />
      </td>
      <td>
        @if (o.receive_status) {
          <p-tag
            [value]="getStatusLabel(o.receive_status)"
            [severity]="getStatusSeverity(o.receive_status)"
            [rounded]="true"
          />
        } @else {
          <span>-</span>
        }
      </td>
      <td>
        @if (o.bill_status) {
          <p-tag
            [value]="getStatusLabel(o.bill_status)"
            [severity]="getStatusSeverity(o.bill_status)"
            [rounded]="true"
          />
        } @else {
          <span>-</span>
        }
      </td>
      <td>
        <div class="action-buttons">
          <p-button
            icon="pi pi-eye"
            [rounded]="true"
            [text]="true"
            severity="info"
            (onClick)="viewOrder(o)"
            [pTooltip]="'COMMON.VIEW' | translate"
          />
          <p-button
            icon="pi pi-print"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="printOrder(o)"
            [pTooltip]="'PURCHASES.PRINT' | translate"
          />
          @if (o.status === 'draft') {
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editOrder(o)"
              [pTooltip]="'COMMON.EDIT' | translate"
            />
            <p-button
              icon="pi pi-send"
              [rounded]="true"
              [text]="true"
              severity="warn"
              (onClick)="submitApproval(o)"
              [pTooltip]="'PURCHASES.SUBMIT_APPROVAL' | translate"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteOrder(o)"
              [pTooltip]="'COMMON.DELETE' | translate"
            />
          }
          @if (o.status === 'pending_approval') {
            <p-button
              icon="pi pi-check"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="approveOrder(o)"
              [pTooltip]="'PURCHASES.APPROVE' | translate"
            />
          }
          @if (o.status === 'approved') {
            <p-button
              icon="pi pi-check-circle"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="confirmOrder(o)"
              [pTooltip]="'PURCHASES.CONFIRM' | translate"
            />
          }
          @if (o.status === 'confirmed' || o.status === 'partially_received') {
            <p-button
              icon="pi pi-box"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="openCreateGrn(o)"
              [pTooltip]="'PURCHASES.CREATE_GRN' | translate"
            />
          }
          @if (o.status === 'confirmed' || o.status === 'received' || o.status === 'partially_received' || o.status === 'partially_billed') {
            <p-button
              icon="pi pi-file"
              [rounded]="true"
              [text]="true"
              severity="warn"
              (onClick)="openCreateBill(o)"
              [pTooltip]="'PURCHASES.CREATE_BILL' | translate"
            />
          }
          @if (o.status !== 'draft' && o.status !== 'cancelled' && o.status !== 'closed') {
            <p-button
              icon="pi pi-lock"
              [rounded]="true"
              [text]="true"
              severity="secondary"
              (onClick)="closeOrder(o)"
              [pTooltip]="'PURCHASES.CLOSED' | translate"
            />
          }
          <p-button
            icon="pi pi-copy"
            [rounded]="true"
            [text]="true"
            severity="secondary"
            (onClick)="duplicateOrder(o)"
            [pTooltip]="'PURCHASES.DUPLICATE' | translate"
          />
          @if (o.status !== 'cancelled' && o.status !== 'closed') {
            <p-button
              icon="pi pi-ban"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="cancelOrder(o)"
              [pTooltip]="'PURCHASES.CANCEL' | translate"
            />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <ng-template #filtersTpl>
    <app-sales-filter-bar
      [statusOptions]="statusOptions"
      [customers]="filterSuppliers()"
      (filtersChange)="onFiltersChange($event)"
    />
  </ng-template>

  <app-data-table
    [data]="tableData()"
    [lazy]="true"
    [totalRecords]="totalRecords()"
    [first]="first"
    [loading]="tableLoading()"
    [rows]="rows"
    (onLazyLoad)="onPageChange($event)"
    [columns]="columns"
    (retry)="retry()"
    [bodyTpl]="bodyTpl"
    [filtersTpl]="filtersTpl"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingOrder() ? ('PURCHASES.EDIT_ORDER' | translate) : ('PURCHASES.NEW_ORDER' | translate)"
  width="950px"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="orderForm" class="order-form">
    <!-- Row 1: Supplier + Date + Expected Delivery -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.SUPPLIER' | translate }} * <p-button icon="pi pi-plus" [rounded]="true" [text]="true" size="small" severity="success" (onClick)="openQuickAddSupplier()" [pTooltip]="'PURCHASES.ADD_SUPPLIER' | translate" /></label>
        <p-select
          formControlName="supplier_id"
          [options]="searchedSuppliers()"
          optionValue="id"
          [filter]="true"
          [filterBy]="'name,name_ar,name_en,code'"
          (onFilter)="onSupplierSearch($event)"
          [placeholder]="'PURCHASES.SUPPLIER' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
          [loading]="supplierSearchLoading()"
        >
          <ng-template #selectedItem let-selected>
            <span>{{ selected.code }} - {{ selected.name }}</span>
          </ng-template>
          <ng-template #item let-partner>
            <span>{{ partner.code }} - {{ partner.name }}</span>
          </ng-template>
        </p-select>
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.EXPECTED_DELIVERY' | translate }}</label>
        <p-datepicker formControlName="expected_delivery_date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
    </div>

    <!-- Row 2: Warehouse + Currency + Exchange Rate + Payment Terms -->
    <div class="form-grid">
      <div class="form-field">
        <label>{{ 'PURCHASES.WAREHOUSE' | translate }}</label>
        <p-select
          formControlName="warehouse_id"
          [options]="(warehouses$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [showClear]="true"
          [placeholder]="'PURCHASES.WAREHOUSE' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.CURRENCY' | translate }}</label>
        <p-select
          formControlName="currency_code"
          [options]="(currencies$ | async) || []"
          optionLabel="code"
          optionValue="code"
          [placeholder]="'PURCHASES.CURRENCY' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.EXCHANGE_RATE' | translate }}</label>
        <p-inputNumber formControlName="exchange_rate" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="6" [style]="{ width: '100%' }" />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.PAYMENT_TERMS' | translate }}</label>
        <p-inputNumber formControlName="payment_terms_days" [min]="0" [style]="{ width: '100%' }" />
      </div>
    </div>

    <!-- Row 3: Reference + Subject -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.REFERENCE' | translate }}</label>
        <input pInputText formControlName="reference" />
      </div>
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.SUBJECT' | translate }}</label>
        <input pInputText formControlName="subject" />
      </div>
    </div>

    <!-- Line Items Section -->
    <div class="lines-section">
      <div class="lines-header">
        <h3>{{ 'PURCHASES.LINE_ITEMS' | translate }}</h3>
        <p-button
          icon="pi pi-plus"
          [label]="'PURCHASES.ADD_LINE' | translate"
          severity="contrast"
          [outlined]="true"
          size="small"
          styleClass="header-add-btn"
          (onClick)="addItem()"
        />
      </div>

      <div class="barcode-row">
        <span class="pi pi-barcode barcode-icon"></span>
        <input pInputText
          [ngModel]="barcodeValue()" (ngModelChange)="barcodeValue.set($event)"
          [ngModelOptions]="{standalone: true}"
          [placeholder]="'INVENTORY.SCAN_BARCODE' | translate"
          (keydown.enter)="onBarcodeScan($event)"
          [disabled]="barcodeLoading()"
          class="barcode-input" />
        @if (barcodeLoading()) { <i class="pi pi-spin pi-spinner"></i> }
      </div>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-product">{{ 'PURCHASES.PRODUCT' | translate }}</th>
            <th class="col-unit">{{ 'PURCHASES.UNIT' | translate }}</th>
            <th class="col-qty">{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th class="col-price">{{ 'PURCHASES.UNIT_COST' | translate }}</th>
            <th class="col-discount">{{ 'PURCHASES.DISCOUNT' | translate }}</th>
            <th class="col-tax">{{ 'PURCHASES.TAX' | translate }}</th>
            <th class="col-total">{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="items">
          @for (item of items.controls; track item; let i = $index) {
            <tr [formGroupName]="i">
              <td>
                <p-select
                  formControlName="product_id"
                  [options]="searchedProducts()"
                  optionValue="id"
                  [filter]="true"
                  [filterBy]="'name_ar,name_en,code,barcode'"
                  (onFilter)="onProductSearch($event)"
                  appendTo="body"
                  [style]="{ width: '100%' }"
                  [placeholder]="'PURCHASES.PRODUCT' | translate"
                  [loading]="searchLoading()">
                  <ng-template #item let-product>
                    <div style="display: flex; flex-direction: column; gap: 1px;">
                      <small style="color: #94a3b8;">{{ product.category?.name_ar || '—' }}</small>
                      <span>{{ product.name_ar }} <small style="color: #64748b;">({{ product.code }})</small></span>
                      @if (product.barcode) { <small style="color: #94a3b8;"><i class="pi pi-barcode"></i> {{ product.barcode }}</small> }
                    </div>
                  </ng-template>
                  <ng-template #selectedItem let-product>
                    <span>{{ product.name_ar }}</span>
                  </ng-template>
                </p-select>
                @if (getProductBarcode(item.get('product_id')?.value); as bc) {
                  <div class="row-barcode"><i class="pi pi-barcode"></i> {{ bc }}</div>
                }
              </td>
              <td>
                <p-select
                  formControlName="unit_id"
                  [options]="(units$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [placeholder]="'PURCHASES.UNIT' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                />
              </td>
              <td>
                <p-inputNumber formControlName="quantity" [min]="0.01" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="unit_cost" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="discount_percent" [min]="0" [max]="100" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="2" [style]="{ width: '100%' }" suffix="%" />
              </td>
              <td>
                <p-select
                  formControlName="tax_rate_id"
                  [options]="(taxRates$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [showClear]="true"
                  [placeholder]="'PURCHASES.TAX' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                />
              </td>
              <td class="amount line-total-cell">
                {{ getLineTotal(i) | number:'1.2-2' }}
              </td>
              <td>
                <p-button
                  icon="pi pi-times"
                  [rounded]="true"
                  [text]="true"
                  severity="danger"
                  (onClick)="removeItem(i)"
                  [disabled]="items.length <= 1"
                  size="small"
                />
              </td>
            </tr>
          }
        </tbody>
      </table>

      @if (items.length === 0) {
        <div class="no-items">{{ 'PURCHASES.NO_ITEMS' | translate }}</div>
      }
    </div>

    <!-- Totals Section -->
    <div class="totals-section">
      <div class="totals-row">
        <span class="totals-label">{{ 'PURCHASES.SUBTOTAL' | translate }}</span>
        <span class="totals-value">{{ subtotal | number:'1.2-2' }}</span>
      </div>
      <div class="totals-row">
        <span class="totals-label">{{ 'PURCHASES.DISCOUNT_AMOUNT' | translate }}</span>
        <span class="totals-value discount">- {{ discountAmount | number:'1.2-2' }}</span>
      </div>
      <div class="totals-row grand-total">
        <span class="totals-label">{{ 'PURCHASES.TOTAL' | translate }}</span>
        <span class="totals-value">{{ total | number:'1.2-2' }}</span>
      </div>
    </div>

    <!-- Notes -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.NOTES' | translate }}</label>
        <textarea pTextarea formControlName="notes" rows="2"></textarea>
      </div>
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
        <textarea pTextarea formControlName="notes_ar" rows="2"></textarea>
      </div>
    </div>
  </form>
  <div class="dialog-custom-footer">
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="dialogVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSave()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
  </div>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog
  [header]="'PURCHASES.PURCHASE_ORDER' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '900px' }"
  [closable]="true"
>
  @if (viewingOrder(); as o) {
    <div class="view-order">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'PURCHASES.ORDER_NUMBER' | translate }}</label>
          <span class="mono">{{ o.order_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'PURCHASES.DATE' | translate }}</label>
          <span>{{ o.date }}</span>
        </div>
        @if (o.expected_delivery_date) {
          <div class="info-item">
            <label>{{ 'PURCHASES.EXPECTED_DELIVERY' | translate }}</label>
            <span>{{ o.expected_delivery_date }}</span>
          </div>
        }
        <div class="info-item">
          <label>{{ 'PURCHASES.STATUS' | translate }}</label>
          <p-tag
            [value]="getStatusLabel(o.status)"
            [severity]="getStatusSeverity(o.status)"
          />
        </div>
        @if (o.receive_status) {
          <div class="info-item">
            <label>{{ 'PURCHASES.RECEIVE_STATUS' | translate }}</label>
            <p-tag
              [value]="getStatusLabel(o.receive_status)"
              [severity]="getStatusSeverity(o.receive_status)"
              [rounded]="true"
            />
          </div>
        }
        @if (o.bill_status) {
          <div class="info-item">
            <label>{{ 'PURCHASES.BILL_STATUS' | translate }}</label>
            <p-tag
              [value]="getStatusLabel(o.bill_status)"
              [severity]="getStatusSeverity(o.bill_status)"
              [rounded]="true"
            />
          </div>
        }
        <div class="info-item">
          <label>{{ 'PURCHASES.SUPPLIER' | translate }}</label>
          <span>{{ o.supplier_name }}</span>
        </div>
        @if (o.warehouse_name) {
          <div class="info-item">
            <label>{{ 'PURCHASES.WAREHOUSE' | translate }}</label>
            <span>{{ o.warehouse_name }}</span>
          </div>
        }
        @if (o.purchase_request_number) {
          <div class="info-item">
            <label>{{ 'PURCHASES.PR_NUMBER' | translate }}</label>
            <span class="mono">{{ o.purchase_request_number }}</span>
          </div>
        }
        @if (o.reference) {
          <div class="info-item">
            <label>{{ 'PURCHASES.REFERENCE' | translate }}</label>
            <span>{{ o.reference }}</span>
          </div>
        }
        <div class="info-item">
          <label>{{ 'PURCHASES.CURRENCY' | translate }}</label>
          <span>{{ o.currency_code }}</span>
        </div>
      </div>

      @if (o.notes || o.notes_ar) {
        <div class="view-description">
          @if (o.notes) {
            <label>{{ 'PURCHASES.NOTES' | translate }}</label>
            <p>{{ o.notes }}</p>
          }
          @if (o.notes_ar) {
            <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
            <p>{{ o.notes_ar }}</p>
          }
        </div>
      }

      <table class="view-lines-table">
        <thead>
          <tr>
            <th>#</th>
            <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
            <th>{{ 'PURCHASES.UNIT' | translate }}</th>
            <th>{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th>{{ 'PURCHASES.RECEIVED' | translate }}</th>
            <th>{{ 'PURCHASES.BILLED' | translate }}</th>
            <th>{{ 'PURCHASES.UNIT_COST' | translate }}</th>
            <th>{{ 'PURCHASES.DISCOUNT' | translate }}</th>
            <th>{{ 'PURCHASES.LINE_TOTAL' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (item of o.items; track $index) {
            <tr>
              <td>{{ $index + 1 }}</td>
              <td>{{ item.product_name }}</td>
              <td>{{ item.unit_name }}</td>
              <td class="amount">{{ item.quantity }}</td>
              <td class="amount">{{ item.received_quantity }}</td>
              <td class="amount">{{ item.billed_quantity }}</td>
              <td class="amount">{{ item.unit_cost | number:'1.2-2' }}</td>
              <td class="amount">{{ item.discount_percent }}%</td>
              <td class="amount">{{ item.line_total | number:'1.2-2' }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr>
            <td colspan="7"></td>
            <td><strong>{{ 'PURCHASES.SUBTOTAL' | translate }}</strong></td>
            <td class="amount"><strong>{{ o.subtotal | number:'1.2-2' }}</strong></td>
          </tr>
          @if (+o.discount_amount > 0) {
            <tr>
              <td colspan="7"></td>
              <td>{{ 'PURCHASES.DISCOUNT_AMOUNT' | translate }}</td>
              <td class="amount discount">- {{ o.discount_amount | number:'1.2-2' }}</td>
            </tr>
          }
          @if (+o.tax_amount > 0) {
            <tr>
              <td colspan="7"></td>
              <td>{{ 'PURCHASES.TAX_AMOUNT' | translate }}</td>
              <td class="amount">{{ o.tax_amount | number:'1.2-2' }}</td>
            </tr>
          }
          <tr class="grand-total-row">
            <td colspan="7"></td>
            <td><strong>{{ 'PURCHASES.TOTAL' | translate }}</strong></td>
            <td class="amount"><strong>{{ o.total | number:'1.2-2' }}</strong></td>
          </tr>
        </tfoot>
      </table>
    </div>
  }
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CLOSE' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="viewDialogVisible.set(false)"
    />
  </ng-template>
</p-dialog>

<!-- Quick Add Supplier Dialog -->
<p-dialog
  [header]="'PURCHASES.ADD_SUPPLIER' | translate"
  [(visible)]="quickAddVisible"
  [modal]="true"
  [style]="{ width: '420px' }"
  [closable]="true"
>
  <form [formGroup]="quickAddForm" class="quick-add-form" style="display: flex; flex-direction: column; gap: 1rem;">
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_AR' | translate }} *</label>
      <input pInputText formControlName="name_ar" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.NAME_EN' | translate }}</label>
      <input pInputText formControlName="name_en" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.PHONE' | translate }}</label>
      <input pInputText formControlName="phone" style="width: 100%" />
    </div>
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem;">{{ 'PARTNERS.EMAIL' | translate }}</label>
      <input pInputText formControlName="email" style="width: 100%" type="email" />
    </div>
  </form>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="quickAddVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="saveQuickSupplier()"
      [loading]="quickAddSaving()"
    />
  </ng-template>
</p-dialog>

<!-- Create GRN Dialog -->
<p-dialog
  [header]="'PURCHASES.CREATE_GRN' | translate"
  [(visible)]="grnDialogVisible"
  [modal]="true"
  [style]="{ width: '650px' }"
  [closable]="true"
>
  <div style="margin-bottom: 1rem;">
    <label style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">{{ 'PURCHASES.WAREHOUSE' | translate }} *</label>
    <p-select
      [options]="(warehouses$ | async) || []"
      optionLabel="name"
      optionValue="id"
      [ngModel]="grnWarehouseId()"
      (ngModelChange)="grnWarehouseId.set($event)"
      [placeholder]="'PURCHASES.WAREHOUSE' | translate"
      [style]="{ width: '100%' }"
      appendTo="body"
    />
  </div>
  <table class="view-lines-table" style="width: 100%;">
    <thead>
      <tr>
        <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
        <th>{{ 'PURCHASES.REMAINING' | translate }}</th>
        <th>{{ 'PURCHASES.QUANTITY' | translate }}</th>
      </tr>
    </thead>
    <tbody>
      @for (item of grnItems(); track item.item_id; let i = $index) {
        <tr>
          <td>{{ item.product_name }}</td>
          <td class="amount">{{ item.remaining }}</td>
          <td>
            <p-inputNumber
              [(ngModel)]="grnItems()[i].quantity"
              [min]="0"
              [max]="item.remaining"
              [style]="{ width: '100%' }"
            />
          </td>
        </tr>
      }
    </tbody>
  </table>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="grnDialogVisible.set(false)"
    />
    <p-button
      [label]="'PURCHASES.CREATE_GRN' | translate"
      icon="pi pi-check"
      (onClick)="saveGrn()"
      [loading]="grnSaving()"
      [disabled]="!grnWarehouseId()"
    />
  </ng-template>
</p-dialog>

<!-- Create Bill Dialog -->
<p-dialog
  [header]="'PURCHASES.CREATE_BILL' | translate"
  [(visible)]="billDialogVisible"
  [modal]="true"
  [style]="{ width: '650px' }"
  [closable]="true"
>
  <table class="view-lines-table" style="width: 100%;">
    <thead>
      <tr>
        <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
        <th>{{ 'PURCHASES.REMAINING' | translate }}</th>
        <th>{{ 'PURCHASES.QUANTITY' | translate }}</th>
      </tr>
    </thead>
    <tbody>
      @for (item of billItems(); track item.item_id; let i = $index) {
        <tr>
          <td>{{ item.product_name }}</td>
          <td class="amount">{{ item.remaining }}</td>
          <td>
            <p-inputNumber
              [(ngModel)]="billItems()[i].quantity"
              [min]="0"
              [max]="item.remaining"
              [style]="{ width: '100%' }"
            />
          </td>
        </tr>
      }
    </tbody>
  </table>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="billDialogVisible.set(false)"
    />
    <p-button
      [label]="'PURCHASES.CREATE_BILL' | translate"
      icon="pi pi-check"
      (onClick)="saveBill()"
      [loading]="billSaving()"
    />
  </ng-template>
</p-dialog>
